How to set a different Http Status in loopback 4
Asked Answered
K

1

8

I can't find any ressources on how to change the success HTTP code using loopback 4.

For example :

201 "created" on post method

204 "no content" on delete method

I tried to specify this in the @api decorator but this change is not reflected in the actual response.

Thank's for your help !

Kielty answered 12/2, 2019 at 17:8 Comment(0)
A
14

I can't find any ressources on how to change the success HTTP code using loopback 4.

We don't have first-class support for this feature yet. The current workaround is to inject the Response object into your controller method and set the status code directly via Express/Node.js core API.

export class TodoController {
  constructor(
    @repository(TodoRepository) protected todoRepo: TodoRepository,
    @inject(RestBindings.Http.RESPONSE) protected response: Response,
  ) {}

  async createTodo(@requestBody() todo: Todo): Promise<Todo> {
    this.response.status(401);
    // ...
  }
}

Don't forget to import Response and RestBindings from @loopback/rest, and inject from @loopback/core. Add the below imports in your controller.

import { Response, RestBindings } from '@loopback/rest';
import { inject } from '@loopback/core';

201 "created" on post method

See the discussion in https://github.com/strongloop/loopback-next/issues/788. The difficult part is how to figure out what URL to send in the Location response header.

204 "no content" on delete method

Just change your controller method to return undefined instead of the current {count: 1} object. I believe this is the default behavior for CRUD controllers scaffolded by our lb4 tool.

export class TodoController {
  // ...
  @del('/todos/{id}', {
    responses: {
      '204': {
        description: 'Todo DELETE success',
      },
    },
  })
  async deleteTodo(@param.path.number('id') id: number): Promise<void> {
    await this.todoRepo.deleteById(id);
  }
Abcoulomb answered 15/2, 2019 at 13:41 Comment(6)
Miroslav, this is not working for me. For this this.response.status(200), I am getting the error Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures.Weathercock
@AshutoshChamoli where is your Response type coming from? Did you import it from @loopback/rest? Until recently, we had to include dom in TypeScript's libs config and as a result, Response was also defined as a global type. Such global DOM Response has different members than Response object provided by Express & Node.jsBanff
@MiroslavBajtoš Its working now, after importing Response from @loopback/rest. Edited the answer too. Thanks :)Weathercock
Also, is there a way I can get faster response for my questions from loopback team. We have a production service running on loopback 4. And we have been making lot of changes, and as a result facing challenges in development and debugging.Weathercock
@MiroslavBajtoš How to mock Response while writing unit test for the controller. Getting the following error Type '{ status: SinonStub<any[], any>; }' is missing the following properties from type 'Response': sendStatus, links, send, json, and 72 more. [2740] let response: Response when I try to mock the response instance response = { status: sinon.stub()}Weathercock
@AshutoshChamoli You can get faster support by buying IBM Advance Support for Runtimes, see developer.ibm.com/node/support. Regarding your second about mocking Response, please open a new StackOverflow question for that.Banff

© 2022 - 2024 — McMap. All rights reserved.