This repository has been archived by the owner on Sep 11, 2020. It is now read-only.
/
action_to_http_request.ts
87 lines (71 loc) · 2.07 KB
/
action_to_http_request.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
import { AxiosRequestConfig } from "axios";
import contentType from "content-type";
import URI from "urijs";
import { Action, Field } from "./siren";
export type FieldValueResolverFn = (
field: Field
) => Promise<string | undefined>;
export default async function actionToHttpRequest(
action: Action,
resolver?: FieldValueResolverFn
): Promise<AxiosRequestConfig> {
const fields = action.fields || [];
const fieldValues = await resolveAllFieldValues(fields, resolver);
const requestMethod = action.method ? action.method : "GET";
if (requestMethod === "GET") {
return Promise.resolve({
url: action.href,
method: action.method,
params: fieldValues,
paramsSerializer: (params: any) => {
return URI.buildQuery(params);
},
data: {} // Need to set this because of https://github.com/axios/axios/issues/86
});
} else {
return Promise.resolve({
url: action.href,
method: action.method,
data: fieldValues,
transformRequest: [jsonRequestTransformer, failIfNotBuffer],
headers: {
"Content-Type": action.type
}
});
}
}
function jsonRequestTransformer(data: any, headers: any): any {
const rawContentType = headers["Content-Type"];
if (!rawContentType) {
return data;
}
const parsedContentType = contentType.parse(rawContentType).type;
if (parsedContentType !== "application/json") {
return data; // pass on data to the next transformer
}
return Buffer.from(JSON.stringify(data), "utf-8");
}
function failIfNotBuffer(data: any, headers: any): any {
if (data && !Buffer.isBuffer(data)) {
throw new Error(
`Failed to serialize data for content-type ${headers["Content-Type"]}`
);
}
return data;
}
async function resolveAllFieldValues(
fields: Field[],
resolver?: FieldValueResolverFn
): Promise<any> {
const data: any = {};
if (!resolver) {
return Promise.resolve(data);
}
for (const field of fields) {
const value = await resolver(field);
if (value) {
data[field.name] = value;
}
}
return Promise.resolve(data);
}