使用 ES6 import/export 时,如何通过快速路由将 sequelize 传递给节点中 MVC 模型中的控制器?

How to pass sequelize through express routes to controller in MVC model in node when using ES6 import/export?

我正在尝试将一些现有代码重构为 MVC 模型,但我不确定我是否弄乱了结构,或者我是否只是想不出如何传递变量,但是,假设我的结构很好,如何通过 Express 路由将 sequelize 实例传递给控制器​​?这是我的代码,希望为清晰起见进行简化:

结构:

src/
  db.js
  routes.js
  server.js
  controllers/mycontroller.js
  models/mymodel.js

server.js:

'use strict';

import express from 'express';
import Sequelize from 'sequelize';

import { router as routes } from './routes';
import db from './db';

const app = express();

try {
  await db.authenticate();
  console.log('Connection has been established successfully.');
} catch (error) {
  console.error('Unable to connect to the database:', error);
}

db.myTable.sync(); // this works fine

app.use(express.urlencoded({ extended: false }));
app.use(routes); // this, I think, needs to pass db.myTable

app.listen( 3300, () => {
  console.log('Listening on 3300');
});

db.js:

'use strict';

import Sequelize from 'sequelize';

import myTableModel from './models/mymodel';

const sequelize = new Sequelize('sqlite::memory');
const db = {};

db.authenticate = () => sequelize.authenticate();
db.myTable = myTableModel(sequelize);

export default db;

routes.js:

import express from 'express';
export const router = express.Router();

import MyController from './controllers/mycontroller';

const myController = new MyController();

... // other routes elided for brevity

router.post('/test', myController.store); // that db.myTable I thought I needed to pass above,
// I think I need to pass again here. Or, alternatively, I could put a constructor into
// MyController and pass it as an arg above when I call 'new MyController', but I still have to
// get it down here into this routes file.

mycontroller.js:

'use strict';

import MyTableModel from '../models/mymodel'; // This was an experiment I tried, but in retrospect,
// it of course makes no sense. I don't need to import the model, I need to have passed the
// instantiated model down here somehow

export default class MyController {
  store = async (req, res, next) => {
    await MyTable.create({ full: req.body.fullUrl}); // This fails (of course), because
    // MyTable.create doesn't exist here.

    res.redirect('/');
  }
}

所以,回到问题:假设这个结构看起来正确(也可以随意评论),我如何让 MyTable sequelize 对象一直传递到控制器,所以它可以做它的事吗?

也许直接调用模型?

'use strict';
import { myTable } from '../db';

export default class MyController {
  store = async (req, res, next) => {
    await MyTable.create({ full: req.body.fullUrl}); 

    res.redirect('/');
  }
}