@eienjs/adonisjs-jsend
Version:
Simple helpers to generate JSend-compliant JSON responses
51 lines (49 loc) • 1.88 kB
JavaScript
import { ExceptionHandler } from "@adonisjs/core/http";
//#region src/jsend_exception_handler_macros.ts
ExceptionHandler.macro("renderErrorAsJsend", async function(error, ctx) {
let additionalData;
if (this.isDebuggingEnabled(ctx)) {
const { default: Youch } = await import("youch");
additionalData = await new Youch(error, ctx.request.request).toJSON();
}
if (additionalData) {
ctx.response.jsendError(error.message, error.status, {
errors: additionalData,
code: error.code
});
return;
}
ctx.response.jsendFail({ errors: [{
title: error.message,
code: error.code
}] }, error.status);
});
ExceptionHandler.macro("renderValidationErrorAsJsend", async function(error, ctx) {
ctx.response.jsendFail({ errors: error.messages }, error.status);
});
ExceptionHandler.macro("renderError", async function(error, ctx) {
const isJsendEnable = this.usingJsend ?? true;
switch (ctx.request.accepts([
"html",
"application/vnd.api+json",
"json"
])) {
case "application/vnd.api+json": return isJsendEnable ? this.renderErrorAsJsend(error, ctx) : this.renderErrorAsJSONAPI(error, ctx);
case "json": return isJsendEnable ? this.renderErrorAsJsend(error, ctx) : this.renderErrorAsJSON(error, ctx);
default: return this.renderErrorAsHTML(error, ctx);
}
});
ExceptionHandler.macro("renderValidationError", async function(error, ctx) {
const isJsendEnable = this.usingJsend ?? true;
switch (ctx.request.accepts([
"html",
"application/vnd.api+json",
"json"
])) {
case "application/vnd.api+json": return isJsendEnable ? this.renderValidationErrorAsJsend(error, ctx) : this.renderValidationErrorAsJSONAPI(error, ctx);
case "json": return isJsendEnable ? this.renderValidationErrorAsJsend(error, ctx) : this.renderValidationErrorAsJSON(error, ctx);
default: return this.renderValidationErrorAsHTML(error, ctx);
}
});
//#endregion
export { };