here is a step to follow in order to setup a backend development with TypeORM, MySQL
1. install NestJS CLI
yarn add -g @nestjs/cli
2. create a nestjs app
nest new my-project
3. install @nestjs/typerom typreorm mysql2 (mysql 2 is much typescript friendly than mysql)
yarn add @nestjs/typeorm typeorm mysql2
4. create a TypeORM config JSON file to store typeorm configuation.
touch ormconfig.json
5. paste the following into the ormconfig.json file
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "test",
"password": "test",
"database": "test",
"synchronize": true,
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
]
}
6. add @nestjs/config package to the project so that we can use ConfigureModule module to access the configuration file.
yarn add @nestjs/config
7. add a database module to the project
touch database.module.ts
8. add the following code the database.module.ts to setup the database connection.
9. add DatabaseModule to the app.module.ts file
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
10. execute yarn start to launch the project and you will see the DB connection had been established.
DB connected Successfully
[Nest] 16320 - 2021-07-10, 9:02:02 p.m. LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +26ms
[Nest] 16320 - 2021-07-10, 9:02:02 p.m. LOG [InstanceLoader] DatabaseModule dependencies initialized +1ms
[Nest] 16320 - 2021-07-10, 9:02:02 p.m. LOG [RoutesResolver] AppController {/}: +5ms
[Nest] 16320 - 2021-07-10, 9:02:02 p.m. LOG [RouterExplorer] Mapped {/, GET} route +3ms
[Nest] 16320 - 2021-07-10, 9:02:02 p.m. LOG [NestApplication] Nest application successfully started +2ms
11. add Graphql to the project
yarn add @nestjs/graphql graphql-tools graphql apollo-server-express
you might encounter missing package errors here, you can manually add them as following
yarn add ts-morph @apollo/gateway
12. add GraphQLModule to the app.module.ts to initialze GraphQL Module
Further reading
TypeORM - Amazing ORM for TypeScript and JavaScript ES7
No comments:
Post a Comment