index.ts 1.8 KB
Newer Older
1 2
import {Request, Response} from 'express';

3 4 5
import faker from 'faker';
import path from 'path';

6 7 8 9 10
const sleep = (time: number) => {
    return new Promise(resolve => setTimeout(resolve, time));
};

export type Options = {
11
    path?: string;
12 13 14 15 16
    delay?: number | ((method: string) => number);
};

export default (options: Options) => {
    return async (req: Request, res: Response) => {
17 18 19 20 21 22
        let method = req.path;
        if (!method) {
            method = Array.isArray(req.query.method) ? req.query.method.join('/') : req.query.method;
        } else {
            method = method.replace(/^\//, '');
        }
23 24 25 26 27 28 29

        if (!method) {
            res.status(404).send({});
            return;
        }

        try {
30
            let {default: mock} = await import(path.resolve(options.path || path.join(__dirname, 'data'), method));
31 32 33 34 35 36 37 38 39 40 41

            if ('function' === typeof mock) {
                mock = await mock(req, res);
            }

            let delay = 0;
            if ('function' === typeof options.delay) {
                delay = options.delay(method);
            } else if (options.delay) {
                delay = options.delay;
            }
P
Peter Pan 已提交
42 43 44 45

            if (delay) {
                await sleep(delay);
            }
46 47 48 49

            if (mock instanceof ArrayBuffer) {
                res.send(Buffer.from(mock));
            } else {
P
Peter Pan 已提交
50
                const result = JSON.parse(faker.fake(JSON.stringify(mock, null, 4)));
51
                if (result && 'status' in result && 'data' in result) {
P
Peter Pan 已提交
52 53 54 55
                    res.json(result);
                } else {
                    res.json({status: 0, msg: '', data: result});
                }
56 57 58
            }
        } catch (e) {
            res.status(500).send(e.message);
59 60
            // eslint-disable-next-line no-console
            console.error(e);
61 62 63
        }
    };
};