我尝试使用api在csv文件中为导出数据创建api,这意味着我想使用羽毛服务下载csv文件。
app.service('/csv').hooks({
before: {
create: [ function(hook, next) {
const dataToStore = [
{
to: 'marshall',
from: 'marshall',
body: 'Stop talking to that rubber ducky!'
}, {
to: 'marshall',
from: 'marshall',
body: `...unless you're rubber duck debugging.`
}
]
hook.data = dataToStore;
next();
}
]
},
after: {
create: [ function(hook,next){
// here i need imported data to be write in csv and make api side as downloadable
// when i hit the service i want to download file in csv file format.
hook.result.code = 200;
next();
}
]
},
error: {
create: [function(hook, next){
hook.error.errors = { code : hook.error.code };
hook.error.code = 200;
next();
}]
}
});
答案 0 :(得分:2)
格式化响应不是在挂钩中完成的,而是在具有general custom formatter或service specific middleware的Express中间件中完成的。
在注册/csv
服务时将其添加到最后(服务呼叫数据将在res.data
中):
const json2csv = require('json2csv');
const fields = [ 'to', 'from', 'body' ];
app.use('/csv', createService(), function(req, res) {
const result = res.data;
const data = result.data; // will be either `result` as an array or `data` if it is paginated
const csv = json2csv({ data, fields });
res.type('csv');
res.end(csv);
});