index.ts 1.9 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
        let method = req.path;
        if (!method) {
19 20 21 22 23
            method = Array.isArray(req.query.method)
                ? req.query.method.join('/')
                : 'string' === typeof req.query.method
                ? req.query.method
                : '';
24 25 26
        } else {
            method = method.replace(/^\//, '');
        }
27 28 29 30 31 32 33

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

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

            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 已提交
46 47 48 49

            if (delay) {
                await sleep(delay);
            }
50 51 52 53

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