alagarr
Version:
Alagarr is a request-response helper library that removes the boilerplate from your Node.js serverless functions and helps make your code portable.
48 lines (47 loc) • 1.76 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const html_1 = __importDefault(require("./html"));
const json_1 = __importDefault(require("./json"));
function getBestMatchedFormat(formats, accept) {
const fallback = formats.default || 'html';
const acceptFormats = accept &&
typeof accept === 'string' &&
accept
.split(';')[0]
.split(',')
.map(type => {
const mimeParts = type.split('/');
return mimeParts[mimeParts.length - 1];
});
return ((acceptFormats && acceptFormats.find(type => Reflect.has(formats, type))) ||
fallback);
}
function getBestMatchedResponseHelper(format) {
switch (format) {
case 'html':
return html_1.default;
case 'json':
return json_1.default;
}
throw new TypeError(`"${format}" is not a valid Alagarr respondTo() format.`);
}
function getBestMatchedFormatBody(formats, format) {
switch (format) {
case 'html':
return formats.html;
case 'json':
return formats.json;
}
throw new TypeError(`"${format}" is not a valid Alagarr respondTo() format.`);
}
function respondTo(responseData, request, formats, statusCode, options) {
const { headers: { accept }, } = request;
const format = getBestMatchedFormat(formats, accept);
const responseHelper = getBestMatchedResponseHelper(format);
const body = getBestMatchedFormatBody(formats, format);
return responseHelper(responseData, request, body, statusCode, options);
}
exports.default = respondTo;