Configurazione di NestJS e Graphql

Feb 01 2023
Impara il backend con la tua conoscenza del frontend Ciao a tutti, bentornati nel mio blog . Spero che stiate tutti bene e che questo blog vi trovi in ​​buona salute ❤️.

Impara il backend con la tua conoscenza del frontend

Ciao a tutti, bentornati nel mio blog .
Spero che stiate tutti bene e che questo blog vi trovi in ​​buona salute ❤️.

Sommario
·
Introduzione
·
Installazione e configurazione del progetto
·
Generazione di risorse
·
Tipi di file e loro importanza
∘
module.ts
∘
entity/entity.ts
∘
resolver.ts / controller.ts
∘
service.ts
∘
graphql
∘
dto/input .ts

introduzione

Prima di iniziare con il nostro argomento principale, conosciamo NestJS.
NestJS è un framework Node che supporta sia Typescript che Javascript.
Le persone che provengono da Backend possono trovarlo simile al framework Spring.
Per le persone front-end come noi, la creazione di API con un framework che può essere scritto in JS/TS è affascinante e ho davvero imparato molto nella mia esplorazione di questo framework.

Configurazione di NestJS e Graphql

Non è che non possiamo creare API utilizzando Node, ma NestJS semplifica la creazione di API in Typescript e Javascript.

Questo blog può essere considerato un inizio per NestJS e la creazione di API con Graphql.

Installazione e impostazione del tuo progetto

# Step 1: Install NestJs globally in your local machine
npm i -g @nestjs/cli

# Step 2: Create a new Project
nest new project-name

# Step 3: Choose your Package Manager
? Which package manager would you ❤️  to use? (Use arrow keys)
❯ npm
  yarn
  pnpm

# Step 4: Wait for the packages to get installed in your machine.

Note: NestJS application starts from main.ts

Installazione delle librerie GraphQL

# Step 5: Install Graphql libraries
npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express

import { ApolloDriver } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';

@Module({
  imports: [
    GraphQLModule.forRoot({
      driver: ApolloDriver,
      typePaths: ['./**/*.graphql'],
      definitions: {
        path: join(process.cwd(), 'src/graphql.schema.ts'),
      },
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

NestJS e Angular condividono una struttura di progetto simile. Possiamo generare Risorse in 2 modi

  • Creazione manuale di file come modulo, resolver, dto, controller, ecc.
  • Creazione del modulo utilizzando il comando
  • # Creating modules using command
    nest generate resource resource-name
    (OR)
    nest g resource resource-name
    
    # Choose your transport layer e.g. as we are using graphql go with either 2 or 3
    ? What transport layer do you use? (Use arrow keys)
    ❯ REST API 
      GraphQL (code first) 
      GraphQL (schema first) 
      Microservice (non-HTTP) 
      WebSockets 
    
    # Prompts to generate CRUD Operations for your resource
    ? Would you like to generate CRUD entry points? (Y/n)
    
    

    Code First: 
      Our code drives our development, Schema gets created later based on our code.
    
    Schema First: 
      Based on Schema, code is developed.
    

Altri modi per generare file

# Generating the module file of your resource
nest g mo module-name

# Generating controllers, resources, etc
nest g co controller-name

# Generating service file
nest g s service-name

Ora che abbiamo generato le nostre risorse, capiamo cosa sono quei file e perché ne abbiamo bisogno.

modulo.ts

Poiché abbiamo main.js come voce per la nostra applicazione, allo stesso modo abbiamo anche un punto di ingresso per la nostra risorsa che è module.ts. Ogni altro file nella risorsa è definito qui.

# Example module.ts
import { Module } from '@nestjs/common';
import { CarService } from './car.service';
import { CarResolver } from './car.resolver';

@Module({
  providers: [CarResolver, CarService]
})
export class CarModule {}

Questa cartella è specifica per le tabelle che dovrebbero essere generate nel nostro database. Supponiamo che tu voglia generare una tabella nel tuo database Postgres, potremmo specificare quali colonne, i loro tipi e anche le chiavi primarie possono essere definite in questo particolare file.

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity('car-table')
export class Car {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column('varchar', { length: 500 })
  name: string;
}

Questo file è specifico per i nostri endpoint API.
resolver.ts - When we use graphql as transport layer.
controller.ts- When we use REST as transport layer.

import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { CarService } from './car.service';
import { CreateCarInput } from './dto/create-car.input';
import { UpdateCarInput } from './dto/update-car.input';

@Resolver('Car')
export class CarResolver {
  constructor(private readonly carService: CarService) {}

  @Mutation('createCar')
  create(@Args('createCarInput') createCarInput: CreateCarInput) {
    return this.carService.create(createCarInput);
  }

  @Query('car')
  findAll() {
    return this.carService.findAll();
  }

  @Mutation('updateCar')
  update(@Args('updateCarInput') updateCarInput: UpdateCarInput) {
    return this.carService.update(updateCarInput.id, updateCarInput);
  }
}

La connessione al database effettiva e la logica aziendale vengono inserite qui. questo sarà collegato con i risolutori.

import { Injectable } from '@nestjs/common';
import { CreateCarInput } from './dto/create-car.input';

@Injectable()
export class CarService {
  create(createCarInput: CreateCarInput) {
    return 'This action adds a new car';
  }

  findAll() {
    return `This action returns all car`;
  }
}

Questo file contiene lo schema per il nostro modulo come qual è il tipo di richiesta e quale sarà il tipo di risposta che restituisce.

type Car {
  id: ID
  name: String
}

input CreateCarInput {
  name: String!
}
type Query {
  car: [Car]!
  car(id: Int!): Car
}

type Mutation {
  createCar(createCarInput: CreateCarInput!): Car!
}

Ecco il nostro ultimo file, questo file è specifico per gli input utilizzati nella risorsa.

import { Field, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class CreateCarDto {
  @Field() readonly id?: string;
  @Field() readonly name: string;
}

Ci siamo, questo è tutto gente per questo blog.
Spero che questo blog sia piaciuto a tutti.
Se ti piace, dagli un applauso
e condividilo con il tuo amico.

Nel mio prossimo blog, esploreremo le connessioni al database e anche la creazione di API.
Si prega di rimanere sintonizzati per lo stesso...

Per contenuti più entusiasmanti su Frontend, seguimi .

Grazie mille, tutti .
Alla prossima volta,
Buon apprendimento ✍️

Abhishek Kovuri , sviluppatore dell'interfaccia utente