Last active
March 14, 2021 14:54
-
-
Save dantldev/9e3ba4ca72560990fd76af805b16dc5e to your computer and use it in GitHub Desktop.
Helper function to implement middlewares on nextjs
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 _middleware es un objeto con funciones | |
* útiles para user dentro de api routes de nextjs | |
*/ | |
export const _middleware = { | |
/** | |
* @description Si esta función es llamada como primera linea | |
* dentro de un método "handler" en una ruta api de nextjs, | |
* su finalidad es ejecutar tantos middlewares como sea posible | |
* antes de la ejecución del resto de la función. | |
* | |
* Si es llamada dentro de un trycatch (lo cual debería ser así), | |
* esta función retornara un error para ser recibido luego por su | |
* hermana "catch" y devolver un mensaje http de error. | |
* | |
* @param {Request} req Request http object | |
* @param {Response} res Response http object | |
* @param {...any} middlewares one or a set of middleware functions | |
* @example | |
* | |
* try { | |
* await _middleware.run(req, res, middleware1, middleware2, ...); | |
* } catch(error) { | |
* return _middleware.catch(res, error) | |
* } | |
* // el resto del handler y eventualmente | |
* // la respuesta http | |
*/ | |
async run(req, res, ...middlewares) { | |
const fns = [...middlewares]; | |
for (let i = 0; i < fns.length; i++) { | |
const fn = fns[i]; | |
await fn(req, res, (result) => { | |
console.log(typeof result); | |
console.log('this runs'); | |
return result; | |
}); | |
} | |
}, | |
/** | |
* Esta es la función hermana de "run" | |
* ver "run para referencia de uso conjunto." | |
* @param {Response} res Response http object | |
* @param {Error} error An Error throw for another function | |
*/ | |
catch(res, error) { | |
handleError(res, error); | |
}, | |
}; | |
// si no sabes como se construye un middleware... Aquí hay unos ejemplos: | |
// async middleware function example | |
async function setFact(req, res, next) { | |
try { | |
const apiResponse = await fetch('https://cat-fact.herokuapp.com/facts'); | |
const apiData = await apiResponse.json(); | |
req.fact = apiData[0].text; | |
return next(req, res); | |
} catch (error) { | |
// you can throw anything here really | |
throw { errors: 'Ups! this is an error message', status: 500 }; | |
} | |
} | |
// sync middlware function example | |
function testMiddleware(req, res, next) { | |
req.test = 'is working'; | |
return next(req, res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment