✨ 无需刷新获得其他设备上传的文本 (增加websocket
添加云函数
__websocket__
import cloud from '@lafjs/cloud'
type scoketWithId = { socket: WebSocket, id: string };
const CLIENTS = "CLISENTS"
function getUniqueID() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4();
};
const broadcast = (clients: scoketWithId[], tp: string) => {
clients.forEach(client => {
if (client.socket.readyState == 1)
client.socket.send(JSON.stringify({
tp
}))
})
}
export async function main(ctx: FunctionContext) {
if (ctx.method === "WebSocket:connection") {
let clients = cloud.shared.get(CLIENTS);
const newClient: scoketWithId = { socket: ctx.socket, id: getUniqueID() };
if (!clients) {
cloud.shared.set(CLIENTS, [newClient]);
} else {
cloud.shared.set(CLIENTS, [...clients, newClient]);
}
ctx.socket.send(JSON.stringify({ id: newClient.id, tp: "connection" }));
}
if (ctx.method === "WebSocket:message") {
const { tp, ...rest } = JSON.parse(String.fromCharCode.apply(null, ctx.params.data));
if (tp === "reload-copy" || tp === "clear") {
broadcast(cloud.shared.get(CLIENTS), tp);
}
const clients = (cloud.shared.get(CLIENTS) as scoketWithId[]).filter(client => client.socket.readyState !== 3);
cloud.shared.set(CLIENTS, clients);
}
}
verify
import cloud from '@lafjs/cloud'
export async function main(ctx: FunctionContext) {
if(ctx.user) {
ctx.response.status(200).send({ok: true})
} else {
ctx.response.status(404).send({ ok: false })
}
}