使用AdminBro为NestJS应用创建简易Admin后台

前言

每次开发一个后端应用,基本上都要编写一个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

安装

1
2
3
npm i admin-bro @admin-bro/nestjs @admin-bro/mongoose
npm i express @admin-bro/express express-formidable
npm i express-session

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 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);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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://i.loli.net/2021/04/11/lKLDBnySw12Gzke.png

https://i.loli.net/2021/04/11/GHV2iE5qPBRQOuX.png

演示代码

https://github.com/demo-box/adminbro-nestjs-demo