datau-scene-request
v0.1.4
Published
场库请求库含http和ws
Downloads
9
Readme
datau-scene-request
场库请求库含 http 和 ws
Usage
npm i datau-scene-request -S
// http
import { httpRequest } from 'datau-scene-request';
try {
const res = await httpRequest({
url: '/api/xxx',
params: {},
});
console.log(res);
} catch (err) {
console.error(err);
}
import { wsRequest } from 'datau-scene-request';
const wsIns = wsRequest({
url: '/ws/xxx',
onOpen: (p) => {},
onError: (p) => {},
onMessage: (p) => {
console.log(p.msg.data.toString());
},
onClose: (p) => {},
});
定制请求
import { httpService, httpRequest } from 'datau-scene-request';
// http 定制请求拦截器
httpService.interceptors.request.use(function () {
/*...*/
});
httpService.interceptors.request.clear(); // Removes interceptors from requests
httpService.interceptors.response.use(function () {
/*...*/
});
httpService.interceptors.response.clear(); // Removes interceptors from responses
try {
const res = await httpRequest({
url: '/api/xxx',
params: {},
});
console.log(res);
} catch (err) {
console.error(err);
}
import { wsRequest, DefaultWsRequestClass, overwriteWsClass } from 'datau-scene-request';
// 定制ws请求,为所有ws请求增加心跳
overwriteWsClass(
class WsRequest extends DefaultWsRequestClass {
heartbeatTimer;
constructor(props) {
super(props);
this.heartbeatTimer = null;
}
openHandler(onOpen, p) {
let { ws } = p || {};
// 心跳
this.heartbeatTimer = null;
// 定时发送心跳
this.heartbeatTimer = setInterval(() => {
ws.send(JSON.stringify({ msg: '心跳数据', query: p.query }));
}, 3000);
onOpen(p);
}
closeHandler(onClose, p) {
onClose(p);
// 停止心跳
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
}
}
},
);
const wsIns = wsRequest({
url: '/ws/xxx',
onOpen: (p) => {},
onError: (p) => {},
onMessage: (p) => {
console.log(p.msg.data.toString());
},
onClose: (p) => {},
});