gpt4 book ai didi

node.js - 如何覆盖feathersjs默认服务方法

转载 作者:太空宇宙 更新时间:2023-11-03 23:01:17 26 4
gpt4 key购买 nike

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

我能做什么?

最佳答案

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

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
}
}));

关于node.js - 如何覆盖feathersjs默认服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com