前言
每次开发一个后端应用,基本上都要编写一个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 {}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。