feat: websocket 支持直接返回内容并将其设置到某个 key 上 Closes #3781 (#3831)

This commit is contained in:
吴多益 2022-03-23 14:00:06 +08:00 committed by GitHub
parent 7fdf80aadd
commit 3872b325bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 86 additions and 28 deletions

View File

@ -394,12 +394,9 @@ Service 支持通过 WebSocket 获取数据,只需要设置 ws由于无示
}
},
"body": {
{
"label": "名称",
"type": "input-text",
"value": "name",
"name": "amis"
}
"label": "名称",
"type": "static",
"name": "name"
}
}
```
@ -430,33 +427,82 @@ WebSocket 客户端的默认实现是使用标准 WebSocket如果后端使用
> 1.4.0 及以上版本修改了 ws 类型,将之前的字符串改成了对象的方式,会有两个参数 url 和 body
下面是目前 amis 中 WebSocket 支持的默认实现:
```javascript
wsFetcher(ws, onMessage, onError) {
if (ws) {
const socket = new WebSocket(ws.url);
socket.onopen = event => {
if (ws.body) {
socket.send(JSON.stringify(ws.body));
}
};
socket.onmessage = event => {
if (event.data) {
onMessage(JSON.parse(event.data));
}
};
socket.onerror = onError;
return {
close: socket.close
};
} else {
return {
close: () => {}
};
if (ws) {
const socket = new WebSocket(ws.url);
socket.onopen = event => {
if (ws.body) {
socket.send(JSON.stringify(ws.body));
}
};
socket.onmessage = event => {
if (event.data) {
let data;
try {
data = JSON.parse(event.data);
} catch (error) {}
if (typeof data !== 'object') {
let key = ws.responseKey || 'data';
data = {
[key]: event.data
};
}
onMessage(data);
}
};
socket.onerror = onError;
return {
close: socket.close
};
} else {
return {
close: () => {}
};
}
}
```
通过 onMessage 来通知 amis 数据修改了,并返回 close 函数来关闭连接。
> 1.8.0 及以上版本
如果 WebSocket 返回的结果不是 JSON 而只是某个字符串,需要配置 `responseKey` 属性来将这个结果放在这个 key 上,比如下面的例子
```json
{
"type": "service",
"ws": {
"url": "ws://localhost:8777?name=${name}",
"data": {
"name": "${name}"
},
"responseKey": "name"
},
"body": {
"label": "名称",
"type": "static",
"name": "name"
}
}
```
通过 onMessage 来通知 amis 数据修改了,并返回 close 函数来关闭连接。
对应的后端就只需要返回字符串
```javascript
const WebSocket = require('ws');
const ws = new WebSocket.Server({port: 8777});
ws.on('connection', function connection(ws) {
setInterval(() => {
const random = Math.floor(Math.random() * Math.floor(100));
ws.send(random);
}, 500);
});
```
## 调用外部函数获取数据

View File

@ -103,6 +103,7 @@ export interface RenderSchemaFilter {
export interface wsObject {
url: string;
responseKey?: string;
body?: any;
}
@ -296,7 +297,18 @@ const defaultOptions: RenderOptions = {
};
socket.onmessage = event => {
if (event.data) {
onMessage(JSON.parse(event.data));
let data;
try {
data = JSON.parse(event.data);
} catch (error) {}
if (typeof data !== 'object') {
let key = ws.responseKey || 'data';
data = {
[key]: event.data
};
}
onMessage(data);
}
};
socket.onerror = onError;