每次開發一個後端應用,基本上都要編寫一個admin後臺來管理(CRUD)各類資源,在Python生態中,Django和Flask框架都有對應的admin包,經過簡單設置就能夠擁有一個CRUD的admin後臺。我也一直在尋找相似功能的NPM包,終於找到了AdminBro。因爲目前AdminBro官網上的NestJS+AdminBro文檔寫得不是很清晰,因此寫下這篇文章,記錄下如何在NestJS應用中使用AdminBrogit
如下代碼演示環境爲:github
npm i admin-bro @admin-bro/nestjs @admin-bro/mongoose npm i express @admin-bro/express express-formidable npm i express-session
// comment.schema.ts import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Document } from "mongoose"; @Schema() export class Comment extends Document { @Prop({ default: Date.now, }) created_at: Date; @Prop() user_id: string; @Prop() content: string; @Prop() liked_num: number; @Prop() client_name: string; @Prop() connect_key: string; } export const CommentSchema = SchemaFactory.createForClass(Comment);
// app.module.ts import { Module } from '@nestjs/common'; import AdminBro from 'admin-bro'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { Database, Resource } from '@admin-bro/mongoose'; import { Model } from 'mongoose'; import { getModelToken, MongooseModule } from '@nestjs/mongoose'; import { AdminModule } from '@admin-bro/nestjs'; import { Comment, CommentSchema } from '../comment/comment.schema'; AdminBro.registerAdapter({ Database, Resource }); @Module({ imports: [ MongooseModule.forRoot('mongodb://127.0.0.1/comment'), AdminModule.createAdminAsync({ useFactory: (commentModel: Model<Comment>) => { return { auth: { authenticate: async () => { // 認證邏輯 return Promise.resolve({ email: 'test' } }), cookieName: 'admin_panel', cookiePassword: 'xxx2arfa', }, adminBroOptions: { rootPath: '/admin', resources: [commentModel], }, }; }, inject: [getModelToken(Comment.name)], imports: [ MongooseModule.forFeature([ { name: Comment.name, schema: CommentSchema }, ]), ], }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {}