当使用ES6导入/导出时,如何通过快速路由将sequelize传递到节点中MVC模型中的控制器



我正在尝试将一些现有的代码重构到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序列化对象一直传递到控制器,这样它就可以完成它的任务?

也许直接调用模型?

'use strict';
import { myTable } from '../db';
export default class MyController {
store = async (req, res, next) => {
await MyTable.create({ full: req.body.fullUrl}); 
res.redirect('/');
}
}

最新更新