-
Hi, I'm developing a REST API backend using Adonis v5. In my prior project using Adonis v4, I had defined a couple of macros on the { response } that is passed to controllers (I had response.success & response.error) using Service Providers. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
So I figured it out, all thanks to @Forsties08! First, we create a contract declare module '@ioc:Adonis/Core/Response' {
interface ResponseContract {
/**
* Macro to handle successful response
* @param data Data to be sent in response
* @param status status of the response
* @param code code, if applicable. Will fallback to status if not provided
*/
success(data: any, status?: number, code?: number): this;
/**
* Macro to handle erroneous response
* @param errors Errors to be sent in response
* @param status status of the response
* @param code code, if applicable. Will fallback to status if not provided
* @param data Extra data to be sent in response, if required
*/
error(errors: any, status?: number, code?: number, data?: any): this;
}
} Once we have defined the contract, we provide the implementation in the boot method of // Add this import
import { ResponseConstructorContract } from '@ioc:Adonis/Core/Response';
// And then in boot method, add the following:
this.$container.with(['Adonis/Core/Response'], (context: ResponseConstructorContract) => {
context.macro('error', function error(errors: any, status = 400, code = null, data = null) {
this.status(status).json({
success: false,
code: code || status,
message: errors,
data,
});
});
context.macro('success', function success(data, status = 200, code = null) {
this.status(200).json({
success: true,
code: code || status,
data,
});
});
}); That's it! Now we can use response.success & response.error in our controllers! |
Beta Was this translation helpful? Give feedback.
So I figured it out, all thanks to @Forsties08!
Here's the code snippets in case someone else is looking for a solution to this:
First, we create a contract
contracts/response.ts
: