-
Notifications
You must be signed in to change notification settings - Fork 121
/
SimpleResponseWriter.ts
47 lines (43 loc) · 1.93 KB
/
SimpleResponseWriter.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
import { CONTENT_TYPE } from '../../util/MetadataTypes';
import { DATA_TYPE_BINARY } from '../../util/ContentTypes';
import { HttpError } from '../../util/errors/HttpError';
import { HttpResponse } from '../../server/HttpResponse';
import { ResponseDescription } from '../operations/ResponseDescription';
import { ResponseWriter } from './ResponseWriter';
import { UnsupportedHttpError } from '../../util/errors/UnsupportedHttpError';
/**
* Writes to an {@link HttpResponse} based on the incoming {@link ResponseDescription} or error.
*/
export class SimpleResponseWriter extends ResponseWriter {
public async canHandle(input: { response: HttpResponse; result: ResponseDescription | Error }): Promise<void> {
if (!(input.result instanceof Error)) {
const dataType = input.result.body?.dataType;
if (dataType && dataType !== DATA_TYPE_BINARY) {
throw new UnsupportedHttpError('Only binary results are supported.');
}
}
}
public async handle(input: { response: HttpResponse; result: ResponseDescription | Error }): Promise<void> {
if (input.result instanceof Error) {
let code = 500;
if (input.result instanceof HttpError) {
code = input.result.statusCode;
}
input.response.setHeader('content-type', 'text/plain');
input.response.writeHead(code);
input.response.end(`${input.result.name}: ${input.result.message}\n${input.result.stack}`);
} else {
input.response.setHeader('location', input.result.identifier.path);
if (input.result.body) {
const contentType = input.result.body.metadata.get(CONTENT_TYPE)?.value ?? 'text/plain';
input.response.setHeader('content-type', contentType);
input.result.body.data.pipe(input.response);
}
input.response.writeHead(200);
if (!input.result.body) {
// If there is an input body the response will end once the input stream ends
input.response.end();
}
}
}
}