forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.ts
155 lines (132 loc) · 4.88 KB
/
client.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/**
* @description
* HTTP code snippet generator for Node.js using node-fetch.
*
* @author
* @hirenoble
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
import type { Client } from '../../index.js';
import stringifyObject from 'stringify-object';
import { CodeBuilder } from '../../../helpers/code-builder.js';
import { getHeaderName } from '../../../helpers/headers.js';
export const fetch: Client = {
info: {
key: 'fetch',
title: 'Fetch',
link: 'https://github.com/bitinn/node-fetch',
description: 'Simplified HTTP node-fetch client',
extname: '.cjs',
installation: 'npm install node-fetch@2 --save',
},
convert: ({ method, fullUrl, postData, headersObj, cookies }, options) => {
const opts = {
indent: ' ',
...options,
};
let includeFS = false;
const { blank, push, join, unshift } = new CodeBuilder({ indent: opts.indent });
push("const fetch = require('node-fetch');");
const url = fullUrl;
const reqOpts: Record<string, any> = {
method,
};
if (Object.keys(headersObj).length) {
reqOpts.headers = headersObj;
}
switch (postData.mimeType) {
case 'application/x-www-form-urlencoded':
unshift("const { URLSearchParams } = require('url');");
push('const encodedParams = new URLSearchParams();');
blank();
postData.params?.forEach(param => {
push(`encodedParams.set('${param.name}', '${param.value}');`);
});
reqOpts.body = 'encodedParams';
break;
case 'application/json':
if (postData.jsonObj) {
// Though `fetch` doesn't accept JSON objects in the `body` option we're going to
// stringify it when we add this into the snippet further down.
reqOpts.body = postData.jsonObj;
}
break;
case 'multipart/form-data':
if (!postData.params) {
break;
}
// The `form-data` module automatically adds a `Content-Type` header for `multipart/form-data` content and if we add our own here data won't be correctly transmitted.
// eslint-disable-next-line no-case-declarations -- We're only using `contentTypeHeader` within this block.
const contentTypeHeader = getHeaderName(headersObj, 'content-type');
if (contentTypeHeader) {
delete headersObj[contentTypeHeader];
}
unshift("const FormData = require('form-data');");
push('const formData = new FormData();');
blank();
postData.params.forEach(param => {
if (!param.fileName && !param.fileName && !param.contentType) {
push(`formData.append('${param.name}', '${param.value}');`);
return;
}
if (param.fileName) {
includeFS = true;
push(`formData.append('${param.name}', fs.createReadStream('${param.fileName}'));`);
}
});
break;
default:
if (postData.text) {
reqOpts.body = postData.text;
}
}
// construct cookies argument
if (cookies.length) {
const cookiesString = cookies
.map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`)
.join('; ');
if (reqOpts.headers) {
reqOpts.headers.cookie = cookiesString;
} else {
reqOpts.headers = {};
reqOpts.headers.cookie = cookiesString;
}
}
blank();
push(`const url = '${url}';`);
// If we ultimately don't have any headers to send then we shouldn't add an empty object into the request options.
if (reqOpts.headers && !Object.keys(reqOpts.headers).length) {
delete reqOpts.headers;
}
const stringifiedOptions = stringifyObject(reqOpts, {
indent: ' ',
inlineCharacterLimit: 80,
// The Fetch API body only accepts string parameters, but stringified JSON can be difficult to
// read, so we keep the object as a literal and use this transform function to wrap the literal
// in a `JSON.stringify` call.
transform: (object, property, originalResult) => {
if (property === 'body' && postData.mimeType === 'application/json') {
return `JSON.stringify(${originalResult})`;
}
return originalResult;
},
});
push(`const options = ${stringifiedOptions};`);
blank();
if (includeFS) {
unshift("const fs = require('fs');");
}
if (postData.params && postData.mimeType === 'multipart/form-data') {
push('options.body = formData;');
blank();
}
push('fetch(url, options)');
push('.then(res => res.json())', 1);
push('.then(json => console.log(json))', 1);
push(".catch(err => console.error('error:' + err));", 1);
return join()
.replace(/'encodedParams'/, 'encodedParams')
.replace(/"fs\.createReadStream\(\\"(.+)\\"\)"/, 'fs.createReadStream("$1")');
},
};