如何覆盖feathersjs默认的服务方法

时间:2017-12-08 18:12:00

标签: node.js method-overriding feathersjs feathers-service

我使用feathers generate service命令创建了feathersjs服务。我想覆盖它对create方法的定义。

这是我的服务类

/* eslint-disable no-unused-vars */
// Initializes the `userGroup` service on path `/usergroup`
const createService = require('feathers-sequelize');
const createModel = require('../../models/user-group.model');
const hooks = require('./user-group.hooks');
const filters = require('./user-group.filters');
const async = require('async');

module.exports = function () {
  const app = this;
  const Model = createModel(app);
  const paginate = app.get('paginate');

  const options = {
    name: 'usergroup',
    Model,
    paginate,
    create: fnCreateGroup // documentation says this allows you to create your own create method
  };

  function fnCreateGroup(data, params) {
    let json = {
      done: false
    };
    let permissionIds = Object.keys(data.permissionList), inIds = [];
    for (let i in permissionIds) {
      if (data.permissionList[permissionIds[i]]) {
        inIds.push(parseInt(permissionIds[i]));
      }
    }
    if (inIds.length === 0) {
      json.cause = 'You must provide the permission List';
      return Promise.resolve(json);
    }
    async.parallel([
      function (cb) {
        Model.create({
          groupName: data.groupName
        }).then(function (ug) {
          cb(null, ug);
        }, function (err) {
          cb(err, null);
        });
      },
      function (cb) {
        app.models.permissions.findAll({
          where: {
            id: {
              $in: inIds
            }
          }
        }).then(function (plist) {
          cb(null, plist);
        });
      }
    ]
      , function (err, results) {
      if (typeof err !== 'undefined' && err !== null) {
        json.err = err;
        return Promise.resolve(json);
      } else {
        let permissions = results[1], group = results[0];
        for (let i = 0; i < permissions.length; i++) {
          group.addPermission(permissions[i]);
        }
        json.done = true;
        json.id = group.id;
        return Promise.resolve(json);
      }
    });
  }

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

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

  service.hooks(hooks);

  if (service.filter) {
    service.filter(filters);
  }
};

对create方法的测试显示原始方法的结果而不是我的。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

database adapter common API中记录了如何覆盖和扩展现有服务。您可以通过设置hook.result或扩展现有ES6类来使用hooks

const Service = require( 'feathers-sequelize').Service;

class MyService extends Service {
  create(data, params) {
    data.created_at = new Date();

    return super.create(data, params);
  }
}

app.use('/todos', new MyService({
  paginate: {
    default: 2,
    max: 4
  }
}));