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

dyn-mocker

v1.1.5

Published

A dyn-mock server for front-end development

Downloads

3

Readme

dyn-mocker

A dynamic "mock + proxy" server for front-end development. Please see the sample project in source code.

Usage

1. install

npm i dyn-mocker -D

or

yarn add dyn-mocker --dev

2. configuration

Make a mock directory, and copy the mock-config.js into it.
Make a root directory as the root of mock files.
--mock
----root
----mock-config.js
--package.json

3. configuration

sample:

const config = {
	mockEnabled: true,
	mockPath: ['mock/root', 'mock/root-old'], //模拟文件根目录
	proxyTarget: 'http://your-backend-server.com', //后台接口服务地址(代理目标),为空表示不代理
	isHttps: false, //是否https
	port: 8085, //端口
	checkPath: function (urlPath) { //urlPath校验函数,返回true表示需要进行mock处理,为false直接走代理
		return true
	},
	beforeResponse: function (respData, req) { //数据返回前的回调钩子,respData包含status、headers、body属性
		respData.headers['Access-Control-Allow-Origin'] = req.headers['origin'] || req.headers['Origin'];
		respData.headers['Access-Control-Allow-Credentials'] = 'true';
		respData.headers['Access-Control-Max-Age'] = '600';
		respData.headers['Access-Control-Allow-Headers'] = 'Content-Type,Content-Length,Authorization,Access,X-Requested-With,yxt-token';
		//respData.headers["Access-Control-Allow-Methods"] = "PUT,POST,GET,DELETE,PATCH,OPTIONS";

		respData.headers['P3P'] = 'CP="CAO PSA OUR"';
	}
}
module.exports = config;

Edit the mock-config.js options:

mockEnabled

[true] to enable it

mockPath

the root path[s] of mock files. String or array of string.

proxyTarget

If no mock file for a url request, the http pipe will be reversely proxied to this target server. If this is empty, then won't proxy.

isHttps

[true] for https

port

Port of the mock server

checkPath

A function to check a url which needs to mock or not. eg:
function (urlPath) {
    return urlPath.match(/\/api\//);
}

beforeResponse

A function to do customized job before responding.respData contains [status、headers、body] properties. eg:
function (respData, req) {
    respData.headers["Access-Control-Allow-Origin"] = req.headers["origin"] || req.headers["Origin"];
    respData.headers["Access-Control-Allow-Credentials"] = "true";
    respData.headers["Access-Control-Allow-Headers"] = "Content-Type,Content-Length,Authorization,Access,X-Requested-With,yxt_token";
    //respData.headers["Access-Control-Allow-Methods"] = "PUT,POST,GET,DELETE,PATCH,OPTIONS";
}

4. Add script to package.json

"scripts": {
	...
    "mock": "node ./node_modules/dyn-mocker ./mock/mock-config.js"
}

5. Start mock server

npm run mock

6. Create js files for dyn-mocker in the mock/root directory

Simple js file:

// dyn-mocker use json eval mode, but not JSON.parse
module.export = {
	disabled: 0,
	status: 200,
	"headers": {
		"server": "dyn-mocker",
		"set-cookie": "foo=bar; path=/",
		"cache-control": "no-cache"
	},
	"body": {
		"status": 0,
		"obj": {
			"cfg": {
				"o": {
					"buttons": [
						{
							"id": 1,
							"title": "按钮1"
						},
						{
							"id": 2,
							"title": "按钮2"
						}
					]
				}
			}
		},
		"msg": ""
	}
}

Js file with functions:

module.export = {
    disabled: 0,
    body: function (query, post, header, request) {
        //output log in the node console
        console.log('post data: ' + post)

        //use queryString in url
        //use key word 'this', which point to the yaml root object
        if (query.id == '1') return ok(this.case_1);

        //use http postData
        if (post && post.type == 'test') return ok(this.case_2);

        //use http headers
        if (header["content-type"] == "text/txt") return ok("Hello,txt")

        //use request info
        return ok({default: 'no data', url: request.url})

        function ok(d) {
            return {status: 0, data: d}
        }
    },
    case_1: {
        id: 1,
        b: 2
    },
    case_2: {
        a: 3,
        b: "test"
    }
}

Another js:

module.exports = {
    disabled: 0,
    status: 200,
    headers: function (query, post, header, request) {
        var r = {}
        if (post.rememberPwd && this.checkFn(post, header)) {
            process._cookiev = 'a=b' + (+new Date);
            r['set-cookie'] = process._cookiev + '; Max-Age=30000; path=/';
        }
        else {
            process._cookiev = '';
            r['set-cookie'] = process._cookiev + '; Max-Age=0; path=/';
        }
        return r;
    },
    body: function (query, post, header, request) {
        return {
            status: this.checkFn(post, header) ? 0 : 1,
            data: '', returnValue: 'token-xxxxxxx',
            msg: '用户名密码错误'
        }
    },
    checkFn: function (post, header) {
        if (post.password == '123456' || post.password == '') return true;

        if (post.useRemembered && post.password == '_fakepwd') {
            var cookie = header['Cookie'] || header['cookie'];
            return cookie && cookie.indexOf(process._cookiev) > -1
        }
    }
}