middleware.js 2.6 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
import {fileURLToPath} from 'url';
18 19
import path from 'path';

20
const cwd = path.dirname(fileURLToPath(import.meta.url));
21

22 23
const sleep = time => {
    return new Promise(resolve => setTimeout(resolve, time));
24 25
};

26 27
export default options => {
    return async (req, res) => {
28
        let method = req.path;
29
        const query = req.query;
30
        if (!method) {
31 32 33 34
            method = Array.isArray(query.method)
                ? query.method.join('/')
                : 'string' === typeof query.method
                ? query.method
35 36 37 38 39 40
                : '';
        } else {
            method = method.replace(/^\//, '');
        }

        if (!method) {
P
Peter Pan 已提交
41 42 43 44
            res.status(404).json({
                status: 1,
                msg: 'Method does not exist'
            });
45 46 47 48
            return;
        }

        try {
49
            let {default: mock} = await import(path.resolve(options?.path || path.join(cwd, 'data'), method));
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

            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;
            }

            if (delay) {
                await sleep(delay);
            }

66
            if (mock instanceof Response) {
67
                res.send(mock);
P
Peter Pan 已提交
68 69
            } else if ('string' === typeof mock) {
                res.send(mock);
70
            } else {
71
                const result = JSON.parse(JSON.stringify(mock, null, 4));
72 73 74 75 76 77 78
                if (result && 'status' in result && 'data' in result) {
                    res.json(result);
                } else {
                    res.json({status: 0, msg: '', data: result});
                }
            }
        } catch (e) {
P
Peter Pan 已提交
79 80 81 82
            res.status(500).json({
                status: 1,
                msg: e.message
            });
83 84 85 86 87
            // eslint-disable-next-line no-console
            console.error(e);
        }
    };
};