swiftyper-node 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/utils.js CHANGED
@@ -1,277 +1,272 @@
1
- 'use strict';
2
-
3
- const qs = require('qs');
4
-
5
- const hasOwn = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
6
-
7
- const OPTIONS_KEYS = [
8
- 'maxNetworkRetries',
9
- 'timeout',
10
- ];
11
-
12
- const DEPRECATED_OPTIONS = {};
13
-
14
- const DEPRECATED_OPTIONS_KEYS = Object.keys(DEPRECATED_OPTIONS);
15
-
16
- const utils = (module.exports = {
17
- isOptionsHash(o) {
18
- return (
19
- o &&
20
- typeof o === 'object' &&
21
- (OPTIONS_KEYS.some((prop) => hasOwn(o, prop)) ||
22
- DEPRECATED_OPTIONS_KEYS.some((prop) => hasOwn(o, prop)))
23
- );
24
- },
25
-
26
- /**
27
- * Stringifies an Object, accommodating nested objects
28
- * (forming the conventional key 'parent[child]=value')
29
- */
30
- stringifyRequestData: (data) => {
31
- return (
32
- qs
33
- .stringify(data, {
34
- serializeDate: (d) => Math.floor(d.getTime() / 1000),
35
- })
36
- .replace(/%5B/g, '[')
37
- .replace(/%5D/g, ']')
38
- );
39
- },
40
-
41
- /**
42
- * Outputs a new function with interpolated object property values.
43
- * Use like so:
44
- * const fn = makeURLInterpolator('some/url/{param1}/{param2}');
45
- * fn({ param1: 123, param2: 456 }); // => 'some/url/123/456'
46
- */
47
- makeURLInterpolator: (() => {
48
- const rc = {
49
- '\n': '\\n',
50
- '"': '\\"',
51
- '\u2028': '\\u2028',
52
- '\u2029': '\\u2029',
53
- };
54
- return (str) => {
55
- const cleanString = str.replace(/["\n\r\u2028\u2029]/g, ($0) => rc[$0]);
56
- return (outputs) => {
57
- return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) =>
58
- encodeURIComponent(outputs[$1] || '')
59
- );
60
- };
61
- };
62
- })(),
63
-
64
- extractUrlParams: (path) => {
65
- const params = path.match(/\{\w+\}/g);
66
- if (!params) {
67
- return [];
68
- }
69
-
70
- return params.map((param) => param.replace(/[{}]/g, ''));
71
- },
72
-
73
- /**
74
- * Return the data argument from a list of arguments
75
- *
76
- * @param {object[]} args
77
- * @returns {object}
78
- */
79
- getDataFromArgs(args) {
80
- if (!Array.isArray(args) || !args[0] || typeof args[0] !== 'object') {
81
- return {};
82
- }
83
-
84
- if (!utils.isOptionsHash(args[0])) {
85
- return args.shift();
86
- }
87
-
88
- const argKeys = Object.keys(args[0]);
89
-
90
- const optionKeysInArgs = argKeys.filter((key) =>
91
- OPTIONS_KEYS.includes(key)
92
- );
93
-
94
- if (
95
- optionKeysInArgs.length > 0 &&
96
- optionKeysInArgs.length !== argKeys.length
97
- ) {
98
- emitWarning(
99
- `Options found in arguments (${optionKeysInArgs.join(
100
- ', '
101
- )}). Did you mean to pass an options object? See https://github.com/swiftyper-sk/swiftyper-node/wiki/Passing-Options.`
102
- );
103
- }
104
-
105
- return {};
106
- },
107
-
108
- /**
109
- * Return the options hash from a list of arguments
110
- */
111
- getOptionsFromArgs: (args) => {
112
- const opts = {
113
- auth: null,
114
- headers: {},
115
- settings: {},
116
- };
117
- if (args.length > 0) {
118
- const arg = args[args.length - 1];
119
- if (typeof arg === 'string') {
120
- opts.auth = args.pop();
121
- } else if (utils.isOptionsHash(arg)) {
122
- const params = {...args.pop()};
123
-
124
- const extraKeys = Object.keys(params).filter(
125
- (key) => !OPTIONS_KEYS.includes(key)
126
- );
127
-
128
- if (extraKeys.length) {
129
- const nonDeprecated = extraKeys.filter((key) => {
130
- if (!DEPRECATED_OPTIONS[key]) {
131
- return true;
132
- }
133
- const newParam = DEPRECATED_OPTIONS[key];
134
- if (params[newParam]) {
135
- throw Error(
136
- `Both '${newParam}' and '${key}' were provided; please remove '${key}', which is deprecated.`
137
- );
138
- }
139
- /**
140
- * TODO turn this into a hard error in a future major version (once we have fixed our docs).
141
- */
142
- emitWarning(`'${key}' is deprecated; use '${newParam}' instead.`);
143
- params[newParam] = params[key];
144
- });
145
- if (nonDeprecated.length) {
146
- emitWarning(
147
- `Invalid options found (${extraKeys.join(', ')}); ignoring.`
148
- );
149
- }
150
- }
151
-
152
- if (Number.isInteger(params.maxNetworkRetries)) {
153
- opts.settings.maxNetworkRetries = params.maxNetworkRetries;
154
- }
155
- if (Number.isInteger(params.timeout)) {
156
- opts.settings.timeout = params.timeout;
157
- }
158
- }
159
- }
160
- return opts;
161
- },
162
-
163
- /**
164
- * Provide simple "Class" extension mechanism
165
- */
166
- protoExtend(sub) {
167
- const Super = this;
168
- const Constructor = hasOwn(sub, 'constructor')
169
- ? sub.constructor
170
- : function(...args) {
171
- Super.apply(this, args);
172
- };
173
-
174
- Object.assign(Constructor, Super);
175
- Constructor.prototype = Object.create(Super.prototype);
176
- Object.assign(Constructor.prototype, sub);
177
-
178
- return Constructor;
179
- },
180
-
181
- /**
182
- * Remove empty values from an object
183
- */
184
- removeNullish: (obj) => {
185
- if (typeof obj !== 'object') {
186
- throw new Error('Argument must be an object');
187
- }
188
-
189
- return Object.keys(obj).reduce((result, key) => {
190
- if (obj[key] != null) {
191
- result[key] = obj[key];
192
- }
193
- return result;
194
- }, {});
195
- },
196
-
197
- /**
198
- * Normalize standard HTTP Headers:
199
- * {'foo-bar': 'hi'}
200
- * becomes
201
- * {'Foo-Bar': 'hi'}
202
- */
203
- normalizeHeaders: (obj) => {
204
- if (!(obj && typeof obj === 'object')) {
205
- return obj;
206
- }
207
-
208
- return Object.keys(obj).reduce((result, header) => {
209
- result[utils.normalizeHeader(header)] = obj[header];
210
- return result;
211
- }, {});
212
- },
213
-
214
- /**
215
- * Stolen from https://github.com/marten-de-vries/header-case-normalizer/blob/master/index.js#L36-L41
216
- * without the exceptions which are irrelevant to us.
217
- */
218
- normalizeHeader: (header) => {
219
- return header
220
- .split('-')
221
- .map(
222
- (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()
223
- )
224
- .join('-');
225
- },
226
-
227
- callbackifyPromiseWithTimeout: (promise, callback) => {
228
- if (callback) {
229
- // Ensure callback is called outside of promise stack.
230
- return promise.then(
231
- (res) => {
232
- setTimeout(() => {
233
- callback(null, res);
234
- }, 0);
235
- },
236
- (err) => {
237
- setTimeout(() => {
238
- callback(err, null);
239
- }, 0);
240
- }
241
- );
242
- }
243
-
244
- return promise;
245
- },
246
-
247
- /**
248
- * Allow for special capitalization cases
249
- */
250
- pascalToCamelCase: (name) => {
251
- return name[0].toLowerCase() + name.substring(1);
252
- },
253
-
254
- emitWarning,
255
-
256
- validateInteger: (name, n, defaultVal) => {
257
- if (!Number.isInteger(n)) {
258
- if (defaultVal !== undefined) {
259
- return defaultVal;
260
- } else {
261
- throw new Error(`${name} must be an integer`);
262
- }
263
- }
264
-
265
- return n;
266
- },
267
- });
268
-
269
- function emitWarning(warning) {
270
- if (typeof process.emitWarning !== 'function') {
271
- return console.warn(
272
- `Swiftyper: ${warning}`
273
- ); /* eslint-disable-line no-console */
274
- }
275
-
276
- return process.emitWarning(warning, 'Swiftyper');
277
- }
1
+ 'use strict';
2
+
3
+ const qs = require('qs');
4
+
5
+ const hasOwn = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
6
+
7
+ const OPTIONS_KEYS = ['maxNetworkRetries', 'timeout'];
8
+
9
+ const DEPRECATED_OPTIONS = {};
10
+
11
+ const DEPRECATED_OPTIONS_KEYS = Object.keys(DEPRECATED_OPTIONS);
12
+
13
+ const utils = (module.exports = {
14
+ isOptionsHash(o) {
15
+ return (
16
+ o &&
17
+ typeof o === 'object' &&
18
+ (OPTIONS_KEYS.some((prop) => hasOwn(o, prop)) ||
19
+ DEPRECATED_OPTIONS_KEYS.some((prop) => hasOwn(o, prop)))
20
+ );
21
+ },
22
+
23
+ /**
24
+ * Stringifies an Object, accommodating nested objects
25
+ * (forming the conventional key 'parent[child]=value')
26
+ */
27
+ stringifyRequestData: (data) => {
28
+ return qs
29
+ .stringify(data, {
30
+ serializeDate: (d) => Math.floor(d.getTime() / 1000),
31
+ })
32
+ .replace(/%5B/g, '[')
33
+ .replace(/%5D/g, ']');
34
+ },
35
+
36
+ /**
37
+ * Outputs a new function with interpolated object property values.
38
+ * Use like so:
39
+ * const fn = makeURLInterpolator('some/url/{param1}/{param2}');
40
+ * fn({ param1: 123, param2: 456 }); // => 'some/url/123/456'
41
+ */
42
+ makeURLInterpolator: (() => {
43
+ const rc = {
44
+ '\n': '\\n',
45
+ '"': '\\"',
46
+ '\u2028': '\\u2028',
47
+ '\u2029': '\\u2029',
48
+ };
49
+ return (str) => {
50
+ const cleanString = str.replace(/["\n\r\u2028\u2029]/g, ($0) => rc[$0]);
51
+ return (outputs) => {
52
+ return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) =>
53
+ encodeURIComponent(outputs[$1] || '')
54
+ );
55
+ };
56
+ };
57
+ })(),
58
+
59
+ extractUrlParams: (path) => {
60
+ const params = path.match(/\{\w+\}/g);
61
+ if (!params) {
62
+ return [];
63
+ }
64
+
65
+ return params.map((param) => param.replace(/[{}]/g, ''));
66
+ },
67
+
68
+ /**
69
+ * Return the data argument from a list of arguments
70
+ *
71
+ * @param {object[]} args
72
+ * @returns {object}
73
+ */
74
+ getDataFromArgs(args) {
75
+ if (!Array.isArray(args) || !args[0] || typeof args[0] !== 'object') {
76
+ return {};
77
+ }
78
+
79
+ if (!utils.isOptionsHash(args[0])) {
80
+ return args.shift();
81
+ }
82
+
83
+ const argKeys = Object.keys(args[0]);
84
+
85
+ const optionKeysInArgs = argKeys.filter((key) =>
86
+ OPTIONS_KEYS.includes(key)
87
+ );
88
+
89
+ if (
90
+ optionKeysInArgs.length > 0 &&
91
+ optionKeysInArgs.length !== argKeys.length
92
+ ) {
93
+ emitWarning(
94
+ `Options found in arguments (${optionKeysInArgs.join(
95
+ ', '
96
+ )}). Did you mean to pass an options object? See https://github.com/swiftyper-sk/swiftyper-node/wiki/Passing-Options.`
97
+ );
98
+ }
99
+
100
+ return {};
101
+ },
102
+
103
+ /**
104
+ * Return the options hash from a list of arguments
105
+ */
106
+ getOptionsFromArgs: (args) => {
107
+ const opts = {
108
+ auth: null,
109
+ headers: {},
110
+ settings: {},
111
+ };
112
+ if (args.length > 0) {
113
+ const arg = args[args.length - 1];
114
+ if (typeof arg === 'string') {
115
+ opts.auth = args.pop();
116
+ } else if (utils.isOptionsHash(arg)) {
117
+ const params = {...args.pop()};
118
+
119
+ const extraKeys = Object.keys(params).filter(
120
+ (key) => !OPTIONS_KEYS.includes(key)
121
+ );
122
+
123
+ if (extraKeys.length) {
124
+ const nonDeprecated = extraKeys.filter((key) => {
125
+ if (!DEPRECATED_OPTIONS[key]) {
126
+ return true;
127
+ }
128
+ const newParam = DEPRECATED_OPTIONS[key];
129
+ if (params[newParam]) {
130
+ throw Error(
131
+ `Both '${newParam}' and '${key}' were provided; please remove '${key}', which is deprecated.`
132
+ );
133
+ }
134
+ /**
135
+ * TODO turn this into a hard error in a future major version (once we have fixed our docs).
136
+ */
137
+ emitWarning(`'${key}' is deprecated; use '${newParam}' instead.`);
138
+ params[newParam] = params[key];
139
+ });
140
+ if (nonDeprecated.length) {
141
+ emitWarning(
142
+ `Invalid options found (${extraKeys.join(', ')}); ignoring.`
143
+ );
144
+ }
145
+ }
146
+
147
+ if (Number.isInteger(params.maxNetworkRetries)) {
148
+ opts.settings.maxNetworkRetries = params.maxNetworkRetries;
149
+ }
150
+ if (Number.isInteger(params.timeout)) {
151
+ opts.settings.timeout = params.timeout;
152
+ }
153
+ }
154
+ }
155
+ return opts;
156
+ },
157
+
158
+ /**
159
+ * Provide simple "Class" extension mechanism
160
+ */
161
+ protoExtend(sub) {
162
+ const Super = this;
163
+ const Constructor = hasOwn(sub, 'constructor')
164
+ ? sub.constructor
165
+ : function (...args) {
166
+ Super.apply(this, args);
167
+ };
168
+
169
+ Object.assign(Constructor, Super);
170
+ Constructor.prototype = Object.create(Super.prototype);
171
+ Object.assign(Constructor.prototype, sub);
172
+
173
+ return Constructor;
174
+ },
175
+
176
+ /**
177
+ * Remove empty values from an object
178
+ */
179
+ removeNullish: (obj) => {
180
+ if (typeof obj !== 'object') {
181
+ throw new Error('Argument must be an object');
182
+ }
183
+
184
+ return Object.keys(obj).reduce((result, key) => {
185
+ if (obj[key] != null) {
186
+ result[key] = obj[key];
187
+ }
188
+ return result;
189
+ }, {});
190
+ },
191
+
192
+ /**
193
+ * Normalize standard HTTP Headers:
194
+ * {'foo-bar': 'hi'}
195
+ * becomes
196
+ * {'Foo-Bar': 'hi'}
197
+ */
198
+ normalizeHeaders: (obj) => {
199
+ if (!(obj && typeof obj === 'object')) {
200
+ return obj;
201
+ }
202
+
203
+ return Object.keys(obj).reduce((result, header) => {
204
+ result[utils.normalizeHeader(header)] = obj[header];
205
+ return result;
206
+ }, {});
207
+ },
208
+
209
+ /**
210
+ * Stolen from https://github.com/marten-de-vries/header-case-normalizer/blob/master/index.js#L36-L41
211
+ * without the exceptions which are irrelevant to us.
212
+ */
213
+ normalizeHeader: (header) => {
214
+ return header
215
+ .split('-')
216
+ .map(
217
+ (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()
218
+ )
219
+ .join('-');
220
+ },
221
+
222
+ callbackifyPromiseWithTimeout: (promise, callback) => {
223
+ if (callback) {
224
+ // Ensure callback is called outside of promise stack.
225
+ return promise.then(
226
+ (res) => {
227
+ setTimeout(() => {
228
+ callback(null, res);
229
+ }, 0);
230
+ },
231
+ (err) => {
232
+ setTimeout(() => {
233
+ callback(err, null);
234
+ }, 0);
235
+ }
236
+ );
237
+ }
238
+
239
+ return promise;
240
+ },
241
+
242
+ /**
243
+ * Allow for special capitalization cases
244
+ */
245
+ pascalToCamelCase: (name) => {
246
+ return name[0].toLowerCase() + name.substring(1);
247
+ },
248
+
249
+ emitWarning,
250
+
251
+ validateInteger: (name, n, defaultVal) => {
252
+ if (!Number.isInteger(n)) {
253
+ if (defaultVal !== undefined) {
254
+ return defaultVal;
255
+ } else {
256
+ throw new Error(`${name} must be an integer`);
257
+ }
258
+ }
259
+
260
+ return n;
261
+ },
262
+ });
263
+
264
+ function emitWarning(warning) {
265
+ if (typeof process.emitWarning !== 'function') {
266
+ return console.warn(
267
+ `Swiftyper: ${warning}`
268
+ ); /* eslint-disable-line no-console */
269
+ }
270
+
271
+ return process.emitWarning(warning, 'Swiftyper');
272
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swiftyper-node",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "description": "Swiftyper API",
5
5
  "keywords": [
6
6
  "swiftyper",