tools-mock
Version:
A node.js mock tool to quickly start the server via http
134 lines (133 loc) • 3.66 kB
TypeScript
/// <reference types="node" />
import * as http from 'http';
import { pathItem } from './CMockWSRouter';
export default class CMockConfig {
/**
* 静态资源目录
*/
staticDir: string;
/**
* 启动端口-默认3900
*/
port: number;
config: {
/**
* 接口配置数据
*/
data?: {
[key: string]: {
method: 'POST' | 'GET';
fun: (data: any, req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage> & {
req: http.IncomingMessage;
}) => any;
};
};
/**
* 请求前处理
*/
reqBefore?: (req: http.IncomingMessage, res: http.ServerResponse<http.IncomingMessage> & {
req: http.IncomingMessage;
}) => any;
/**
* 请求后数据处理
*
* @example
* //标头参考:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Accept
* CMock.config.resAfter = (param)=>{
*
* const endStr= param.data
let isHtml = endStr.indexOf('<!DOCTYPE')
isHtml = isHtml < 20 && isHtml >= 0
if (isHtml) {
param.headers['Content-Type']='text/html; charset=utf-8'
endStr = endStr.substring(1, endStr.length - 1)
endStr = endStr
.replace(/\\\"/g, '"')
.replace(/\\r/g, '\r')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
}
param.data = endStr
* }
*/
resAfter?: (param: {
/**
* 接口地址
*/
url: string;
/**
* 接口返回数据
*/
data: any;
/**
* 标头
*/
headers: {
[key: string]: string;
};
}) => any;
/**
* 对于静态文件地址处理
* @param url
* @returns
*/
staticFileUrl?: (url: string) => string;
/**
* 对于静态文件格式处理
* @param extname
* @returns
*
* @example
* CMock.staticFileContentType=(extname) => {
return (
{
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.zip': 'application/zip'
}[extname] || 'application/octet-stream'
)
}
*/
staticFileContentType?: (extname: string) => string;
};
/**
* websocket服务配置
*/
wsconfig: {
/**
* 开启websocket
*/
open: boolean;
/**
* websocket入口地址配置
* @example
{
'/gameServer': {
connection(req, ws) {
console.log('connection gameServer')
},
message(message, ws) {
console.log('message')
}
},
'/api/mini/games/#{token}/#{miniGame}': {
connection(req, ws, params) {
console.log('connection',params)
},
message(message, ws) {
console.log('message')
}
},
}
*/
data?: {
[key: string]: Omit<pathItem, 'params'>;
};
};
}