io.ts 6.4 KB
Newer Older
P
Peter Pan 已提交
1 2 3
/* eslint-disable no-console */

import crypto, {BinaryLike} from 'crypto';
4
import {promises as fs, writeFileSync} from 'fs';
P
Peter Pan 已提交
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

import path from 'path';
import querystring from 'querystring';

const apiUrl = '/api';

type Query = Record<string, string | number> | null;

interface WriteOptions {
    type?: 'json' | 'buffer';
}

interface MetaData {
    uri: string;
    query?: Record<string, string | string[]>;
    filename: string;
    headers: Record<string, string>;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
interface ResponseData<T = any> {
    status: number;
    msg?: string;
    data: T;
}

function isEmpty(obj: Record<string, unknown> | null | undefined) {
    if (obj == null) {
        return true;
    }
    return !Object.keys(obj).length;
}

export default class IO {
    public static readonly metaFileName = 'meta.json';
    public static readonly dataPath = 'data';
    public static readonly hashFunction = 'md4';

    protected readonly url: string;
    protected readonly dataDir: string;

    protected metadata: MetaData[] = [];

    constructor(url: string, dataDir: string) {
        this.url = url;
        this.dataDir = dataDir;
51 52 53 54 55

        writeFileSync(path.join(this.dataDir, IO.metaFileName), JSON.stringify(this.metadata), {
            encoding: 'utf-8',
            flag: 'w'
        });
P
Peter Pan 已提交
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
    }

    public static isSameUri(url1: Pick<MetaData, 'uri' | 'query'>, url2: Pick<MetaData, 'uri' | 'query'>) {
        if (url1.uri !== url2.uri) {
            return false;
        }
        if (!isEmpty(url2.query)) {
            if (isEmpty(url1.query)) {
                return false;
            }
            for (const [key, value] of Object.entries(url2.query)) {
                const existValue = url1.query[key];
                if (existValue !== value) {
                    if (Array.isArray(value) && Array.isArray(existValue)) {
                        const count = value.reduce<Record<string, number>>((m, v) => {
                            if (m[v] == null) {
                                m[v] = 1;
                            } else {
                                m[v]++;
                            }
                            return m;
                        }, {});
                        for (const i of existValue) {
                            if (count[i] == null) {
                                return false;
                            }
                            count[i]--;
                        }
                        return Object.values(count).every(c => c === 0);
                    }
                    return false;
                }
            }
            return true;
        } else {
            return isEmpty(url1.query);
        }
    }

    private generateFilename(content: BinaryLike) {
        const hash = crypto.createHash(IO.hashFunction);
        hash.update(content);
        return hash.digest('hex');
    }

    private addMeta(meta: MetaData) {
        const exist = this.metadata.find(data => IO.isSameUri(data, meta));
        if (!exist) {
            this.metadata.push(meta);
        }
    }

    protected async write(
        filePath: string,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        content: Record<string, any> | Buffer,
        contentType: string,
        options?: WriteOptions | WriteOptions['type']
    ) {
P
Peter Pan 已提交
115
        const {default: mkdirp} = await import('mkdirp');
P
Peter Pan 已提交
116 117 118 119 120 121 122
        const type = 'string' === typeof options ? options : options?.type ?? 'json';

        const fileDir = path.join(this.dataDir, IO.dataPath, filePath);
        await mkdirp(fileDir);
        let fileContent: Buffer;
        let extname: string;
        if (type === 'buffer') {
P
Peter Pan 已提交
123
            const {default: mime} = await import('mime-types');
P
Peter Pan 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
            extname = mime.extension(contentType) || '';
            if (extname) {
                extname = '.' + extname;
            }
            fileContent = content as Buffer;
        } else {
            extname = '.json';
            fileContent = Buffer.from(JSON.stringify(content), 'utf-8');
        }

        const filename = this.generateFilename(fileContent) + extname;
        await fs.writeFile(path.join(fileDir, filename), fileContent, {
            encoding: null,
            flag: 'w'
        });
        console.log(`write file ${path.join(filePath, filename)}`);
        return filename;
    }

143 144
    async fetch(uri: string, query?: Query) {
        const {default: fetch} = await import('node-fetch');
P
Peter Pan 已提交
145 146 147 148 149
        let url = this.url + apiUrl + uri;
        if (!isEmpty(query)) {
            url += '?' + querystring.stringify(query);
        }
        try {
150
            return await fetch(url);
P
Peter Pan 已提交
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
        } catch (e) {
            console.error(e);
        }
    }

    protected async fetchAndWrite<T>(uri: string, query?: Query, options?: WriteOptions | WriteOptions['type']) {
        const type = 'string' === typeof options ? options : options?.type ?? 'json';

        const response = await this.fetch(uri, query);
        if (!response.ok) {
            throw new Error('not ok');
        }

        let content: ResponseData<T> | ArrayBuffer;
        if (type === 'buffer') {
            content = await response.buffer();
        } else {
            content = (await response.json()) as ResponseData<T>;
        }
        const filename = await this.write(uri, content, response.headers.get('content-type'), options);
        this.addMeta({
            uri,
            query: isEmpty(query) ? undefined : querystring.parse(querystring.stringify(query)),
            filename,
            headers: ['Content-Type', 'Content-Disposition'].reduce((m, t) => {
                m[t] = response.headers.get(t) || undefined;
                return m;
            }, {})
        });
        return content;
    }

    async save<T>(uri: string, query?: Query) {
        return ((await this.fetchAndWrite<T>(uri, query, 'json')) as ResponseData<T>).data;
    }

    async saveBinary(uri: string, query?: Query) {
        return (await this.fetchAndWrite(uri, query, 'buffer')) as Buffer;
    }

    async getData<T>(uri: string, query?: Query) {
        return ((await (await this.fetch(uri, query)).json()) as ResponseData<T>).data;
    }

    generateMeta() {
        return fs.writeFile(path.join(this.dataDir, IO.metaFileName), JSON.stringify(this.metadata), {
            encoding: 'utf-8',
            flag: 'w'
        });
    }

    sleep(time: number) {
        return new Promise(resolve => {
            setTimeout(resolve, time);
        });
    }
}