96 lines
2.5 KiB
JavaScript
Raw Normal View History

2016-01-22 15:40:43 +01:00
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
// Local Strapi dependencies.
2016-01-26 18:03:52 +01:00
const request = require('./helpers/request');
2016-01-22 15:40:43 +01:00
const response = require('./helpers/response');
2016-02-08 12:07:58 +01:00
const utils = require('./utils/utils');
2016-01-22 15:40:43 +01:00
/**
* JSON API hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Initialize the hook
*/
initialize: function (cb) {
function * _interceptor(next) {
2016-01-22 15:40:43 +01:00
// Wait for downstream middleware/handlers to execute to build the response
yield next;
// Exclude administration routes
if (this.request.url.indexOf('admin') === -1) {
// Set the required header
this.response.type = 'application/vnd.api+json';
// Verify Content-Type header
if (this.request.type !== 'application/vnd.api+json') {
this.status = 406;
this.body = '';
} else if (_.startsWith(this.status, '2')) {
// Intercept success requests
// Detect route
2016-02-08 12:07:58 +01:00
const matchedRoute = utils.matchedRoute(this);
if (!_.isUndefined(matchedRoute)) {
// Handlers set the response body
2016-02-08 12:07:58 +01:00
const actionRoute = strapi.config.routes[this.request.method.toUpperCase() + ' ' + matchedRoute.path];
if (!_.isUndefined(actionRoute)) {
2016-03-02 16:20:36 +01:00
yield response.set(this, matchedRoute, actionRoute);
}
}
} else {
// Intercept error requests
this.body = {
errors: this.body
};
2016-01-22 15:40:43 +01:00
}
}
}
2016-01-22 15:40:43 +01:00
if ((_.isPlainObject(strapi.config.jsonapi) && strapi.config.jsonapi.enabled === true) || (_.isBoolean(strapi.config.jsonapi) && strapi.config.jsonapi === true)) {
strapi.app.use(_interceptor);
}
2016-01-22 15:40:43 +01:00
cb();
2016-01-26 18:03:52 +01:00
},
/**
* Parse request and attributes
*/
parse: function (strapi) {
return function * (next) {
// Verify Content-Type header and exclude administration and user routes
if (this.request.url.indexOf('admin') !== -1 && !(_.isPlainObject(strapi.config.jsonapi) && strapi.config.jsonapi.enabled === true)) {
yield next;
} else if (this.request.type !== 'application/vnd.api+json') {
this.response.status = 406;
this.response.body = '';
} else {
try {
yield request.parse(this);
yield next;
} catch (err) {
_.assign(this.response, err);
}
}
};
2016-01-22 15:40:43 +01:00
}
};
return hook;
};