NodeJS 使用expressjs和prisma基于请求源更改数据库

up9lanfz  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(212)

我想根据请求来源动态更改数据库。
我创建了一个全局中间件,它在每个路由上都被调用。

// middlwares/global.middleware.js

import DBController from "../controllers/db.controller.js";
import { db1, db2 } from "../prisma/prismaClient.js";
export default (req, res, next) => {
  const dbcontroller = DBController();
  const domain = req.get("origin");
  switch (domain) {
    case "http://localhost:3000":
      dbcontroller.setDB(db1);
      break;
    case "http://localhost:3001":
      dbcontroller.setDB(db2);
      break;
  }
  next();
};

但是当我通过调用dbcontroller.setDB()方法并最终调用this.DB在DBController中设置db时,它是未定义的。

// controller/db.controller.js

import autoBind from "auto-bind";
class DBController {
  constructor() {
    this.DB;
    autoBind(this);
  }
  setDB(prismaClient) {
    this.DB = prismaClient;
  }
}
export default DBController;
// conrtoller/controller.js

import { generateResponse } from "./../util/public.util.js";
import DBController from "./db.controller.js";
import autoBind from "auto-bind";
import createError from "http-errors";
class Controller extends DBController {
  constructor() {
    super();
    this.generateResponse = generateResponse;
    this.createError = createError;
    autoBind(this);
  }
}
export default Controller;
// controller/article.controller.js

import Controller from "./controller.js";
class ArticleController extends Controller {
  async get(req, res, next) {
    try {
      const articles = await this.DB.article.findMany(); //this.DB is undefined
      const response = this.generateResponse("success", articles);
      res.send(response);
    } catch (error) {
      next(error);
    }
  }
}
export default new ArticleController();

我不知道我应该如何设置一个全局数据库内的顶级控制器,可以使用的每一个地方。
我也尝试了js global.db vars和express app.set(“db”,db1),但我认为这些都不是这项工作的好解决方案。

i1icjdpr

i1icjdpr1#

最后我修改了global.middleware.js文件,修改了request,而不是在高级controller中设置数据库:

import {
  prisma_aramgostar,
  prisma_karen
} from "../prisma/prismaClient.js";
export default async(req, res, next) => {
  const domain = await req.get("x-forwarded-host");
  switch (domain) {
    case "localhost:3000":
      req.DB = prisma_aramgostar;
      console.log("db: aramgostar");
      break;
    case "127.0.0.1:3001":
      req.DB = prisma_karen;
      console.log("db: karen");
      break;
  }
  next();
};

相关问题