rspack-plugin-mock
Version:
inject api mock server to development server
130 lines (127 loc) • 3.29 kB
JavaScript
// src/core/defineMock.ts
import { isArray } from "@pengzhanbo/utils";
function defineMock(config) {
return config;
}
function createDefineMock(transformer) {
const define = (config) => {
if (isArray(config))
config = config.map((item) => transformer(item) || item);
else
config = transformer(config) || config;
return config;
};
return define;
}
// src/core/defineMockData.ts
import { deepClone, deepEqual, isFunction } from "@pengzhanbo/utils";
var mockDataCache = /* @__PURE__ */ new Map();
var responseCache = /* @__PURE__ */ new WeakMap();
var staleInterval = 70;
var CacheImpl = class {
value;
// 初始化数据的备份,用于 判断 传入的初始化数据是否发生变更
#initialValue;
#lastUpdate;
constructor(value) {
this.value = value;
this.#initialValue = deepClone(value);
this.#lastUpdate = Date.now();
}
hotUpdate(value) {
if (Date.now() - this.#lastUpdate < staleInterval)
return;
if (!deepEqual(value, this.#initialValue)) {
this.value = value;
this.#initialValue = deepClone(value);
this.#lastUpdate = Date.now();
}
}
};
function defineMockData(key, initialData) {
if (!mockDataCache.has(key))
mockDataCache.set(key, new CacheImpl(initialData));
const cache = mockDataCache.get(key);
cache.hotUpdate(initialData);
if (responseCache.has(cache))
return responseCache.get(cache);
const res = [
() => cache.value,
(val) => {
if (isFunction(val))
val = val(cache.value) ?? cache.value;
cache.value = val;
}
];
Object.defineProperty(res, "value", {
get() {
return cache.value;
},
set(val) {
cache.value = val;
}
});
responseCache.set(cache, res);
return res;
}
// src/core/sse.ts
import { Transform } from "node:stream";
var SSEStream = class extends Transform {
constructor(req) {
super({ objectMode: true });
req.socket.setKeepAlive(true);
req.socket.setNoDelay(true);
req.socket.setTimeout(0);
}
pipe(destination, options) {
if (destination.writeHead) {
destination.writeHead(200, {
"Content-Type": "text/event-stream; charset=utf-8",
"Transfer-Encoding": "identity",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
});
destination.flushHeaders?.();
}
destination.write(":ok\n\n");
return super.pipe(destination, options);
}
_transform(message, encoding, callback) {
if (message.comment)
this.push(`: ${message.comment}
`);
if (message.event)
this.push(`event: ${message.event}
`);
if (message.id)
this.push(`id: ${message.id}
`);
if (message.retry)
this.push(`retry: ${message.retry}
`);
if (message.data)
this.push(dataString(message.data));
this.push("\n");
callback();
}
write(message, ...args) {
return super.write(message, ...args);
}
};
function dataString(data) {
if (typeof data === "object")
return dataString(JSON.stringify(data));
return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}
`).join("");
}
function createSSEStream(req, res) {
const sse = new SSEStream(req);
sse.pipe(res);
return sse;
}
export {
createDefineMock,
createSSEStream,
defineMock,
defineMockData
};