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

基于角色的权限控制原理与实战 #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 条回复
暂无回复~~
官方服务号
随机课程
React + dva + roadhog 轻松学

React + dva + roadhog 轻松学

7 个视频43 分钟中级

Pro¥ 109.00¥ 87.20

React已完结

学员(39)
LIANGWEIBIAO · 元婴一只快乐的码农 · 大乘宏 · 道祖爱优美 · 元婴米斯特张 · 真仙[微信红包]恭喜发财,大吉大利 · 道祖WeChain · 真仙萎鳴咸一 · 太乙Pip · 太乙Flash52 · 太乙lRockets · 道祖liu_hao0813 · 大乘
最新动态
LIANGWEIBIAO · 元婴学习到了5:49
一只快乐的码农 · 大乘学习到了5:49
宏 · 道祖学习到了0:00
爱优美 · 元婴学习到了0:00
米斯特张 · 真仙学习到了0:00
统计信息
    学员: 17786
    视频数量: 1049
    帖子数量: 427

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 关注我们 | 在线学员:114

Top