Created
March 17, 2020 00:59
-
-
Save bpinedah/bdb4cd655006b4195701c84ff3e1df61 to your computer and use it in GitHub Desktop.
Router article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @description Function to generate handler for lambda | |
* @returns {function(*)} | |
*/ | |
toLambda() { | |
return async event => { | |
// FUNCTIONS HELPERS | |
/** | |
* @description Get a flat array | |
* @param arr Array to flat | |
* @private | |
*/ | |
const _toFlat = arr => [].concat(...arr); | |
// PARAMS | |
const { resource, path, httpMethod: method, queryStringParameters, body } = event; | |
const [ awsPath ] = resource.split('/{proxy*}'); | |
const [, routerPath] = path.split(awsPath); | |
const findPredicate = this._findAndComposeRoute(method.toLowerCase(), routerPath); | |
const routesFound = this._routes.filter(findPredicate); | |
// ROUTES FOUND VALIDATION | |
if ((routesFound.length === 0) || (routesFound.length === 1 && routesFound[0].method === "*")) { | |
return resHandler(404, { message: "Oops route not found on router" }); | |
} | |
// GET MIDDLEWARES FUNCTIONS | |
const functions = routesFound.map(i => ([...i.middlewares])); | |
const lastRoute = [...routesFound].pop(); | |
const pathParams = lastRoute.params; | |
const fns = _toFlat(functions); | |
// ADD PARAMS AND BODY TO NATIVE EVENT | |
event.params = pathParams; | |
event.query = queryStringParameters || {}; | |
event.body = body && method.toLowerCase() !== "get" ? body : {}; | |
return Pipeline.create(fns)(event); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment