ncrudify
Version:
Configurable CRUD module for NestJS and Mongoose.
196 lines (132 loc) • 7.64 kB
Markdown
Swagger is a powerful tool for documenting and testing APIs. In NestJS, you can easily integrate Swagger using the `@nestjs/swagger` package and `swagger-ui-express`. Below, I’ll explain how to set up Swagger in your NestJS application and configure it to work seamlessly with your `Crudify`-generated APIs.
### **Install Required Packages**
First, install the necessary packages using npm or yarn:
```bash
npm install @nestjs/swagger swagger-ui-express
```
### **Configure Swagger in `main.ts`**
In your `main.ts` file, configure Swagger using the `DocumentBuilder` and `SwaggerModule`. This setup allows you to customize the Swagger documentation to fit your application's needs.
Here’s an example configuration:
```typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Swagger configuration
const config = new DocumentBuilder()
.setTitle('Crudify API') // Set the title of the API
.setDescription('API generated by Crudify') // Set the description
.setVersion('1.0') // Set the API version
.build();
// Create the Swagger document
const document = SwaggerModule.createDocument(app, config);
// Set up the Swagger UI endpoint
SwaggerModule.setup('api', app, document, {
swaggerOptions: {
filter: true, // Enable filtering by tag
},
});
await app.listen(3000);
}
bootstrap();
```
## **Adding `@ApiTags` to Group Endpoints in Swagger**
To organize your API endpoints in Swagger, you can use the `@ApiTags` decorator from the `@nestjs/swagger` package. This decorator allows you to group related endpoints under a specific tag, making it easier for users to navigate and understand your API documentation.
### **Add `@ApiTags` to Your Controller**
In your controller, use the `@ApiTags` decorator to specify a tag for all endpoints within that controller. For example, if you have a `UserController`, you can group all user-related endpoints under the `users` tag.
Here’s an example:
```typescript
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { UserService } from './user.service';
import { User } from './user.entity';
import { Crudify, CrudifyController } from 'ncrudify';
@ApiTags('users') // Group all endpoints under the 'users' tag
@Crudify({
model: {
type: User, // Define your Mongoose model
},
})
@Controller('users')
export class UserController extends CrudifyController<User> {
constructor(public service: UserService) {
super(service);
}
}
```
### **Why Use `@ApiTags`?**
The `@ApiTags` decorator provides the following benefits:
1. **Improved Organization**: Endpoints are grouped logically, making it easier for users to find related operations.
2. **Better Readability**: Tags act as categories in the Swagger UI, improving the overall readability of your API documentation.
3. **Filtering**: If you enabled the `filter: true` option in the Swagger UI configuration, users can filter endpoints by tags for a more focused view.
### **Viewing Tags in Swagger UI**
Once you’ve added `@ApiTags` to your controllers, the Swagger UI will display your endpoints grouped by their respective tags. For example:
- **`users`**: Contains all user-related endpoints (e.g., `GET /users`, `POST /users`).
- **`products`**: Contains all product-related endpoints (e.g., `GET /products`, `POST /products`).
This grouping makes it easier for users to navigate and test your API.
### **Explanation of the Configuration**
#### **1. `DocumentBuilder`**
The `DocumentBuilder` is used to define the metadata for your Swagger documentation. It includes:
- **`.setTitle('Crudify API')`**: Sets the title of your API.
- **`.setDescription('API generated by Crudify')`**: Provides a description of your API.
- **`.setVersion('1.0')`**: Specifies the version of your API.
You can also add additional configurations, such as:
- **`.addTag('users')`**: Adds tags to group related endpoints.
- **`.addBearerAuth()`**: Adds authentication support for your API.
#### **2. `SwaggerModule.createDocument(app, config)`**
This method generates the Swagger document based on the configuration and your application’s routes.
#### **3. `SwaggerModule.setup('api', app, document, { swaggerOptions: { filter: true } })`**
This method sets up the Swagger UI at the `/api` endpoint. The `swaggerOptions` object allows you to customize the Swagger UI behavior:
- **`filter: true`**: Enables filtering by tag, making it easier for users to navigate your API documentation.
### **Why This Configuration Was Chosen**
This setup was designed to provide users with the **maximum configurability** for their Swagger documentation. Here’s why:
1. **Customizable Metadata**: The `DocumentBuilder` allows you to define the title, description, version, and tags for your API, making it easy to tailor the documentation to your application.
2. **Flexible Swagger UI Options**: The `swaggerOptions` parameter in `SwaggerModule.setup` lets you customize the Swagger UI behavior, such as enabling filtering or adding custom styles.
3. **Integration with `Crudify`**: By configuring Swagger in `main.ts`, you ensure that all routes, including those generated by `Crudify`, are automatically documented without additional effort.
4. **Clear Separation of Concerns**: Keeping the Swagger configuration in `main.ts` ensures that your application’s bootstrap logic remains clean and focused.
### **Adding Tags and Authentication (Optional)**
To further enhance your Swagger documentation, you can add tags and authentication support.
#### **Example: Adding Tags**
```typescript
const config = new DocumentBuilder()
.setTitle('Crudify API')
.setDescription('API generated by Crudify')
.setVersion('1.0')
.addTag('users', 'Operations related to users') // Add a tag for user-related endpoints
.addTag('products', 'Operations related to products') // Add a tag for product-related endpoints
.build();
```
#### **Example: Adding Bearer Authentication**
```typescript
const config = new DocumentBuilder()
.setTitle('Crudify API')
.setDescription('API generated by Crudify')
.setVersion('1.0')
.addBearerAuth() // Add Bearer token authentication support
.build();
```
### **Accessing the Swagger UI**
Once your application is running, you can access the Swagger UI by navigating to:
```
http://127.0.0.1:3000/api
```
Here, you’ll see all your API endpoints, grouped by tags (if configured), and you can test them directly from the browser.
### **Key Takeaways**
1. **Install `@nestjs/swagger` and `swagger-ui-express`**: These packages are required to integrate Swagger into your NestJS application.
2. **Configure Swagger in `main.ts`**: Use the `DocumentBuilder` and `SwaggerModule` to set up Swagger documentation.
3. **Customize Swagger UI**: Use `swaggerOptions` to enable filtering or other UI customizations.
4. **Maximize Configurability**: This setup ensures that your Swagger documentation is flexible and integrates seamlessly with `Crudify`.
By following this guide, you can easily configure Swagger for your NestJS application and provide a user-friendly API documentation experience. Let me know if you need further assistance! 🚀