Override Response view

There is the current implementation of the :

import {EndpointInfo, Res, ResponseData} from "../../filters";
import {Middleware} from "../decorators/class/middleware";
import {TemplateRenderingError} from "../errors/TemplateRenderingError";
import {IMiddleware} from "../interfaces";

/**
 * See example to override ResponseViewMiddleware [here](/docs/middlewares/override/response-view.md).
 * @middleware
 */
@Middleware()
export class ResponseViewMiddleware implements IMiddleware {
  public use(@ResponseData() data: any, @EndpointInfo() endpoint: EndpointInfo, @Res() response: Res) {
    return new Promise((resolve, reject) => {
      const {viewPath, viewOptions} = endpoint.store.get(ResponseViewMiddleware);

      if (viewPath !== undefined) {
        if (viewOptions !== undefined) {
          data = Object.assign({}, data, viewOptions);
        }

        response.render(viewPath, data, (err: any, html) => {
          /* istanbul ignore next */
          if (err) {
            reject(new TemplateRenderingError(endpoint.target, endpoint.methodClassName, err));
          } else {
            resolve(html);
          }
        });
      } else {
        resolve();
      }
    });
  }
}
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
33
34

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

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

import {EndpointInfo, Res, ResponseData, ResponseViewMiddleware} from "@tsed/common";
import {OverrideProvider} from "@tsed/di";

@OverrideProvider(ResponseViewMiddleware)
export class MyResponseViewMiddleware extends ResponseViewMiddleware {
  public use(
    @ResponseData() data: any,
    @EndpointInfo() endpoint: EndpointInfo,
    @Res() response: Res
  ): any {

    // DO SOMETHING

    return super.use(data, endpoint, response);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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/MyResponseViewMiddleware";

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