前言
每次开发一个后端利用,基本上都要编写一个 admin 后盾来治理 (CRUD) 各种资源,在 Python 生态中,Django 和 Flask 框架都有对应的 admin 包,通过简略设置就能够领有一个 CRUD 的 admin 后盾。我也始终在寻找相似性能的 NPM 包,终于找到了 AdminBro。因为目前 AdminBro 官网上的 NestJS+AdminBro 文档写得不是很清晰,所以写下这篇文章,记录下如何在 NestJS 利用中应用 AdminBro
以下代码演示环境为:
- 数据库:MongoDB 4.4.3
- 操作系统: Windows10
- 开发工具: VSCode
- 技术栈: NodeJS 10.20.1 + NestJS 7.2.4 + AdminBro 3.4.0 + Mongoose 5.12.3
装置
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 {}
成果
演示代码
https://github.com/demo-box/adminbro-nestjs-demo