使用AdminBro爲NestJS應用建立簡易Admin後臺

前言

每次開發一個後端應用,基本上都要編寫一個admin後臺來管理(CRUD)各類資源,在Python生態中,Django和Flask框架都有對應的admin包,經過簡單設置就能夠擁有一個CRUD的admin後臺。我也一直在尋找相似功能的NPM包,終於找到了AdminBro。因爲目前AdminBro官網上的NestJS+AdminBro文檔寫得不是很清晰,因此寫下這篇文章,記錄下如何在NestJS應用中使用AdminBrogit

如下代碼演示環境爲:github

  • 數據庫: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://i.loli.net/2021/04/11/lKLDBnySw12Gzke.png

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

演示代碼

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

相關文章
相關標籤/搜索