How to connect GraphQL API & Nest JS backend with MySQL/PgSQL database?
Published: 2024-06-04 05:25:31

Connecting a GraphQL NestJS backend with MySQL and PostgreSQL databases involves several steps. Here’s a step-by-step guide for both databases:

### Step 1: Setup a New NestJS Project
1. **Install Nest CLI**:
   ```bash
   npm install -g @nestjs/cli
   ```
2. **Create a New Project**:
   ```bash
   nest new project-name
   ```
3. **Navigate to the Project Directory**:
   ```bash
   cd project-name
   ```

### Step 2: Install Required Packages
1. **Install TypeORM and GraphQL Packages**:
   ```bash
   npm install @nestjs/typeorm typeorm @nestjs/graphql graphql apollo-server-express
   ```
2. **Install Database Drivers**:
   For MySQL:
   ```bash
   npm install mysql2
   ```
   For PostgreSQL:
   ```bash
   npm install pg
   ```

### Step 3: Configure TypeORM and GraphQL
1. **Create a GraphQL Module Configuration**:
   Open `src/app.module.ts` and configure the GraphQL module:
   ```typescript
   import { Module } from '@nestjs/common';
   import { TypeOrmModule } from '@nestjs/typeorm';
   import { GraphQLModule } from '@nestjs/graphql';
   import { join } from 'path';
   import { UserModule } from './user/user.module';

   @Module({
     imports: [
       TypeOrmModule.forRoot({
         type: 'mysql', // or 'postgres'
         host: 'localhost',
         port: 3306, // or 5432 for PostgreSQL
         username: 'root', // or your PostgreSQL username
         password: 'password', // or your PostgreSQL password
         database: 'test',
         entities: [__dirname + '/**/*.entity{.ts,.js}'],
         synchronize: true,
       }),
       GraphQLModule.forRoot({
         autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
       }),
       UserModule,
     ],
   })
   export class AppModule {}
   ```

### Step 4: Define the User Entity
1. **Create a User Entity**:
   Create the `src/user/user.entity.ts` file:
   ```typescript
   import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
   import { ObjectType, Field, Int } from '@nestjs/graphql';

   @ObjectType()
   @Entity()
   export class User {
     @Field(type => Int)
     @PrimaryGeneratedColumn()
     id: number;

     @Field()
     @Column()
     name: string;

     @Field()
     @Column()
     email: string;
   }
   ```

### Step 5: Create the User Service
1. **Implement Service Logic**:
   Open `src/user/user.service.ts` and implement the service methods:
   ```typescript
   import { Injectable } from '@nestjs/common';
   import { InjectRepository } from '@nestjs/typeorm';
   import { Repository } from 'typeorm';
   import { User } from './user.entity';

   @Injectable()
   export class UserService {
     constructor(
       @InjectRepository(User)
       private usersRepository: Repository<User>,
     ) {}

     findAll(): Promise<User[]> {
       return this.usersRepository.find();
     }

     findOne(id: number): Promise<User> {
       return this.usersRepository.findOneBy({ id });
     }

     create(user: Partial<User>): Promise<User> {
       return this.usersRepository.save(user);
     }

     async update(id: number, user: Partial<User>): Promise<User> {
       await this.usersRepository.update(id, user);
       return this.usersRepository.findOneBy({ id });
     }

     async delete(id: number): Promise<void> {
       await this.usersRepository.delete(id);
     }
   }
   ```

### Step 6: Create the User Resolver
1. **Generate a Resolver**:
   Use the Nest CLI to generate a resolver:
   ```bash
   nest g resolver user
   ```

2. **Define Resolver Logic**:
   Open `src/user/user.resolver.ts` and define the resolver logic:
   ```typescript
   import { Resolver, Query, Mutation, Args, Int } from '@nestjs/graphql';
   import { UserService } from './user.service';
   import { User } from './user.entity';
   import { CreateUserInput } from './dto/create-user.input';

   @Resolver(of => User)
   export class UserResolver {
     constructor(private readonly userService: UserService) {}

     @Query(returns => [User])
     users() {
       return this.userService.findAll();
     }

     @Query(returns => User)
     user(@Args('id', { type: () => Int }) id: number) {
       return this.userService.findOne(id);
     }

     @Mutation(returns => User)
     createUser(@Args('createUserInput') createUserInput: CreateUserInput) {
       return this.userService.create(createUserInput);
     }

     @Mutation(returns => User)
     updateUser(
       @Args('id', { type: () => Int }) id: number,
       @Args('updateUserInput') updateUserInput: CreateUserInput,
     ) {
       return this.userService.update(id, updateUserInput);
     }

     @Mutation(returns => Boolean)
     async deleteUser(@Args('id', { type: () => Int }) id: number) {
       await this.userService.delete(id);
       return true;
     }
   }
   ```

### Step 7: Create DTOs
1. **Create DTOs for User Input**:
   Create the `src/user/dto/create-user.input.ts`:
   ```typescript
   import { InputType, Field } from '@nestjs/graphql';

   @InputType()
   export class CreateUserInput {
     @Field()
     name: string;

     @Field()
     email: string;
   }
   ```

### Step 8: Update the User Module
1. **Update the User Module**:
   Open `src/user/user.module.ts` and update it to include the controller and service:
   ```typescript
   import { Module } from '@nestjs/common';
   import { TypeOrmModule } from '@nestjs/typeorm';
   import { User } from './user.entity';
   import { UserService } from './user.service';
   import { UserResolver } from './user.resolver';

   @Module({
     imports: [TypeOrmModule.forFeature([User])],
     providers: [UserService, UserResolver],
   })
   export class UserModule {}
   ```

### Step 9: Run the Application
1. **Start the NestJS Application**:
   ```bash
   npm run start:dev
   ```

### Step 10: Test the GraphQL API
1. **Access the GraphQL Playground**:
   Navigate to `http://localhost:3000/graphql` to access the GraphQL playground and test your API by running queries and mutations.

This guide provides a foundational approach to creating a GraphQL API in NestJS connected to MySQL or PostgreSQL databases. You can further expand and customize it based on your application's requirements.

Disclaimer: This content is generated by AI.