nest-crud-server v11.2.4
Ví dụ
Sử dụng Crud và TypeormCrudService để tạo RestfulAPI
File .controller
import { Controller } from "@nestjs/common";
import { Crud } from "nest-crud-server";
import { PostService } from "./post.service";
@Crud({
params: {
primaryKey: "postId",
},
routes: {
exclude: ["getCountBase"],
updateOneBase: {
// allowParamsOverride: true,
},
},
})
@Controller("post")
export class PostController {
constructor(private service: PostService) {}
}File .service
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { TypeOrmCrudService } from "nest-crud-server";
import { Repository } from "typeorm";
import { PostEntity } from "./post.entity";
@Injectable()
export class PostService extends TypeOrmCrudService<PostEntity> {
constructor(@InjectRepository(PostEntity) repo: Repository<PostEntity>) {
super(repo);
}
}File .entity
import {
Column,
CreateDateColumn,
Entity,
PrimaryColumn,
UpdateDateColumn,
} from "typeorm";
@Entity({ name: "Post" })
export class PostEntity {
@PrimaryColumn({ generated: "increment" })
postId: number;
@Column()
title: string;
avatarSrc: string;
@Column({ default: "" })
description: string;
@Column({ default: "" })
shortDescription: string;
@CreateDateColumn() createDate: Date;
@UpdateDateColumn() updateDate: Date;
}Mô tả
Cách sử dụng Crud
Tham số truyền vào
params.primaryKey: kiểustringlà khóa chính củaEntity. Ví dụPostEntitycó khóa chính làpostIdroutesgồm nhiều tham số khác nhauonly: kiểustring[]bao gồm các giá trị:"getManyBase" | "getOneBase" | "createOneBase" | "createManyBase" | "updateOneBase" | "replaceOneBase" | "deleteOneBase" | "recoverOneBase" | "getCountBase" | "getSumBase"
Ví dụ Controller chỉ muốn cung cấp API để
getManyvàcreateOnethì truyềnroutes: { only: ["getManyBase", "createOneBase"]; }Với ví dụ trên thì chỉ request đến
Controllervới 2 phương thức làGET(để lấy danh sách) vàPOST(để tạo)exclude: kiểustring[]tương tựonlynhưng ngược lại
Ví dụ
Controllercó tất cả phương thức:getMany(lấy danh sách),getOne(lấy một đối tượng),createOne(tạo đối tượng),updateOne(cập nhật đối tượng),deleteOne(xóa đối tượng)... và bạn muốn bỏ phương thứccreateMany(tạo nhiều đối tượng) thì thực hiện như sauroutes: { exclude: ["createManyBase"]; }
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago