It is not clear how to access request/response, context or application instance on a simple controller on Loopback4. Is it available globally or do I inject it into the controller class, if so how, please help.
EDIT: I needed to change the returned status codes of the controller actions, so I thought I would need the Response Context for this, and thought I would need the app to get this response context. Found out that I can get an access to the Context object through DI;
export class TodoController {
constructor(
@repository(TodoRepository)
public todoRepository: TodoRepository,
@inject(RestBindings.Http.CONTEXT) public ctx: Context,
) {}
I would still like to know about all the options to access those global or singleton objects that are available thorughout the app, from a controller, model, repository etc.
For managing response codes, you do not need to use context object. Here is a better way to do this.
For success response, just change the status code in API schema over the controller method.
@post(rolesPath, {
responses: {
200: {
description: 'Role model instance',
content: {
'application/json': {schema: {'x-ts-type': Role}},
},
},
},
})
async create(@requestBody() role: Role): Promise<Role> {
return await this.roleRepository.create(role);
}
For error responses, use HttpErrors interface from http-errors module which is installed as part of lb4 dependencies automatically..
throw new HttpErrors.BadRequest("Some required data missing in request");
This will throw error response code 400. There are almost all the error codes you will ever require in this interface. You can use them.
Now regarding your other question about how to access global objects. You can do that using DI as you have shown in your queston. But its not a good practice to access it inside controllers or repositories. Rather if you really need to change some stuff, you should do it within Sequence. Refer documentation here.