forked from watson-developer-cloud/node-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.ts
247 lines (228 loc) · 6.66 KB
/
helper.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* Copyright 2014 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import extend = require('extend');
import fileType = require('file-type');
import { isReadable } from 'isstream';
import { lookup } from 'mime-types';
import { basename } from 'path';
// exported interfaces
export interface FileObject {
value: NodeJS.ReadableStream | Buffer | string;
options?: FileOptions;
}
// internal interfaces
export interface FileOptions {
filename?: string;
contentType?: string;
}
export interface FileParamAttributes {
data: NodeJS.ReadableStream | Buffer | FileObject;
contentType: string;
filename: string;
}
export interface FileStream extends NodeJS.ReadableStream {
path: string | Buffer;
}
// custom type guards
function isFileObject(obj: any): obj is FileObject {
return obj && obj.value;
}
function isFileStream(obj: any): obj is FileStream {
return obj && isReadable(obj) && obj.path;
}
export function isFileParam(obj: any): boolean {
return (
obj &&
(isReadable(obj) || Buffer.isBuffer(obj) || isFileObject(obj) || obj.data)
);
}
export function isEmptyObject(obj: any): boolean {
return obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}
/**
* This function retrieves the content type of the input.
* @param {NodeJS.ReadableStream|Buffer|string} inputData - The data to retrieve content type for.
* @returns {string} the content type of the input.
*/
export function getContentType(
inputData: NodeJS.ReadableStream | Buffer | string
): string {
let contentType = null;
if (isFileStream(inputData)) {
// if the inputData is a NodeJS.ReadableStream
const mimeType = lookup(inputData.path);
contentType = { mime: mimeType || null };
} else if (Buffer.isBuffer(inputData)) {
// if the inputData is a Buffer
contentType = fileType(inputData);
} else if (typeof inputData === 'string') {
// if the inputData is a string
contentType = fileType(Buffer.from(inputData));
}
return contentType ? contentType.mime : null;
}
/**
*
* @param {string} url - the url string.
* @returns {string}
*/
export function stripTrailingSlash(url: string): string {
// Match a forward slash / at the end of the string ($)
return url.replace(/\/$/, '');
}
/**
* Validates that all required params are provided
* @param params - the method parameters.
* @param requires - the required parameter names.
* @returns {Error|null}
*/
export function getMissingParams(
params: { [key: string]: any },
requires: string[]
): string[] | Error {
let missing;
if (!requires) {
return null;
} else if (!params) {
missing = requires;
} else {
missing = [];
requires.forEach((require) => {
if (!params[require]) {
missing.push(require);
}
});
}
return missing.length > 0
? new Error('Missing required parameters: ' + missing.join(', '))
: null;
}
/**
* Return true if 'text' is html
* @param {string} text - The 'text' to analyze
* @returns {boolean} true if 'text' has html tags
*/
export function isHTML(text: string): boolean {
return /<[a-z][\s\S]*>/i.test(text);
}
/**
* Returns the first match from formats that is key the params map
* otherwise null
* @param {Object} params - The parameters.
* @param {string[]} requires - The keys we want to check
* @returns {string|null}
*/
export function getFormat(
params: { [key: string]: any },
formats: string[]
): string {
if (!formats || !params) {
return null;
}
for (const item of formats) {
if (item in params) {
return item;
}
}
return null;
}
/**
* this function builds a `form-data` object for each file parameter
* @param {FileParamAttributes} fileParams - the file parameter attributes
* @param {NodeJS.ReadableStream|Buffer|FileObject} fileParams.data - the data content of the file
* @param {string} fileParams.contentType - the content type of the file
* @returns {FileObject}
*/
export function buildRequestFileObject(
fileParams: FileParamAttributes
): FileObject {
// build filename
let filename: string | Buffer;
if (fileParams.filename) {
// prioritize user-given filenames
filename = fileParams.filename;
} else if (
isFileObject(fileParams.data) &&
fileParams.data.options &&
fileParams.data.value
) {
// if FileObject with value and options
filename = fileParams.data.options.filename;
} else if (isFileStream(fileParams.data)) {
// if readable stream with path property
filename = fileParams.data.path;
} else if (
isFileObject(fileParams.data) &&
isFileStream(fileParams.data.value)
) {
// if FileObject with stream value
filename = fileParams.data.value.path;
}
// toString handles the case when path is a buffer
filename = filename ? basename(filename.toString()) : '_';
// build contentType
let contentType: string = 'application/octet-stream';
if (
isFileObject(fileParams.data) &&
fileParams.data.options &&
fileParams.data.options.contentType
) {
// if form-data object
contentType = fileParams.data.options.contentType;
} else if (fileParams.contentType) {
// for multiple producers, this is either null, or the _content_type parameter
// for single producers, this is the single content type
contentType = fileParams.contentType;
} else {
// else utilize file-type package
if (isFileObject(fileParams.data)) {
contentType = getContentType(fileParams.data.value) || contentType;
} else {
contentType = getContentType(fileParams.data) || contentType;
}
}
// build value
let value: NodeJS.ReadableStream | Buffer | string = isFileObject(fileParams.data)
? fileParams.data.value
: fileParams.data;
if (typeof value === 'string') {
value = Buffer.from(value);
}
return {
value,
options: {
filename,
contentType
}
};
}
/**
* this function converts an object's keys to lower case
* @param {Object} headers - the header parameters
* @returns {Object}
*/
export function toLowerKeys(obj: Object): Object {
let _obj = {};
if (obj) {
_obj = extend(
{},
...Object.keys(obj).map(key => ({
[key.toLowerCase()]: obj[key]
}))
);
}
return _obj;
}