2021-06-24 10:09:10 +02:00
|
|
|
import { HttpResponse } from "uWebSockets.js";
|
2020-11-13 18:00:22 +01:00
|
|
|
|
|
|
|
export class BaseController {
|
|
|
|
protected addCorsHeaders(res: HttpResponse): void {
|
2021-06-24 10:09:10 +02:00
|
|
|
res.writeHeader("access-control-allow-headers", "Origin, X-Requested-With, Content-Type, Accept");
|
|
|
|
res.writeHeader("access-control-allow-methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
|
|
|
|
res.writeHeader("access-control-allow-origin", "*");
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
2021-01-17 20:42:33 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Turns any exception into a HTTP response (and logs the error)
|
|
|
|
*/
|
2021-01-18 15:43:27 +01:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2021-01-17 20:42:33 +01:00
|
|
|
protected errorToResponse(e: any, res: HttpResponse): void {
|
2021-03-31 15:48:25 +02:00
|
|
|
if (e && e.message) {
|
|
|
|
let url = e?.config?.url;
|
|
|
|
if (url !== undefined) {
|
2021-06-24 10:09:10 +02:00
|
|
|
url = " for URL: " + url;
|
2021-03-31 15:48:25 +02:00
|
|
|
} else {
|
2021-06-24 10:09:10 +02:00
|
|
|
url = "";
|
2021-03-31 15:48:25 +02:00
|
|
|
}
|
2021-06-24 10:09:10 +02:00
|
|
|
console.error("ERROR: " + e.message + url);
|
|
|
|
} else if (typeof e === "string") {
|
2021-03-31 15:48:25 +02:00
|
|
|
console.error(e);
|
|
|
|
}
|
|
|
|
if (e.stack) {
|
|
|
|
console.error(e.stack);
|
|
|
|
}
|
2021-01-17 20:42:33 +01:00
|
|
|
if (e.response) {
|
2021-06-24 10:09:10 +02:00
|
|
|
res.writeStatus(e.response.status + " " + e.response.statusText);
|
2021-01-17 20:42:33 +01:00
|
|
|
this.addCorsHeaders(res);
|
2021-08-15 08:51:35 +02:00
|
|
|
res.end(
|
|
|
|
"An error occurred: " +
|
|
|
|
e.response.status +
|
|
|
|
" " +
|
|
|
|
(e.response.data && e.response.data.message ? e.response.data.message : e.response.statusText)
|
|
|
|
);
|
2021-01-17 20:42:33 +01:00
|
|
|
} else {
|
2021-06-24 10:09:10 +02:00
|
|
|
res.writeStatus("500 Internal Server Error");
|
2021-01-17 20:42:33 +01:00
|
|
|
this.addCorsHeaders(res);
|
|
|
|
res.end("An error occurred");
|
|
|
|
}
|
|
|
|
}
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|