Skip to content

Instantly share code, notes, and snippets.

@Deepak13245
Created January 6, 2024 10:36
Show Gist options
  • Save Deepak13245/dc243e54a7a42e0b7129d2aea01c26b1 to your computer and use it in GitHub Desktop.
Save Deepak13245/dc243e54a7a42e0b7129d2aea01c26b1 to your computer and use it in GitHub Desktop.
Controller decorator
export function ControllerDecorator() {
// returns a function which takes constructor of class as argument
return constructor => {
// apply custom logic to each function of the controller class
constructor.elements.forEach(element => {
applyDecorator(element.descriptor);
});
return constructor;
}
}
function applyDecorator(descriptor) {
// store the original function
const original = descriptor.value;
// replace with custom logic
descriptor.value = function (req, res) {
try {
// call original function
const result = original.apply(this, [req, res]);
// handle response
if (result instanceof Promise) {
result.then((result) => {
handleHttpResponse(res, result);
}).catch((err) => {
handleHttpError(res, err);
});
return;
}
handleHttpResponse(res, result);
} catch (e) {
// handle error
handleHttpError(res, e);
}
}
}
export function handleHttpResponse(res, httpRes) {
Object.entries(httpRes.headers || {}).forEach(([key, value]) => {
res.set(key, value);
});
if (httpRes instanceof HttpResponse) {
res.status(httpRes.status).json(httpRes.body);
return;
}
res.status(200).json(httpRes);
}
export function handleHttpError(res, httpError) {
if (httpError instanceof HttpError) {
res.status(httpError.status)
.json({
message: httpError.message,
});
return;
}
res.status(500).json({
message: httpError.message,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment