{"id":20340894,"url":"https://github.com/nbaua/codefirstgraphqlnestjs","last_synced_at":"2026-04-29T21:36:59.789Z","repository":{"id":120255000,"uuid":"287463442","full_name":"nbaua/CodeFirstGraphQLNestJS","owner":"nbaua","description":"Simple TypeScript application showing the Code First approach for a NestJS-GraphQL project.","archived":false,"fork":false,"pushed_at":"2020-08-14T12:58:08.000Z","size":432,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-04T14:49:29.174Z","etag":null,"topics":["codefirst","graphql","nestjs","nestjs-backend","nestjs-graphql","typeorm"],"latest_commit_sha":null,"homepage":"https://github.com/nbaua/CodeFirstGraphQLNestJS","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nbaua.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-14T06:43:49.000Z","updated_at":"2021-02-24T14:54:49.000Z","dependencies_parsed_at":null,"dependency_job_id":"4408c1e6-7e82-4851-8eea-2e083bef8bf7","html_url":"https://github.com/nbaua/CodeFirstGraphQLNestJS","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/nbaua/CodeFirstGraphQLNestJS","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nbaua%2FCodeFirstGraphQLNestJS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nbaua%2FCodeFirstGraphQLNestJS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nbaua%2FCodeFirstGraphQLNestJS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nbaua%2FCodeFirstGraphQLNestJS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nbaua","download_url":"https://codeload.github.com/nbaua/CodeFirstGraphQLNestJS/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nbaua%2FCodeFirstGraphQLNestJS/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27439791,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-01T02:00:06.371Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codefirst","graphql","nestjs","nestjs-backend","nestjs-graphql","typeorm"],"created_at":"2024-11-14T21:24:33.025Z","updated_at":"2025-12-01T22:06:44.766Z","avatar_url":"https://github.com/nbaua.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Description\r\n\r\nTypeScript-NestJS-GraphQL Code First Repository.\r\n\r\n## Installation\r\n\r\n### Install NestJS if not installed already\r\n\r\n    npm i -g @nestjs/cli\r\n\r\n### Create the NestJS application\r\n\r\n    nest new graphql-codefirst-nest\r\n\r\n`REQUIRED: Change to the project directory`\r\n\r\n`OPTIONAL: Run the Nest Application to test if everything is working fine.`\r\n\r\n### Install the required NPM packages\r\n\r\n    npm i --save @nestjs/typeorm typeorm mysql dotenv\r\n    npm i --save @nestjs/graphql graphql-tools graphql\r\n    npm i --save apollo-server-express @nestjs/common\r\n\r\n### Enable the GraphQL code first approach\r\n\r\nEnter the following code in `app.module.ts` under imports[]\r\n\r\n```\r\nGraphQLModule.forRoot({\r\n      autoSchemaFile: 'schema.gql',\r\n      debug: false,\r\n      playground: true,\r\n    }),\r\n```\r\n\r\n### Prepare the Environment\r\n\r\n`Create the .env file with required key-value pairs, the following is the minimal required environment variables for this project.`\r\n\r\n```\r\nAPP_PORT=3001\r\nDB_HOST=localhost\r\nDB_PORT=3306\r\nDB_USERNAME=root\r\nDB_PASSWORD=***********\r\nDB_NAME=jobs-db\r\nDB_SYNC=false\r\n```\r\n\r\n### Add TypeORM to the project\r\n\r\n\u003e Use the following to read the .env file correctly\r\n\u003e\r\n\u003e `require('dotenv').config();`\r\n\r\nEnter the following code in `app.module.ts` under imports[],\r\n\r\n```\r\nTypeOrmModule.forRoot({\r\n      type: 'mysql',\r\n      host: process.env.DB_HOST,\r\n      port: +process.env.DB_PORT,\r\n      username: process.env.DB_USERNAME,\r\n      password: process.env.DB_PASSWORD,\r\n      database: process.env.DB_NAME,\r\n      entities: ['dist/**/*.model.js'],\r\n      synchronize: process.env.DB_SYNC === 'true' ? true : false,\r\n    }),\r\n```\r\n\r\n`At this point compiling the project would result in the error since there is no graphql schema is defined. The purpose of the code first approach is to auto-generate this required file automatically based on the code we develop further.`\r\n\r\n\u003e IF YOU GET THIS ERROR\r\n\r\n\u003cmark\u003eError: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client\u003c/mark\u003e\r\n\r\n\u003e CONSIDER ADDING THE USER AN ACCESS TO YOUR DATABASE\r\n\r\n## Development\r\n\r\n\u003e `Step1: Generate Required Artifacts and Reference them in App Module`\r\n\r\n\u003e `Step2: Create data models for TypeORM and GraphQL Entity mapping.`\r\n\r\n\u003e `Step3: Implement the resolvers and services with required API operations.`\r\n\r\n### Generate Required Resolvers, Services, and Modules\r\n\r\n```\r\nnest g resolver company --no-spec\r\nnest g resolver employee --no-spec\r\nnest g service company --no-spec\r\nnest g service employee --no-spec\r\nnest g module company\r\nnest g module employee\r\n```\r\n\r\nThe above command should generate required `skeleton` files under the directory named same as the module name.\r\n\r\n`Update the Company Module with the following code and reference correctly.`\r\n\r\n```\r\n@Module({\r\n  imports: [TypeOrmModule.forFeature([CompanyModel])],\r\n  providers: [CompanyService, CompanyResolver],\r\n  exports: [CompanyService],\r\n})\r\nexport class CompanyModule {}\r\n\r\n```\r\n\r\n`Update the Employee Module with the following code and reference correctly.`\r\n\r\n```\r\n@Module({\r\n  imports: [TypeOrmModule.forFeature([EmployeeModel])],\r\n  providers: [EmployeeService, EmployeeResolver],\r\n  exports: [EmployeeService],\r\n})\r\nexport class EmployeeModule {}\r\n```\r\n\r\n\u003e `Update the App Module with the Company and Employee Module reference under the imports[].`\r\n\r\nThe updated App Module should look like\r\n\r\n```\r\n\r\n@Module({\r\n  imports: [\r\n    TypeOrmModule.forRoot({\r\n      type: 'mysql',\r\n      host: process.env.DB_HOST,\r\n      port: +process.env.DB_PORT,\r\n      username: process.env.DB_USERNAME,\r\n      password: process.env.DB_PASSWORD,\r\n      database: process.env.DB_NAME,\r\n      entities: ['dist/**/*.model.js'],\r\n      synchronize: process.env.DB_SYNC === 'true' ? true : false,\r\n    }),\r\n    GraphQLModule.forRoot({\r\n      autoSchemaFile: 'schema.gql',\r\n      debug: false,\r\n      playground: true,\r\n    }),\r\n    EmployeeModule,\r\n    CompanyModule,\r\n  ],\r\n  controllers: [],\r\n  providers: [],\r\n})\r\nexport class AppModule {}\r\n\r\n```\r\n\r\n### Add Database Model and GraphQL Entity Support\r\n\r\n\u003e \\+ Create the `company.model.ts` file under the `company` directory, add and export\r\n\u003e the class `CompanyModel` from within the file.\r\n\u003e\r\n\u003e \\+ Create the `employee.model.ts` file under the `employee` directory, add and export the class `EmployeeModel` from within the file.\r\n\u003e\r\n\u003e \\+ Add column/field names of the `company` and `employee` tables respectively in above classes.\r\n\u003e\r\n\u003e \\+ Mark them with the `@Field()` decorator for the GraphQL schema generation\r\n\u003e\r\n\u003e \\+ Mark them with the `@Column()` decorator for the TypeORM support\r\n\u003e\r\n\u003e \\+ OPTIONAL: Add TypeORM @JoinColumn() and OneToMany()/@ManyToOne() relation decorators, if the APIs needs to fetch the nested/related data.\r\n\r\nThe updated `company.model.ts` file should look as under, check the source code for `employee.model.ts` for the counter part.\r\n\r\n```\r\n\r\n@ObjectType()\r\n@Entity('company')\r\nexport class CompanyModel {\r\n  @Field()\r\n  @PrimaryGeneratedColumn()\r\n  id: number;\r\n\r\n  @Field({ name: 'name' })\r\n  @Column('varchar', { length: 50, nullable: false })\r\n  name: string;\r\n\r\n  @Field(type =\u003e [EmployeeModel], { nullable: true })\r\n  @OneToMany(\r\n    type =\u003e EmployeeModel,\r\n    employee =\u003e employee.company,\r\n    { lazy: true },\r\n  )\r\n  @JoinColumn({ name: 'id' })\r\n  employees: EmployeeModel[];\r\n}\r\n```\r\n\r\n\u003e NOTE that the class is decorated with `@ObjectType()` and `@Entity()`. Specify the table name to the @Entity decorator to correctly generate the query by TypeORM.\r\n\r\n\u003e For GraphQL to map the data correctly with other relational entities (TypeORM Entities) it is mandatory to specify the `{ lazy: true },` attribute in the relations, Otherwise the result will always return `null`.\r\n\r\n### Implement the Resolvers and Services\r\n\r\n\u003e \\+ Inject the service reference in the resolver classes\r\n\r\n\u003e \\+ Add the endpoints and implement the service counter parts\r\n\r\nThe implemented `company.resolver.ts` looks like\r\n\r\n```\r\n\r\n@Resolver(of =\u003e CompanyModel)\r\nexport class CompanyResolver {\r\n  constructor(@Inject(CompanyService) private CompanyService: CompanyService) {}\r\n\r\n  @Query(returns =\u003e CompanyModel)\r\n  async Company(@Args('id') id: string): Promise\u003cCompanyModel\u003e {\r\n    return await this.CompanyService.findOneCompany(id);\r\n  }\r\n\r\n  @Query(returns =\u003e CompanyModel)\r\n  async Companies(): Promise\u003cCompanyModel[]\u003e {\r\n    return await this.CompanyService.findAllCompanies();\r\n  }\r\n}\r\n\r\n```\r\n\r\nThe implemented `company.service.ts` looks like\r\n\r\n```\r\n\r\n@Injectable()\r\nexport class CompanyService {\r\n  constructor(\r\n    @InjectRepository(CompanyModel)\r\n    private CompanyRepository: Repository\u003cCompanyModel\u003e,\r\n  ) {}\r\n\r\n  findOneCompany(id: string): Promise\u003cCompanyModel\u003e {\r\n    return this.CompanyRepository.findOne(id);\r\n  }\r\n\r\n  findAllCompanies(): Promise\u003cCompanyModel[]\u003e {\r\n    return this.CompanyRepository.find();\r\n  }\r\n}\r\n\r\n```\r\n\r\nCheck the source code for `employee.resolver.ts` and `employee.service.ts` for the\r\ncounter part.\r\n\r\n### Seed the data (For now)\r\n\r\n\u003e Import the seed data into the MySQL tables\r\n\r\n### Build and test the project\r\n\r\n```\r\nnpm run build\r\nOR\r\nnest build\r\n```\r\n\r\nThe above command will build the project and generate a `dist` directory.\r\n\r\n```\r\nnpm run start\r\nOR\r\nnest start\r\n```\r\n\r\nThe above command will start the Nest Application and the GraphQL Playground can be accessed at following URL.\r\n\r\n`http://localhost:3001/graphql`\r\n\r\n`Company API`\r\n\r\n![Company](https://github.com/nbaua/CodeFirstGraphQLNestJS/blob/master/images/company.PNG?raw=true)\r\n\r\n`Employee API`\r\n\r\n![Employee](https://github.com/nbaua/CodeFirstGraphQLNestJS/blob/master/images/employee.PNG?raw=true)\r\n\r\n## ToDo\r\n\r\nThis project is a boilerplate code for anyone to start with the Code First NestJS and GraphQL APIs using TypeORM. The following thing are still needs to be implemented.\r\n\r\n- Add other CRUD operations\r\n- Add exception handling\r\n- Add validations\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnbaua%2Fcodefirstgraphqlnestjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnbaua%2Fcodefirstgraphqlnestjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnbaua%2Fcodefirstgraphqlnestjs/lists"}