Build interceptor and JSON API helpers

This commit is contained in:
Aurélien Georget 2016-01-22 15:40:43 +01:00
parent 637b3ea81d
commit 03400e82f5
4 changed files with 84 additions and 1 deletions

View File

@ -27,5 +27,6 @@ module.exports = {
router: true, router: true,
static: true, static: true,
websockets: true, websockets: true,
studio: true studio: true,
jsonapi: true
}; };

View File

@ -0,0 +1,19 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const JSONAPISerializer = require('jsonapi-serializer');
/**
* JSON API helper
*/
module.exports = {
set: function(ctx, actionRoute) {
console.log(actionRoute);
}
};

View File

@ -0,0 +1,62 @@
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const regex = require('../../../../util/regex');
const response = require('./helpers/response');
/**
* JSON API hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
jsonapi: {}
},
/**
* Initialize the hook
*/
initialize: function (cb) {
function *interceptor(next) {
const self = this;
// Wait for downstream middleware/handlers to execute to build the response
yield next;
// Detect route
const matchedRoute = _.find(strapi.router.stack, function(stack) {
if (new RegExp(stack.regexp).test(self.request.url) && _.includes(stack.methods, self.request.method.toUpperCase())) {
return stack;
}
});
// Handlers set the response body
if (!_.isUndefined(matchedRoute)) {
const actionRoute = strapi.config.routes[self.request.method.toUpperCase() + ' ' + matchedRoute.path];
if (!_.isUndefined(actionRoute)) {
response.set(this, actionRoute);
}
}
};
strapi.app.use(interceptor);
cb();
}
};
return hook;
};

View File

@ -41,6 +41,7 @@
"herd": "~1.0.0", "herd": "~1.0.0",
"include-all": "~0.1.6", "include-all": "~0.1.6",
"json-stringify-safe": "~5.0.1", "json-stringify-safe": "~5.0.1",
"jsonapi-serializer": "^2.0.4",
"koa": "~1.1.2", "koa": "~1.1.2",
"koa-bodyparser": "~2.0.1", "koa-bodyparser": "~2.0.1",
"koa-compose": "~2.3.0", "koa-compose": "~2.3.0",