Technology stack

NestJS +MySQL + TypeORM + apollo-GraphQL

Project structures,

  • Install @nest/ CLI scaffolding to build the project
npm i -g @nest/cli
Copy the code
  • Generating project
nest new nest-test
cd ./nest-test

Copy the code
  • Start the project
yarn start:dev
Copy the code

After the startup is complete, the default address is http://localhost:3000/, and you can see the familiar Hello World! ;

Connect to MySQl database

TypeORM is used as database entity mapping tool, which can simplify database connection and CRUD operation.

  • TypeORM Official Introduction and documentation: TypeORM document (Chinese can be changed in the upper right corner)
  • Guide to using TypeORM under the NestJS framework: @nestjs/ TypeORM documentation

Install dependencies

yarn add @nestjs/typeorm typeorm mysql
Copy the code

insrc/app.module.tsTo configure the database connection

import { join } from 'path'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ "type": "mysql", "host": "localhost", "port": 3306, "username": "root", "password": "sql", "database": "typeorm", "entities": [join(__dirname, '**/entity/*.{ts,js}')], "synchronize": ForRoot ({autoSchemaFile: './schema.gql', // code first}),],})Copy the code

Description:

  • You need to create an empty database in mysql beforehandtypeorm;
  • In the TypeOrmModule configuration above we set the file path for database entity mapping to**/entity/*.{ts,js};
  • For ease of development, setsynchronize: trueTypeorm automatically generates entity class definitions in mysqlCollections, thus eliminating the need to manually set up Collections;

GraphQL configuration

Install dependencies

yarn add @nestjs/graphql graphql-tools graphql apollo-server-express
Copy the code

insrc/app.module.tsIn the configuration GraphQL

There are two strategies for developing GraphQL in the NestJS framework. One is to write the entity class definition firstCode first(Code FirstThe other way is to write firstschema.gqltheArchitecture first(Schema First); Specific see individual be fond of and development style.

import { GraphQLModule } from '@nestjs/graphql'; @Module({imports: [GraphqlModule. forRoot({autoSchemaFile: './schema.gql', // code first}),],})Copy the code

Develop business modules

Specific file directories are as follows:

Write the corresponding service code to start the service: YARN start:dev

Start to finish to visit http://localhost:3000/graphql, open GraphQL Playground can