nest-auth-generic-crud
v1.0.19
Published
nest generic crud with optional authentication and logging
Downloads
4
Maintainers
Readme
Description
Module used for handling jwt authentication and basic crud using a mongoose orm and mongo database
Installation
$ npm i --save nest-auth-generic-crud
Quick Start
Intro
The following code is divided in 2 folders under "src" :
- base, the library folder
- user, a test example for the library
Example
User folder.
Define a model : (user->user.model.ts)
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { BaseEntity } from "../base/base.schema";
import { Document } from "mongoose";
export type UserDocument = User & Document;
@Schema()
export class User extends BaseEntity {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
created_at: Date;
}
export const UserSchema = SchemaFactory.createForClass(User);
Define the module : (user->user.module.ts)
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { UserController } from "./user.controller";
import { UserService } from "./user.service";
import { UserSchema } from "./user.model";
@Module({
imports: [MongooseModule.forFeature([{ name: "User", schema: UserSchema }])],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
Define a controller : (user->user.controller.ts)
import {
Body,
Controller,
HttpStatus,
Param,
Patch,
Post,
Put,
Res,
} from "@nestjs/common";
import { UserService } from "./user.service";
import { BaseController } from "../base/base.controller";
import { CreateUserDto } from "./dto/CreateUserDto";
import { UpdateUserDto } from "./dto/UpdateUserDto";
import { User } from "./user.model";
import { IValidationData, ValidationEnum } from "../base/base.interfaces";
@Controller("user")
export class UserController extends BaseController<
User,
CreateUserDto,
UpdateUserDto
> {
constructor(private userService: UserService) {
super(userService, "http://localhost:3000/auth/validate");
}
@Patch(":id")
async updateChild(@Param("id") id: string, @Body() t: UpdateUserDto) {
return await this.userService.update(id, t);
}
@Post()
async createChild(@Body() t: CreateUserDto) {
const validation = null;
return await this.userService.create(t, validation);
}
}
define a service (user->user.service.ts)
import { Model } from "mongoose";
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { User } from "./user.model";
import { BaseService } from "../base/base.service";
import { CreateUserDto } from "./dto/CreateUserDto";
import { UpdateUserDto } from "./dto/UpdateUserDto";
@Injectable()
export class UserService extends BaseService<
User,
CreateUserDto,
UpdateUserDto
> {
constructor(@InjectModel("User") private readonly userModel: Model<User>) {
super(userModel);
}
}