REST
通過services路徑的RESTful接口米罚,可以把服務(wù)接口暴露出去酥郭。
也就是說可以通過HTTP方法來調(diào)用服務(wù)嘱支,
使用
安裝這個Provider
$ npm install feathers-rest body-parser
如果想在執(zhí)行REST handler之前贩汉,增加其他的中間件盖桥,可以在注冊服務(wù)前零抬,調(diào)用
app.use(middleware)镊讼。
// app.js
'use strict';
const feathers = require('feathers');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
class MessageService {
constructor() {
this.messages = [];
}
find(params) {
return Promise.resolve(this.messages);
}
create(data, params) {
this.messages.push(data);
return Promise.resolve(data);
}
}
const app = feathers()
// Enable the REST provider
.configure(rest())
// Turn on JSON parser for REST services
.use(bodyParser.json())
// Turn on URL-encoded parser for REST services
.use(bodyParser.urlencoded({ extended: true }));
app.use('/messages', new MessageService());
// Log newly created messages on the server
app.service('messages').on('created', message =>
console.log('Created message', message)
);
app.listen(3030);
查詢,路由和中間件參數(shù)
const feathers = require('feathers');
const rest = require('feathers-rest');
const app = feathers();
app.configure(rest())
.use(function(req, res, next) {
req.feathers.fromMiddleware = 'Hello world';
next();
});
app.use('/users/:userId/messages', {
get(id, params) {
console.log(params.query); // -> ?query
console.log(params.provider); // -> 'rest'
console.log(params.fromMiddleware); // -> 'Hello world'
console.log(params.userId); // will be `1` for GET /users/1/messages
return Promise.resolve({
id,
params,
read: false,
text: `Feathers is great!`,
createdAt: new Date.getTime()
});
}
});
app.listen(3030);
自定義響應(yīng)格式
默認(rèn)地平夜,REST回應(yīng)的格式化器是由中間件來實現(xiàn)蝶棋,一般返回JSON格式數(shù)據(jù)。
通過重載res.format來重新格式化res.data忽妒,通過中間件可以返回請求玩裙。