繁体   English   中英

使用ES6导入/导出时,如何通过快速路由将续集传递到节点中MVC model中的controller?

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

我正在尝试将一些现有代码重构为 MVC model,但不确定我是否弄乱了结构,或者我只是不知道如何传递变量,但是,假设我的结构很好,如何通过 Express 路由将续集实例传递到 controller? 这是我的代码,希望为清楚起见进行简化:

结构:

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;

路线.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.

我的控制器.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 object 一直传递到 controller,所以它可以做它的事?

也许直接调用 model?

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

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

    res.redirect('/');
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM