1

我有一个使用该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 方法的测试显示的是原始方法的结果,而不是我的。

我能做些什么?

4

1 回答 1

3

数据库适配器公共 API中记录了如何覆盖和扩展现有服务。您可以通过设置或扩展现有的 ES6 类来使用钩子:hook.result

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
  }
}));
于 2017-12-10T05:13:38.763 回答