npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mock-mini-server

v1.1.0

Published

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

Downloads

8

Readme

mock-mini-server

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

安装

npm install mock-mini-server

运行

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

mockhttp.js配置

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

配置项

|属性|类型|默认值|描述| |:--:|:--:|:-----:|:----------| |defaultDataFile|{String}||静态数据文件名,,只支持js文件和json文件| |baseDist|{String}||所有数据文件的根目录,可以是相对路劲也可以是绝对路径| |port|{Number}}|10100|本地服务器端口号| |openBrowser|{Boolean}|false|开启服务器是否自动打开浏览器| |dev|{Boolean}|false|是否是开发模式,用于打印对应的信息| |middleWare|{Function/Array/Object}||Express中间件,可用于截获请求,实现自定义逻辑| |mockExtend|{Object}}| {} |Mock数据占位符扩展|

defaultDataFile

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

defaultDataFile: 'index.json'

middleWare

截获http请求中间件,用于处理自定义的逻辑

middleWare: [Object/Array/Function]

Object

{
    middleWare: {
        api: 'xx', 
        callback: function (req, res, next, server){
            //截获请求,处理自定义逻辑
        }
    }
}

Array

{
    middleWare: [{
        api: 'xx',
        callback: function (req, res, next, server){
            //截获请求,处理自定义逻辑
        }
    }]
}

Function

{
    middleWare: function (req, res, next, server){
        //截获请求,处理自定义逻辑
    }
}

middleWare 参数说明

| 属性 | 描述 | | :---: | :--- | | api | string,需要截获的请求,支持glob | | function | function,处理自定义逻辑 |

callback 参数说明

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

  • 如果只是对请求的拦截附件处理,需要最后调用next(),以执行后续的逻辑,否则执行完回调立即停止

参数servermock-mini-server数据处理类MockServer的实例化对象,提供如下接口

  • option:当前mock-mini-server设置的配置信息
  • Mock: Mcok对象,可以直接调用server.Mock(template)根据模版生成数据
  • loadData(requestUrl): requestUrl为配置的数据模板对应的key值。根据请求的地址获取配置的数据模版生成的数据,并返回Promise。
  • updateData(requestUrl, data): requestUrl同上,data为对应的数据。更新当前已缓存的数据。

middlwWare调试说明

针对在vscode中进行调试说明,配置如下:

  1. package.json添加如下配置
"scripts": {
    "mock": "node --inspect-brk=9229 ./mockDebug.js"
}

dist为需要开启mock-mini-server的文件夹的根目录 9229vsCode中的配置文件launch.json中自动生成的port

  1. dist目录下面添加mockDebug.js
const mockServer = require('mock-mini-server');

mockServer.run();
  1. vsCode中的配置文件launch.json添加如下配置

打开vscode的的配置文件launch.json,点击添加配置,选择通过 NPM 启动选项,生成如下配置,修改runtimeArgspackage.json中设置的scripts名称,本示例中是mock

{
    "type": "node",
    "request": "launch",
    "name": "run NPM",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
        "run-script",
        "mock"
    ],
    "port": 9229
}

9229为vscode生成的监听端口号,两个地方需要保持一致

  1. mockhttp.js文件中打上断点,然后开始调试,当命中middleWare中的规则时,断点处即可生效调试

Example

// 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){
    server.log('中间件,劫持请求 /goform/module');
    server.loadData(req.path).then(result => {
        res.send(JSON.stringify(result));
        server.log(result);
    }).catch(err => {
        next();
    });
}

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|{Object | function}}||mock数据模版,为function需要返回对应的数据,异步数据需要返回Promise|

如果没有其他配置参数可省略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
        }
    }
}