UNPKG

2.26 kBJavaScriptView Raw
1const requester = require('@axway/requester');
2const mime = require('mime');
3
4const defaultHeaders = {
5 Accept: 'application/json',
6 'Accept-Charset': 'utf-8'
7};
8
9const defaultPostHeaders = {
10 Accept: 'application/json',
11 'Accept-Charset': 'utf-8',
12 'Content-Type': 'application/json; charset=utf-8'
13};
14
15const formats = {
16 json: {
17 parse: (data) => JSON.parse(data),
18 serialize: (data) => {
19 // do not serialize `data` as the new @axway/requester will encode
20 // primitives and objects as JSON (a Buffer can be used to pass
21 // pre-encoded JSON).
22 return data;
23 }
24 }
25};
26
27const header = (headers, key) => {
28 const k = Object.keys(headers).find(s => s.toLowerCase() === key.toLowerCase());
29 return k ? headers[k] : undefined;
30};
31
32const 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
40const 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
48const 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 // Remove `encoding` and delete it from options (it is not a requester
72 // option).
73 delete options.encoding;
74
75 const response = await requester.request(httpOptions, options);
76
77 let { body: responseBody } = response;
78 // encoding is handled by this function now. it used to refer to `encoding`
79 // option in the [request](https://www.npmjs.com/package/request) module,
80 // where if it was `null`, the `body` was returned as a `Buffer`, anything
81 // else, including `undefined`, would be passed to the encoding parameter
82 // for `Buffer.toString`.
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
95exports = module.exports = {
96 invoke: client
97};