-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
41 lines (33 loc) · 1.19 KB
/
utils.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
import { createHash } from 'crypto';
import { readFile } from 'fs/promises';
import got from 'got';
export function isObject(item: any) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
export function mergeDeep<T extends Record<any, any>>(target: T, ...sources: T[]): T {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return mergeDeep(target, ...sources);
}
export async function getUrlFileBuffer(url: string): Promise<Buffer> {
const data = await got.get(url, {
responseType: 'buffer',
}).buffer();
return Buffer.from(data);
}
export function getHash(data: string | Buffer): string {
return createHash('md5').update(data).digest('hex');
}
export async function loadJsonAndAssign<T>(path: string, target: Partial<T> = {}): Promise<T> {
return Object.assign({}, JSON.parse(Buffer.from(await readFile(path)).toString()) as T, target);
}