羽毛js sequelize通过钩子调用存储过程没有解决

时间:2018-05-25 16:52:17

标签: stored-procedures sequelize.js feathersjs

创建一个调用存储过程的钩子时遇到问题。

我的自定义服务挂钩(customservice.hooks.js)是:

const callstored = require('../../hooks/callstored')
module.exports = {
  before: {
    all: [],
    find: [callstored()],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },
 ...

我的服务类(customservice.class.js):

const mysql = require('mysql')

class Service {
  constructor (options) {
    this.options = options || {};
  }

  find (params) {
    return Promise.resolve( [] );
  }

  get (id, params) {
    return Promise.resolve({

      id, text: `A new message with ID: ${id}!`
    });
  }

  create (data, params) {
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this.create(current)));
    }

    return Promise.resolve(data);
  }

  update (id, data, params) {
    return Promise.resolve(data);
  }

  patch (id, data, params) {
    return Promise.resolve(data);
  }

  remove (id, params) {
    return Promise.resolve({ id });
  }
}

module.exports = function (options) {
  return new Service(options);
};

module.exports.Service = Service;

我的服务(customservice.service.js):

const createService = require('./rankingvotes.class.js');
const hooks = require('./rankingvotes.hooks');

module.exports = function (app) {

  const paginate = app.get('paginate');

  const options = {
    name: 'rankingvotes',
    paginate
  };

  // Initialize our service with any options it requires
  app.use('/rankingvotes', createService(options));

  // Get our initialized service so that we can register hooks and filters
  const service = app.service('rankingvotes');

  service.hooks(hooks);

  app.publish(() => {

  });
};

最后我的钩子是(callstored.js)

const Sequelize = require('sequelize');
module.exports = function () {
  return function (hook) {
    sequelize = hook.app.get('sequelizeClient');
    let result=[];
    return sequelize.query('CALL RANKING();',{
      nest: true,
      raw: true }).then(function(response){
        console.log(response[0]) //data are correct
        hook.data=response[0]; 
        return hook;
      }).error(function(err){
        console.log(err);
        return hook;
      });
  }
}

如果我检查控制台,我正确地获得了数据,但没有从像Postman这样的REST客户端调用。

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:0)

如果您想更改回复,则必须设置hook.result

const Sequelize = require('sequelize');
module.exports = function () {
  return async hook => {
    try {
      const sequelize = hook.app.get('sequelizeClient');
      const response = await sequelize.query('CALL RANKING();',{
        nest: true,
        raw: true
      });

      console.log(response[0]) //data are correct
      context.result = response[0]; 
    } catch(error) {
      console.error(error);
    }

    return hook;
  }
}

hook.data是请求数据,仅适用于createupdatepatch

请注意,如果在hook.result挂钩中设置自定义服务find,设置before跳过