New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

mock-http-mini

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mock-http-mini

Mock + Express 简易配置本地假数据服务器

latest
Source
npmnpm
Version
1.0.2
Version published
Maintainers
1
Created
Source

mock-http-mini

Mock + Express 本地假数据服务器,数据文件格式直接采用Mock的语法,同时间,支持扩展Mock数据占位符

安装

npm install mock-http-mini

运行

  • 切换到需要运行本地服务器的根目录
cd dist
  • 直接运行或者指定端口号,指定的端口号会覆盖mockhttp.js中配置的端口号
mock-http-mini 或者 mock-http-mini 8080

mockhttp.js配置

在开启服务器的根目录下面添加配置文件mockhttp.js,如不添加配置文件,则采用默认配置

配置项

属性类型默认值描述
defaultDataFile{String}静态数据文件名,,只支持js文件和json文件
baseDist{String}所有数据文件的根目录,是相对路劲,相对于当前操作的根目录
port{Number}}8090本地服务器端口号
openBrowser{Boolean}false开启服务器是否自动打开浏览器
dev{Boolean}false是否是开发模式,用于打印对应的信息
middleWare`{FunctionArrayObject}`
mockExtend{Object}}{}Mock数据占位符扩展

defaultDataFile

对于没有特殊要求的数据可以直接写在一个文件上,减少数据文件的个数

defaultDataFile: 'index.json'

middleWare

function (req, res, next, server){

}

req, res, next具体的可以看Express中间件开发文档

参数servermock-http-server数据处理类MockServer提供如下接口

属性描述
loadData(requestUrl)requestUrl配置的数据模板对应的key值,根据请求的地址获取配置的数据模版生成的数据,并返回Promise
updateData(requestUrl, data)requestUrl同上,data为对应的数据。每次请求接口,是否返回新的数据
// Object格式
middleWare: {
    api: '/goform/module',
    callback: function(req, res, next, server) {
        server.log('中间件,劫持请求 /goform/module');
        server.loadData(req.path).then(result => {
            res.send(JSON.stringify(result));
            server.log(result);
        }).catch(err => {
            next();
        });
    }
}

// Array格式
middleWare: [
    {
        api: '/goform/module',
        callback: function(req, res, next, server) {
            server.log('中间件,劫持请求 /goform/module');
            server.loadData(req.path).then(result => {
                res.send(JSON.stringify(result));
                server.log(result);
            }).catch(err => {
                next();
            });
        }
    },
    {
        api: 'xxx',
        callback: function(){
            //xxx
        }
    }
    ...
]

// Function格式
middleWare: function(req, res, next, server){
    // xxx
}

mockExtend

mockExtend: {
    ip: function(iptext) {
        if (iptext === '' || iptext === undefined) {
            return `192.168.${this.integer(0, 255)}.${this.integer(1, 254)}`;
        }

        let ip = [];
        iptext += '';
        iptext.split('.').forEach(item => {
            item = item.split('-');
            ip.push(item.length > 1 ? this.integer(item[0], item[1]) : item);
        });

        return ip.join('.');
    },
    ......
}

完整示例如下:

module.exports = {
    defaultDataFile: 'index.json',
    baseDist: 'data',
    port: 8090,
    openBrowser: false,
    dev: false,
    /**
    * 中间件,拦截请求之类的操作
    * req: express请求参数, res:express返回参数, next:express传递, server: 当前数据操作的server对象
    * function(req, res, next, server)
    */
    middleWare: {
        api: '/goform/module',
        callback: function(req, res, next, server) {
            server.log('中间件,劫持请求 /goform/module');
            server.loadData(req.path).then(result => {
                res.send(JSON.stringify(result));
                server.log(result);
            }).catch(err => {
                next();
            });
        }
    },
    /**
    * Moc扩展
    */
    mockExtend: {
        ip: function(iptext) {
            if (iptext === '' || iptext === undefined) {
                return `192.168.${this.integer(0, 255)}.${this.integer(1, 254)}`;
            }

            let ip = [];
            iptext += '';
            iptext.split('.').forEach(item => {
                item = item.split('-');
                ip.push(item.length > 1 ? this.integer(item[0], item[1]) : item);
            });

            return ip.join('.');
        }
    }
};

数据文件配置项说明

配置项

属性类型默认值描述
delay{Number}0延迟返回数据,单位为毫秒,默认不延迟
refresh{Boolean}false每次请求接口,是否返回新的数据
template`{Objectfunction}}`

如果没有其他配置参数可省略template,直接返回template对应的值

js文件例子

module.exports = {
    // 有参赛配置
    getMess: {
        delay: 200,
        refresh: true,
        template: {
            'ID|+1': 1,
            'title': 'Demo',
            'mess': '★',
            'age|1-100': 100,
            'ip': '@IP',
            'ip1': '@IP("192.1-12.250-254.0")'
        }
    }
    // 无参数配置
    getData: {
        'ID|+1': 1,
        'title': 'Demo',
        'mess': '★',
        'age|1-100': 100,
        'ip': '@IP',
        'ip1': '@IP("192.1-12.250-254.0")'
    },
    // 函数模版
    getData: function(){
        return{
            a: 1
            ....
        }
    }
    // 异步数据
    getAsyncData: function(){
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(xxx);
            }, 0);
        });
    }
}

json文件例子

{
    "getMess": {
        "delay": 200,
        "template": {
            "title": "Syntax Demo1",
            "string1|1-10": "★",
            "string2|2-4": "LOVE*",
            "number1|+1": 100,
            "number2|1-100": 100,
            "number3|1-100.1-3": 1,
            "number4|123.1-10": 1,
            "number5|123.2": 1,
            "number6|123.4": 1.123
        }
    }
}

Keywords

mock

FAQs

Package last updated on 04 Jan 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts