☰ Mục lục series
Tài liệu NestJS tiếng Việt
  1. Nhập môn (Overview)
    1. Giới thiệu
    2. First steps
    3. Controllers
    4. Providers
    5. Modules
    6. Middleware
    7. Exception filters
    8. Pipes
    9. Guards
    10. Interceptors
    11. Custom decorators
  2. Nền tảng (Fundamentals)
    1. Custom providers
    2. Asynchronous providers
    3. Dynamic modules
    4. Injection scopes
    5. Circular dependency
    6. Module reference
    7. Lazy-loading modules
    8. Execution context
    9. Lifecycle events
    10. Discovery service
    11. Platform agnosticism
    12. Testing
  3. Kỹ thuật (Techniques)
    1. Configuration
    2. Database (SQL)
    3. MongoDB
    4. Validation
    5. Caching
    6. Serialization
    7. Versioning
    8. Task scheduling
    9. Queues
    10. Logging
    11. Cookies
    12. Events
    13. Compression
    14. File upload
    15. Streaming files
    16. HTTP module
    17. Session
    18. MVC
    19. Performance (Fastify)
    20. Server-Sent Events
  4. Bảo mật (Security)
    1. Authentication
    2. Authorization
    3. Encryption & Hashing
    4. Helmet
    5. CORS
    6. CSRF
    7. Rate limiting
    8. Vòng đời request
  5. OpenAPI (Swagger)
    1. Introduction
    2. Types and parameters
    3. Operations
    4. Security
    5. Mapped types
    6. Decorators
    7. CLI plugin
    8. Other features
  6. Recipes
    1. REPL
    2. CRUD generator
    3. SWC (fast compiler)
    4. Passport (auth)
    5. Hot reload
    6. MikroORM
    7. Router module
    8. Health checks (Terminus)
    9. CQRS
    10. Prisma
    11. Serve static
    12. Commander
    13. Async local storage
  7. WebSockets
    1. Gateways
    2. Exception filters
    3. Pipes
    4. Guards
    5. Interceptors
    6. Adapters
  8. Microservices
    1. Overview
    2. Redis
    3. MQTT
    4. NATS
    5. RabbitMQ
    6. Kafka
    7. gRPC
    8. Custom transporters
    9. Exception filters
    10. Pipes
    11. Pre-request hooks
    12. Guards
    13. Interceptors
  9. GraphQL
    1. Quick start
    2. Resolvers
    3. Mutations
    4. Subscriptions
    5. Scalars
    6. Directives
    7. Interfaces
    8. Unions and enums
    9. Field middleware
    10. Mapped types
    11. Plugins
    12. Complexity
    13. Extensions
    14. CLI plugin
    15. Generating SDL
    16. Sharing models
    17. Other features
    18. Federation
  10. CLI & triển khai
    1. CLI overview
    2. Workspaces
    3. Libraries
    4. Usage
    5. Scripts
    6. Deployment
    7. Standalone apps
  11. FAQ
    1. Serverless
    2. HTTP adapter
    3. Keep-Alive connections
    4. Global path prefix
    5. Raw body
    6. Hybrid application
    7. HTTPS & multiple servers
    8. Common errors
  12. Phụ lục
    1. Bảng thuật ngữ
GraphQL

Plugin với Apollo

Bản dịch từ docs.nestjs.com/graphql/plugins

Plugin cho phép bạn mở rộng các chức năng cốt lõi của Apollo Server bằng cách thực hiện các thao tác tùy chỉnh để phản hồi lại một số sự kiện nhất định. Hiện tại, các sự kiện này tương ứng với từng giai đoạn (phase) riêng lẻ trong vòng đời request GraphQL, cũng như sự kiện khởi động (startup) của chính Apollo Server (đọc thêm tại đây). Ví dụ, một plugin logging cơ bản có thể log lại chuỗi GraphQL query đi kèm mỗi request gửi tới Apollo Server.

Plugin tùy chỉnh

Để tạo một plugin, khai báo một class được gắn decorator @Plugin export từ package @nestjs/apollo. Ngoài ra, để có gợi ý code tốt hơn, hãy implement interface ApolloServerPlugin từ package @apollo/server.

import { ApolloServerPlugin, GraphQLRequestListener } from '@apollo/server';
import { Plugin } from '@nestjs/apollo';

@Plugin()
export class LoggingPlugin implements ApolloServerPlugin {
  async requestDidStart(): Promise<GraphQLRequestListener<any>> {
    console.log('Request started');
    return {
      async willSendResponse() {
        console.log('Will send response');
      },
    };
  }
}

Với đoạn code này, ta có thể đăng ký LoggingPlugin như một provider.

@Module({
  providers: [LoggingPlugin],
})
export class CommonModule {}

Nest sẽ tự động khởi tạo plugin và áp dụng nó vào Apollo Server.

Ghi chú người dịch Cơ chế này giống hệt cách @Injectable() hoạt động với các provider thông thường trong Nest — bạn không tự tạo instance của plugin bằng tay, IoC container sẽ lo việc đó (kèm khả năng inject dependency vào constructor của plugin) rồi tự “gắn” nó vào Apollo Server dưới hậu trường. Khác với việc gọi trực tiếp server.addPlugin(...) như khi dùng Apollo Server thuần, ở đây bạn chỉ cần khai báo decorator và đưa vào providers, phần còn lại Nest tự lo.

Dùng plugin có sẵn

Có sẵn nhiều plugin được cung cấp out-of-the-box. Để dùng một plugin có sẵn, chỉ cần import nó và thêm vào mảng plugins:

GraphQLModule.forRoot({
  // ...
  plugins: [ApolloServerOperationRegistry({ /* options */})]
}),

Gợi ý Plugin ApolloServerOperationRegistry được export từ package @apollo/server-plugin-operation-registry.

Plugin với Mercurius

Một số plugin Fastify đặc thù cho mercurius phải được load sau plugin mercurius (đọc thêm tại đây) trong cây plugin (plugin tree).

Cảnh báo mercurius-upload là một ngoại lệ và cần được đăng ký trong file main.

Vì lý do đó, MercuriusDriver cung cấp một tùy chọn cấu hình plugins không bắt buộc. Nó là một mảng các object gồm hai thuộc tính: plugin và options của nó. Do đó, đăng ký cache plugin sẽ trông như sau:

GraphQLModule.forRoot({
  driver: MercuriusDriver,
  // ...
  plugins: [
    {
      plugin: cache,
      options: {
        ttl: 10,
        policy: {
          Query: {
            add: true
          }
        }
      },
    }
  ]
}),

Ghi chú người dịch “Plugin tree” ở đây ám chỉ cơ chế đăng ký plugin lồng nhau của Fastify (fastify.register()), khác hẳn hệ middleware tuyến tính của Express. Vì mercurius bản thân nó cũng là một Fastify plugin, plugin nào cần truy cập context GraphQL do mercurius tạo ra (schema, decorator…) bắt buộc phải register sau nó — register trước sẽ không thấy được các decorator mà mercurius gắn vào instance Fastify.

Nội dung gốc: NestJS Documentation © Kamil Myśliwiec, giấy phép MIT. Bản dịch và ghi chú: Lê Văn Dũng.