@bitblit/epsilon
Version:
Tiny adapter to simplify building API gateway Lambda APIS
230 lines • 12.5 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var yaml = require("js-yaml");
var misconfigured_error_1 = require("../error/misconfigured-error");
var model_validator_1 = require("./model-validator");
var logger_1 = require("@bitblit/ratchet/dist/common/logger");
var boolean_ratchet_1 = require("@bitblit/ratchet/dist/common/boolean-ratchet");
var built_in_handlers_1 = require("./built-in-handlers");
var response_util_1 = require("../response-util");
/**
* Endpoints about the api itself
*/
var RouterUtil = /** @class */ (function () {
function RouterUtil() {
} // Prevent instantiation
// Parses an open api file to create a router config
RouterUtil.openApiYamlToRouterConfig = function (yamlString, handlers, authorizers, options, errorProcessor, defaultTimeoutMS, customTimeouts, inCorsHandler) {
var _this = this;
if (options === void 0) { options = RouterUtil.createDefaultOpenApiConvertOptions(); }
if (errorProcessor === void 0) { errorProcessor = built_in_handlers_1.BuiltInHandlers.defaultErrorProcessor; }
if (defaultTimeoutMS === void 0) { defaultTimeoutMS = 30 * 1000; }
if (customTimeouts === void 0) { customTimeouts = new Map(); }
if (inCorsHandler === void 0) { inCorsHandler = null; }
if (!yamlString) {
throw new misconfigured_error_1.MisconfiguredError('Cannot configure, missing either yaml or cfg');
}
var doc = yaml.load(yamlString);
var rval = {
authorizers: authorizers,
routes: [],
errorProcessor: errorProcessor
};
var corsHandler = inCorsHandler;
if (!corsHandler) {
var corsOb_1 = RouterUtil.buildCorsResponse();
corsHandler = function (e) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, corsOb_1];
});
}); };
}
if (doc['components'] && doc['components']['schemas']) {
rval.modelValidator = model_validator_1.ModelValidator.createFromParsedOpenApiObject(doc);
}
if (doc['components'] && doc['components']['securitySchemes']) {
// Just validation, nothing to wire here
Object.keys(doc['components']['securitySchemes']).forEach(function (sk) {
if (!authorizers || !authorizers.get(sk)) {
throw new misconfigured_error_1.MisconfiguredError('Doc requires authorizer ' + sk + ' but not found in map');
}
});
}
var missingPaths = [];
if (doc['paths']) {
Object.keys(doc['paths']).forEach(function (path) {
Object.keys(doc['paths'][path]).forEach(function (method) {
var convertedPath = RouterUtil.openApiPathToRouteParserPath(path);
if (method.toLowerCase() === 'options' && options.autoCORSOptionHandler) {
rval.routes.push({
path: convertedPath,
method: method,
function: corsHandler,
authorizerName: null,
disableAutomaticBodyParse: true,
disableQueryMapAssure: true,
disableHeaderMapAssure: true,
disablePathMapAssure: true,
timeoutMS: 10000,
validation: null
});
}
else {
var finder = method + ' ' + path;
var entry = doc['paths'][path][method];
if (!handlers || !handlers.get(finder)) {
missingPaths.push(finder);
}
if (entry && entry['security'] && entry['security'].length > 1) {
throw new misconfigured_error_1.MisconfiguredError('Epsilon does not currently support multiple security (path was ' + finder + ')');
}
var authorizerName = entry['security'] && entry['security'].length == 1 ? Object.keys(entry['security'][0])[0] : null;
var timeoutMS = customTimeouts.get(finder) || defaultTimeoutMS;
var newRoute = {
path: convertedPath,
method: method,
function: handlers.get(finder),
authorizerName: authorizerName,
disableAutomaticBodyParse: options.disableAutomaticBodyParse,
disableQueryMapAssure: options.disableQueryMapAssure,
disableHeaderMapAssure: options.disableHeaderMapAssure,
disablePathMapAssure: options.disablePathMapAssure,
timeoutMS: timeoutMS,
validation: null
};
if (entry['requestBody'] &&
entry['requestBody']['content'] &&
entry['requestBody']['content']['application/json'] &&
entry['requestBody']['content']['application/json']['schema']) {
// TODO: this is brittle as hell, need to firm up
var schema = entry['requestBody']['content'];
logger_1.Logger.silly('Applying schema %j to %s', schema, finder);
var modelName = _this.findAndValidateModelName(method, path, schema, rval.modelValidator);
var required = boolean_ratchet_1.BooleanRatchet.parseBool(entry['requestBody']['required']);
var validation = {
extraPropertiesAllowed: true,
emptyAllowed: !required,
modelName: modelName
};
newRoute.validation = validation;
}
rval.routes.push(newRoute);
}
});
});
}
if (missingPaths.length > 0) {
throw new misconfigured_error_1.MisconfiguredError('Missing expected handlers : "' + JSON.stringify(missingPaths));
}
return rval;
};
RouterUtil.findAndValidateModelName = function (method, path, schema, modelValidator) {
var rval = undefined;
var schemaPath = schema['application/json']['schema']['$ref'];
var inlinePath = schema['application/json']['schema']['type'];
if (schemaPath) {
rval = schemaPath.substring(schemaPath.lastIndexOf('/') + 1);
if (!modelValidator.fetchModel(rval)) {
throw new misconfigured_error_1.MisconfiguredError("Path " + method + " " + path + " refers to schema " + rval + " but its not in the schema section");
}
}
else if (inlinePath) {
rval = method + "-" + path + "-requestBodyModel";
var model = schema['application/json']['schema'];
modelValidator.addModel(rval, model);
}
return rval;
};
RouterUtil.openApiPathToRouteParserPath = function (input) {
var rval = input;
if (rval) {
var sIdx = rval.indexOf('{');
while (sIdx > -1) {
var eIdx = rval.indexOf('}');
rval = rval.substring(0, sIdx) + ':' + rval.substring(sIdx + 1, eIdx) + rval.substring(eIdx + 1);
sIdx = rval.indexOf('{');
}
}
return rval;
};
RouterUtil.createDefaultOpenApiConvertOptions = function () {
return {
autoCORSOptionHandler: true,
disableAutomaticBodyParse: false,
disableQueryMapAssure: false,
disableHeaderMapAssure: false,
disablePathMapAssure: false
};
};
RouterUtil.buildCorsResponse = function (allowedOrigins, allowedMethods, allowedHeaders, body, statusCode) {
if (allowedOrigins === void 0) { allowedOrigins = '*'; }
if (allowedMethods === void 0) { allowedMethods = '*'; }
if (allowedHeaders === void 0) { allowedHeaders = '*'; }
if (body === void 0) { body = '{"cors":true}'; }
if (statusCode === void 0) { statusCode = 200; }
var rval = {
statusCode: statusCode,
body: body,
headers: {
'Access-Control-Allow-Origin': allowedOrigins || '*',
'Access-Control-Allow-Methods': allowedMethods || '*',
'Access-Control-Allow-Headers': allowedHeaders || '*'
}
};
return rval;
};
RouterUtil.buildCorsResponseForRouterConfig = function (cfg) {
return RouterUtil.buildCorsResponse(cfg.corsAllowedOrigins || '*', cfg.corsAllowedMethods || '*', cfg.corsAllowedHeaders || '*', '{"cors":true}', 200);
};
RouterUtil.defaultReflectiveCorsOptionsFunction = function (evt) {
var corsResponse = RouterUtil.buildCorsResponse(response_util_1.ResponseUtil.buildReflectCorsAllowOrigin(evt, '*'), response_util_1.ResponseUtil.buildReflectCorsAllowMethods(evt, '*'), response_util_1.ResponseUtil.buildReflectCorsAllowHeaders(evt, '*'), '', 204);
return corsResponse;
};
// Thin wrapper to implement the handler interface
RouterUtil.DEFAULT_REFLECTIVE_CORS_OPTION_HANDLER = function (e) { return __awaiter(void 0, void 0, void 0, function () {
var rval;
return __generator(this, function (_a) {
rval = RouterUtil.defaultReflectiveCorsOptionsFunction(e);
return [2 /*return*/, rval];
});
}); };
return RouterUtil;
}());
exports.RouterUtil = RouterUtil;
//# sourceMappingURL=router-util.js.map