index.ts 2.0 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

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