/
header.ts
94 lines (84 loc) · 2.24 KB
/
header.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import {deepMerge} from "@tsed/core";
import {IResponseHeader, IResponseHeaders} from "../../interfaces";
import {EndpointFn} from "./endpointFn";
export type IHeaderOptions = string | number | IResponseHeader;
export interface IHeadersOptions {
[key: string]: IHeaderOptions;
}
/**
* @ignore
*/
export function mapHeaders(headers: IHeadersOptions): IResponseHeaders {
return Object.keys(headers).reduce<IResponseHeaders>((newHeaders: IResponseHeaders, key: string, index: number, array: string[]) => {
const value: any = headers[key];
let type = typeof value;
let options: any = {
value
};
if (type === "object") {
options = value;
type = typeof options.value;
}
options.type = options.type || type;
newHeaders[key] = options;
return newHeaders;
}, {});
}
/**
* Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.
*
* ```typescript
* @Header('Content-Type', 'text/plain');
* private myMethod() {}
*
* @Status(204)
* @Header({
* "Content-Type": "text/plain",
* "Content-Length": 123,
* "ETag": {
* "value": "12345",
* "description": "header description"
* }
* })
* private myMethod() {}
* ```
*
* This example will produce the swagger responses object:
*
* ```json
* {
* "responses": {
* "204": {
* "description": "Description",
* "headers": {
* "Content-Type": {
* "type": "string"
* },
* "Content-Length": {
* "type": "number"
* },
* "ETag": {
* "type": "string",
* "description": "header description"
* }
* }
* }
* }
* }
* ```
*
* @deprecated Use @Returns(200).Header("header", "value")
* @decorator
* @operation
* @response
*/
export function Header(headerName: string | number | IHeadersOptions, headerValue?: IHeaderOptions): Function {
if (headerValue !== undefined) {
headerName = {[headerName as string]: headerValue};
}
const headers: IResponseHeaders = mapHeaders(headerName as IHeadersOptions);
return EndpointFn(endpoint => {
const {response} = endpoint;
response.headers = deepMerge(response.headers || {}, headers);
});
}