DEV Community

Mite
Mite

Posted on

3 1 1 1 1

Crudify: Automate Your Mongoose CRUD Operations in NestJS

Are you tired of writing repetitive CRUD logic for your Mongoose models? Meet Crudify, a NestJS library designed to simplify your development workflow by automatically generating RESTful CRUD endpoints. With just a few lines of code, you can set up a fully functional API, complete with Swagger documentation and built-in logging.

๐Ÿ“š What is Crudify?

Crudify is a powerful tool for NestJS developers who work with Mongoose. It reduces boilerplate code by automating the creation of CRUD (Create, Read, Update, Delete) endpoints for your models. But thatโ€™s not all! It also provides automatic Swagger documentation and integrates a logger to handle uncaught errors, making your API more maintainable and developer-friendly.

With Crudify, you can:

  • ๐Ÿš€ Automatically generate CRUD endpoints for your Mongoose models.
  • ๐Ÿ“– Get fully functional Swagger UI without any additional setup.
  • ๐Ÿ› ๏ธ Customize endpoints to fit your specific needs.
  • ๐Ÿงฐ Simplify debugging with integrated logging.

๐Ÿ› ๏ธ Quick Setup

1. Install Dependencies

npm install ncrudify
Enter fullscreen mode Exit fullscreen mode

2. Define Your Model

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User extends Document {
  @Prop({ required: true }) name: string;
  @Prop({ required: true, unique: true }) email: string;
  @Prop() age: number;
}

export const UserSchema = SchemaFactory.createForClass(User);
Enter fullscreen mode Exit fullscreen mode

3. Create a Service

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { CrudifyService } from 'ncrudify';

@Injectable()
export class UserService extends CrudifyService<User> {
  constructor(@InjectModel(User.name) userModel: Model<User>) {
    super(userModel);
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Build a Controller

import { Controller } from '@nestjs/common';
import { UserService } from './user.service';
import { Crudify, CrudifyController } from 'ncrudify';

@Crudify({ model: { type: User } })
@Controller('users')
export class UserController extends CrudifyController<User> {
  constructor(public service: UserService) {
    super(service);
  }
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŒ Swagger Integration

Crudify makes it effortless to set up Swagger documentation for your API. Swagger automatically documents all your CRUD endpoints, making it easier to test and share your API with your team or external users.

Once set up, you can access the Swagger UI at http://localhost:3000/api, where youโ€™ll find a user-friendly interface to interact with your API.

1. Import CrudifySwaggerModule in AppModule:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CrudifySwaggerModule } from 'ncrudify';

@Module({
  imports: [
    MongooseModule.forRoot(process.env.MONGODB_URI),
    CrudifySwaggerModule,
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

2. Setup Swagger in main.ts:

import { NestFactory } from '@nestjs/core';
import { CrudifySwaggerModule } from 'ncrudify';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  CrudifySwaggerModule.setupSwagger(app);
  await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฐ Integrated Logging

Crudify includes a logger to capture and manage uncaught errors, making your debugging process more efficient. The logger is based on Errsole, a tool designed to help developers track runtime errors and improve error handling.

How to Enable the Logger

1. Import CrudifyLoggerModule in AppModule:

import { CrudifyLoggerModule } from 'ncrudify';

@Module({
  imports: [CrudifyLoggerModule],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

2. Access the Logger UI

By default, the Crudify Logger listens on http://localhost:3001. You can access this interface to see all uncaught errors, including stack traces and request details, which makes identifying and fixing issues faster.

Customize the Logger

You can adjust the loggerโ€™s configuration by providing custom options, such as log levels or output destinations, to match your projectโ€™s needs.


๐Ÿ”Ž Advanced Query Filters

Crudify supports powerful query filters using a simple format:

field=[$operator]:value
Enter fullscreen mode Exit fullscreen mode

Examples

  • age=[$gt]:30 - Find users older than 30.
  • name=[$eq]:John - Find users named John.

Supported Operators

  • $eq: Equal to
  • $ne: Not equal to
  • $gt: Greater than
  • $lt: Less than
  • $gte: Greater than or equal to
  • $lte: Less than or equal to
  • $cont: Contains (for strings)
  • $excl: Does not contain (for strings)
  • $in: In a set of values
  • $notin: Not in a set of values
  • $isnull: Is null
  • $notnull: Is not null
  • $between: Between two values

๐Ÿ’ก Boost Your Productivity

Crudify is more than just a tool for generating endpoints. Itโ€™s a productivity booster for NestJS developers, helping you focus on what matters: building great applications. By handling the repetitive parts of CRUD operations, Swagger setup, and error logging, Crudify saves you time and effort.

๐Ÿ‘‰ GitHub: Crudify

โค๏ธ Support on Buy Me a Coffee.

๐Ÿ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay