reskript icon indicating copy to clipboard operation
reskript copied to clipboard

探索一下mock的解决方案

Open otakustay opened this issue 4 years ago • 1 comments

otakustay avatar Mar 26 '21 01:03 otakustay

使用支持json和js文件的简单mock可以满足我们项目的大部分场景需求,实现不超过100行。可以考虑先简单加一个

        if (fs.existsSync(filePath)) {
            // read file from the mock directory
            const mockData = fs.readFileSync(filePath).toString('utf-8');
            res.end(mockData);
        } else if (fs.existsSync(jsFilePath)) {
            delete require.cache[jsFilePath];
            const result = require(jsFilePath);
            // searchParams to json
            const jsonParams = JSON.parse(body || '{}');
            reqUrl.searchParams.forEach((value, name) => {
                jsonParams[name] = value;
            });
            if (result && typeof result === 'function') {
                res.end(JSON.stringify(result(jsonParams)));
            }
        } else {
            console.log(`file ${filePath} not found`);
            res.end(`{"ret": "0","msg": "file ${filePath} not found"}`);
        }
    });

就是url到文件的路径映射。json直接就是response,js支持模板接口返回数据。

isee15 avatar Nov 10 '22 02:11 isee15