剧场模式
首页后端TypeScript基于角色的权限控制原理与实战

基于角色的权限控制原理与实战 #3 优化代码(三更)

海外散仙厉飞雨 · 化神发布于新课程
0

https://docs.mongodb.com/manual/reference/operator/query/in/

src/app.ts

import express, { Express, Request, Response } from "express";

// database
import mongoose from "mongoose";

// error handler
import errorMiddleware from "./middlewares/error.middleware";

// config
import "dotenv/config";
import config from "./config/config";

// middleware
import morgan from "morgan";
import helmet from "helmet";
import cors from "cors";
import routes from "./routes";

// logger
import { Logger, ILogger } from "./utils/logger";
import notFoundError from "./middlewares/notFoundHandler.middleware";

// model
import User from "./models/User";

import bcrypt from "bcryptjs";
import Admin from "./models/Admin";

export class Application {
  app: Express;
  config = config;
  logger: ILogger;

  constructor() {
    this.logger = new Logger(__filename);
    this.app = express();
    this.app.use(require("express-status-monitor")());
    this.app.use(helmet());
    this.app.use(cors());
    this.app.use(
      morgan("dev", {
        skip: () => config.environment === "test"
      })
    );

    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));

    this.app.get("/", (_req: Request, res: Response) => {
      res.json({
        message: "hello world"
      });
    });

    this.app.use("/api", routes);

    this.app.use(notFoundError);

    this.app.use(errorMiddleware);
  }

  setupDbAndServer = async () => {
    await this.setupDb();
    await this.startServer();
    await this.createUser();
    await this.createAdmin();
  };

  setupDb = async () => {
    mongoose.set("useFindAndModify", false);
    const mongodbUrl = `${config.db.host}:${config.db.port}/${config.db.database}`;
    await mongoose.connect(mongodbUrl, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    this.logger.info(`Connected to database. Connection: ${mongodbUrl}`);
  };

  startServer = (): Promise<boolean> => {
    return new Promise((resolve, _reject) => {
      this.app
        .listen(+this.config.port, this.config.host, () => {
          this.logger.info(
            `Server started at http://${this.config.host}:${this.config.port}`
          );
          resolve(true);
        })
        .on("error", err => console.error(err));
    });
  };

  createAdmin = async (): Promise<any> => {
    try {
      const adminDatas = [
        {
          username: config.superAdmin.username,
          password: config.superAdmin.password
        },
        {
          username: config.basicAdmin.username,
          password: config.basicAdmin.password
        }
      ];

      const admins = await Admin.find({
        username: { $in: [adminDatas[0].username, adminDatas[1].username] }
      });

      if (admins) return;

      adminDatas.map(async (data: { username: string; password: string }) => {
        const hashedPassword = await bcrypt.hash(data.password, 10);

        let admin = new Admin({
          username: data.username,
          password: hashedPassword
        });

        await admin.save();
      });
    } catch (error) {
      return Promise.reject(error);
    }
  };

  createUser = async (): Promise<any> => {
    try {
      const user = await User.findOne({ username: config.user.username });
      if (user) return;

      const hashedPassword = await bcrypt.hash(config.user.password, 10);

      let newUser = new User({
        username: config.user.username,
        password: hashedPassword,
        email: config.user.email
      });

      await newUser.save();
    } catch (error) {
      return Promise.reject(error);
    }
  };
}
0 条回复
暂无回复~~
订阅号服务号小程序(beta)
随机课程
诱人的 GraphQL & React & Apollo 入门与实战视频教程

诱人的 GraphQL & React & Apollo 入门与实战视频教程

34 个视频3 小时 20 分钟入门

Pro¥ 209.00¥ 167.20

前后端分离GraphQL已完结

学员
yanger0000 · 元婴🔆 · 金仙华仔 · 金仙
最新动态
yanger0000 · 元婴学习到了0:00
🔆 · 金仙学习到了5:49
华仔 · 金仙学习到了5:49
统计信息
    学员: 14720
    视频数量: 852
    帖子数量: 420

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:89

Top