1 | const requester = require('@axway/requester');
|
2 | const mime = require('mime');
|
3 |
|
4 | const defaultHeaders = {
|
5 | Accept: 'application/json',
|
6 | 'Accept-Charset': 'utf-8'
|
7 | };
|
8 |
|
9 | const defaultPostHeaders = {
|
10 | Accept: 'application/json',
|
11 | 'Accept-Charset': 'utf-8',
|
12 | 'Content-Type': 'application/json; charset=utf-8'
|
13 | };
|
14 |
|
15 | const formats = {
|
16 | json: {
|
17 | parse: (data) => JSON.parse(data),
|
18 | serialize: (data) => {
|
19 |
|
20 |
|
21 |
|
22 | return data;
|
23 | }
|
24 | }
|
25 | };
|
26 |
|
27 | const header = (headers, key) => {
|
28 | const k = Object.keys(headers).find(s => s.toLowerCase() === key.toLowerCase());
|
29 | return k ? headers[k] : undefined;
|
30 | };
|
31 |
|
32 | const parse = (body, contentType) => {
|
33 | const key = mime.getExtension(contentType);
|
34 | if (formats.hasOwnProperty(key)) {
|
35 | body = formats[key].parse(body);
|
36 | }
|
37 | return body;
|
38 | };
|
39 |
|
40 | const serialize = (body, contentType) => {
|
41 | const key = mime.getExtension(contentType);
|
42 | if (formats.hasOwnProperty(key)) {
|
43 | body = formats[key].serialize(body);
|
44 | }
|
45 | return body;
|
46 | };
|
47 |
|
48 | const client = async (method, url, body, hdrs, options) => {
|
49 | let headers;
|
50 | if (body) {
|
51 | headers = {
|
52 | ...defaultPostHeaders,
|
53 | ...hdrs
|
54 | };
|
55 | body = serialize(body, header(headers, 'content-type'));
|
56 | } else {
|
57 | headers = {
|
58 | ...defaultHeaders,
|
59 | ...hdrs
|
60 | };
|
61 | }
|
62 |
|
63 | const httpOptions = {
|
64 | method,
|
65 | url,
|
66 | body,
|
67 | headers
|
68 | };
|
69 |
|
70 | const { encoding } = options;
|
71 |
|
72 |
|
73 | delete options.encoding;
|
74 |
|
75 | const response = await requester.request(httpOptions, options);
|
76 |
|
77 | let { body: responseBody } = response;
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 | if (encoding !== null) {
|
84 | responseBody = responseBody.toString(encoding);
|
85 | }
|
86 |
|
87 | const parsed = parse(responseBody, header(response.headers, 'content-type'));
|
88 |
|
89 | return {
|
90 | response,
|
91 | body: parsed
|
92 | };
|
93 | };
|
94 |
|
95 | exports = module.exports = {
|
96 | invoke: client
|
97 | };
|