Override Send response

There is the current implementation of the @@SendResponseMiddleware@@:

import {isBoolean, isNumber, isStream, isString} from "@tsed/core";
import {ConverterService} from "../../converters";
import {Res, ResponseData} from "../../filters";
import {Middleware} from "../decorators";
import {IMiddleware} from "../interfaces/index";

/**
 * See example to override SendResponseMiddleware [here](/docs/middlewares/override/send-response.md).
 * @middleware
 */
@Middleware()
export class SendResponseMiddleware implements IMiddleware {
  constructor(protected converterService: ConverterService) {}

  public use(@ResponseData() data: any, @Res() response: Res) {
    if (data === undefined) {
      return response.send();
    }

    if (isStream(data)) {
      data.pipe(response);

      return response;
    }

    if (isBoolean(data) || isNumber(data) || isString(data) || data === null) {
      return response.send(data);
    }

    return response.json(this.converterService.serialize(data));
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

But for some reason, this implementation isn't enough to meet your needs.

With @@OverrideProvider@@ it's possible to change the default implementation like this:

import {OverrideProvider, Res, ResponseData, SendResponseMiddleware} from "@tsed/common";

@OverrideProvider(SendResponseMiddleware)
export class MySendResponseMiddleware extends SendResponseMiddleware {
  public use(@ResponseData() data: any, @Res() response: Res): any {

    const originalResult = super.use(data, response);

    // ... your instruction
    return {data: originalResult, errors: []};
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

::: tip By default, the server import automatically your middlewares matching with this rules ${rootDir}/middlewares/**/*.ts (See componentScan configuration).

.
├── src
│   ├── controllers
│   ├── services
│   ├── middlewares
│   └── Server.ts
└── package.json
1
2
3
4
5
6
7

If not, just import your middleware in your server or edit the componentScan configuration.

import {ServerLoader, ServerSettings} from "@tsed/common";
import "./src/other/directory/MySendResponseMiddleware";

@ServerSettings({
    ...
})
export class Server extends ServerLoader {}
1
2
3
4
5
6
7

:::