-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathreply.ts
More file actions
65 lines (55 loc) · 1.79 KB
/
reply.ts
File metadata and controls
65 lines (55 loc) · 1.79 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Request, Response } from '@intentjs/hyper-express';
import { HttpStatus } from './status-codes.js';
import { isUndefined } from '../../utils/helpers.js';
import { StreamableFile } from './streamable-file.js';
import { instanceToPlain } from 'class-transformer';
export class Reply {
async handle(req: Request, res: Response, dataFromHandler: any) {
const { method } = req;
/**
* Set the status code of the response
*/
if (!res.statusCode && method === 'POST') {
res.status(HttpStatus.CREATED);
} else if (!res.statusCode) {
res.status(HttpStatus.OK);
}
if (dataFromHandler instanceof StreamableFile) {
const headers = dataFromHandler.getHeaders();
if (
isUndefined(res.getHeader('Content-Type')) &&
!isUndefined(headers.type)
) {
res.header('Content-Type', headers.type);
}
if (
isUndefined(res.getHeader('Content-Disposition')) &&
!isUndefined(headers.type)
) {
res.header('Content-Disposition', headers.disposition);
}
if (
isUndefined(res.getHeader('Content-Length')) &&
!isUndefined(headers.length)
) {
res.header('Content-Length', headers.length + '');
}
return res.stream(dataFromHandler.getStream());
}
if (!dataFromHandler) return;
/**
* Default to JSON
*/
let plainData = Array.isArray(dataFromHandler)
? dataFromHandler.map(r => this.transformToPlain(r))
: this.transformToPlain(dataFromHandler);
if (typeof plainData != null && typeof plainData === 'object') {
return res.json(plainData);
}
return res.send(String(plainData));
}
transformToPlain(plainOrClass: any) {
if (!plainOrClass) return plainOrClass;
return instanceToPlain(plainOrClass);
}
}