-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathutils.js
More file actions
111 lines (85 loc) · 2.21 KB
/
Copy pathutils.js
File metadata and controls
111 lines (85 loc) · 2.21 KB
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
import path from 'path';
import url from 'url';
import querystring from 'querystring';
import fs from 'fs';
import stream from 'stream';
import Result from './result';
import ResultFile from './result_file';
import UploadResult from './upload_result';
const URI_REGEXP = /^https?:/i;
const DEFAULT_URL_FORMAT = 'url';
const ANY_FORMAT = 'any';
export const normalizeFilesParam = async (promise) => {
const value = await promise;
if (value instanceof Result) {
return value.files;
}
return Promise.all(value);
};
export const normalizeBaseUri = (baseUri) => {
if (baseUri[baseUri.length - 1] !== '/') {
return `${baseUri}/`;
}
return baseUri;
};
export const buildFileParam = async (api, value) => {
if (URI_REGEXP.test(value)) {
return value;
}
if (value instanceof Result) {
return value.file.url;
}
if (value instanceof ResultFile) {
return value.url;
}
if (value instanceof UploadResult) {
return value;
}
return api.upload(value);
};
export const detectFormat = (params, toFormat) => {
let resource;
if (toFormat.toString().toLowerCase() === 'zip') {
return ANY_FORMAT;
}
if (params.Url) {
return DEFAULT_URL_FORMAT;
}
if (params.File) {
resource = params.File;
} else if (params.Files) {
[resource] = params.Files;
}
if (resource instanceof ResultFile) {
resource = resource.url;
}
if (resource instanceof UploadResult) {
return resource.fileExt;
}
const { pathname } = url.parse(resource);
return path.extname(pathname).substring(1);
};
export const buildQueryString = (params) => {
const result = {};
Object.keys(params).forEach((key) => {
const val = params[key];
if (val instanceof Array) {
val.forEach((v, i) => {
result[`${key}[${i}]`] = v.toString();
});
} else {
result[key] = val.toString();
}
});
return querystring.stringify(result);
};
export const getReadableStream = (source) => {
if (source instanceof stream.Readable) {
return source;
}
return fs.createReadStream(source);
};
export const encodeFileName = (fileName) => {
const str = encodeURIComponent(fileName);
return str.replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16)}`);
};