node.js - 将 sequelize 模型实例传递给服务在 express.js 中不起作用

标签 node.js class express inheritance sequelize.js

我想访问 ItemService 中 CRUDService 的 findById 函数。我从 readAll 函数得到响应,但没有从 findById 得到响应。我认为我从 ItemService 通过构造函数传递给 CRUDService 的 dao 对象不起作用。我是 node js 和 express js 的新手。请问你能帮帮我吗。
这是原油服务

class CRUDService{

  constructor(dao) {
    this.dao = dao;
  }

  readAll = () => {
    const rows = dao.findAll();
    return rows;
  };

  findById = (rowId) => {
    const row = dao.findByPk(rowId);
    return row;
  };
}

module.exports = CRUDService
这是物品服务
const CRUDService = require('../common/crud.service.js');
const ItemDAO = require('./item.dao.js');

class ItemService extends CRUDService{

  constructor() {
    const dao = new ItemDAO();
    super(ItemDAO);
  }

  readAll = () => {
    const rows = ItemDAO.findAll();
    return rows;
  };
}

module.exports = ItemService
这是 DAO
const {Sequelize, Model} = require('sequelize');
const sequelize = require('../database');

class ItemDAO extends Model {}

ItemDAO.init(
{
  id: {
    type: Sequelize.UUID,
    primaryKey: true,
    defaultValue: Sequelize.UUIDV1
  },
  name_en: Sequelize.STRING,
  name_local: Sequelize.STRING,
  created_at: Sequelize.TIME,
  created_by: Sequelize.STRING,
  is_deleted: Sequelize.BOOLEAN
  },
  { 
    sequelize,
    modelName: 'Item',
    schema: 'cat',
    timestamps: false,
    tableName: 'item'
  }
);

module.exports = ItemDAO;

最佳答案

您需要将 ItemDAO 的实例传递给 super 构造函数。

const CRUDService = require('../common/crud.service.js');
const ItemDAO = require('./item.dao.js');
class ItemService extends CRUDService{

  constructor() {
    super(new ItemDAO()); // ---> here
  }

  readAll = () => {
    const rows = this.readAll();
    return rows;
  };
}

module.exports = ItemService
还需要修改你的服务。
class CRUDService{

  constructor(dao) {
    this.dao = dao;
  }

  readAll = () => this.dao.findAll().then(rows => rows);

  findById = (rowId) => this.dao.findByPk(rowId).then(row => row);
}
还要记住,这些方法返回 promise 最好使用 .then() 或使用 async/await

关于node.js - 将 sequelize 模型实例传递给服务在 express.js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62498881/

相关文章:

javascript - 未定义 forEach TypeError : undefined is not a function

node.js - 构建成功。发布失败, "Class constructor Parser cannot be invoked without ' new'"

c# - 不包含静态 'Main' [但确实如此?]

javascript - API 使用 token 向 odoo 进行身份验证

javascript - 尽管调用文件相同,但为什么会出现连接错误?

C++ 模板和访问命名空间

C++ 类 - 我的程序有什么问题?

node.js - 在 Cookie 中存储 Express Session

node.js - 无法使用 Node 0.9 和最新的 Express 4.11.2 提供静态目录

node.js - Grunt.js 永远关注