This commit is contained in:
2026-02-04 23:34:34 +08:00
parent 5a8491b83a
commit d15a658466
8 changed files with 130 additions and 173 deletions

View File

@@ -0,0 +1,57 @@
const main = () => {
const random = Math.random().toString(36).slice(-6)
return 'hello a ' + random
}
// fs.writeFileSync('./a.txt', main() + '\n', { flag: 'a' })
console.log('pwd', process.cwd())
// const value = fs.readFileSync('./bun.config.ts', 'utf-8')
// console.log('a.txt 内容:', value)
const listen = async () => {
console.log('子进程启动,等待消息...')
const getParams = async () => {
return new Promise((resolve) => {
process.on('message', (msg) => {
console.log('子进程收到消息:', msg)
resolve(msg)
})
})
}
try {
const params = await getParams()
console.log('处理参数:', params)
// 执行主要逻辑
const result = main()
// 发送结果回主进程
const response = {
foo: 'bar',
params,
success: true,
data: { code: 200, data: result },
timestamp: new Date().toISOString()
}
process.send?.(response, (error) => {
if (error) {
console.error('发送消息失败:', error)
} else {
console.log('成功发送响应:', response)
}
process.exit(0)
})
} catch (error) {
console.error('子进程执行出错:', error)
process.send?.({
success: false,
error: error.message
})
process.exit(1)
}
}
// 启动监听
listen().catch(console.error)

View File

@@ -0,0 +1,14 @@
import { QueryRouterServer } from "@kevisual/router";
const app = new QueryRouterServer();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main. filename: root/listen-demo/router.ts',
params: ctx.query
}
}).addTo(app)
app.wait()

24
src/2025-10/main.ts Normal file
View File

@@ -0,0 +1,24 @@
import { QueryRouterServer } from "@kevisual/router";
const app = new QueryRouterServer();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main. filename: root/light-code-demo/main.ts',
params: ctx.query
}
}).addTo(app)
app.route({
path: 'main2'
}).define(async (ctx) => {
ctx.body = {
message: 'this is main2. filename: root/light-code-demo/main.ts',
params: ctx.query
}
}).addTo(app)
app.wait()

46
src/2025-10/sign.ts Normal file
View File

@@ -0,0 +1,46 @@
import { QueryRouterServer as Mini } from "@kevisual/router";
import { NocoApi } from "@kevisual/noco";
const config = {
NOCODB_URL: process.env.NOCODB_URL || 'https://nocodb.xiongxiao.me',
NOCODB_API_KEY: process.env.NOCODB_API_KEY || 'uca1Zx3p_**'
}
const table = 'mcby44q8zrayvn9'
const nocoAPi = new NocoApi({
baseURL: config.NOCODB_URL,
token: config.NOCODB_API_KEY,
table,
});
console.log('nocoAPi', await nocoAPi.record.list())
const app = new Mini();
app.route({
path: 'sign'
}).define(async (ctx) => {
const { Title, Description } = ctx.query
// 这里可以处理签到
await nocoAPi.record.create({ Title, Description })
const list = await nocoAPi.record.list({ sort: '-CreatedAt' })
ctx.body = { message: '签到成功', list }
}).addTo(app)
app.route({
path: 'sign',
key: 'list'
}).define(async (ctx) => {
// 这里可以处理签到
ctx.body = await nocoAPi.record.list()
}).addTo(app)
app.route({
path: 'sign',
key: 'delete'
}).define(async (ctx) => {
const { id } = ctx.query
// 这里可以处理签到
await nocoAPi.record.delete({ Id: id })
const list = await nocoAPi.record.list({ sort: '-CreatedAt' })
ctx.body = { message: '删除成功', list }
}).addTo(app)
app.wait()

56
src/2025-10/weather.ts Normal file
View File

@@ -0,0 +1,56 @@
const weatherHost = 'n65khufe5n.re.qweatherapi.com';
const token = 'fdad5aeb2ba54949a8a1df2a0f3d1efb'
const xihu = '101210113'; // 西湖
export const getWeather = async (location: string = xihu) => {
const url = `https://${weatherHost}/v7/weather/3d?location=${location}`;
const headers = {
'Authorization': `Bearer ${token}`
};
const res = await fetch(url, { headers });
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data = await res.json();
return data;
}
// getWeather().then(console.log).catch(console.error);
// https://dev.qweather.com/
class Weather {
host: string;
token: string;
constructor(opts: { host: string; token: string }) {
this.host = opts.host;
this.token = opts.token;
console.log(this.host, this.token);
}
getWeather(location: string) {
return fetch(`https://${this.host}/v7/weather/now?location=${location}`, {
headers: {
'Content-Type': 'application/json',
'X-QW-Api-Key': '<KEY>'.replace('<KEY>', this.token),
},
}).then((res) => res.json());
}
}
const newWeather = new Weather({
host: process.env?.QWEATHER_HOST || weatherHost,
token: process.env?.QWEATHER_TOKEN || token,
});
// newWeather.getWeather(xihu).then(console.log).catch(console.error);
import { QueryRouterServer as Mini } from "@kevisual/router";
const app = new Mini();
app.route({
path: 'main'
}).define(async (ctx) => {
ctx.body = await newWeather.getWeather(xihu);
}).addTo(app)
app.wait()

76
src/ws.ts Normal file
View File

@@ -0,0 +1,76 @@
import { App, ListenProcessResponse } from '@kevisual/router'
import { ReconnectingWebSocket } from '@kevisual/router/ws'
const app = new App();
app.route({
path: 'livecode-status',
description: 'LiveCode 状态路由',
metadata: {
tags: ['livecode', 'status'],
},
}).define(async (ctx) => {
ctx.body = {
status: 'LiveCode 模块运行正常',
timestamp: new Date().toISOString(),
};
}).addTo(app)
app.createRouteList();
await new Promise((resolve) => setTimeout(resolve, 1000));
// 创建支持断开重连的 WebSocket 客户端
const ws = new ReconnectingWebSocket('ws://localhost:51515/livecode/ws?id=test-live-app', {
maxRetries: Infinity, // 无限重试
retryDelay: 1000, // 初始重试延迟 1 秒
maxDelay: 30000, // 最大延迟 30 秒
backoffMultiplier: 2, // 指数退避倍数
});
ws.onMessage(async (message) => {
console.log('收到消息:', message);
if (message.type === 'router' && message.id) {
console.log('收到路由响应:', message);
const data = message?.data as ListenProcessResponse;
if (!data) {
ws.send({
type: 'router',
id: message.id,
data: { code: 500, message: 'No data received' }
});
return;
}
const msg = data.message;
if (!msg) {
ws.send({
type: 'router',
id: message.id,
data: { code: 500, message: 'No {message} received' }
});
return;
}
const context = data.context || {};
const res = await app.run(msg, context);
console.log('路由处理结果:', res);
ws.send({
type: 'router',
id: message.id,
data: res
});
}
});
ws.onOpen(() => {
console.log('连接已建立,可以开始通信');
});
ws.onError((error) => {
console.error('连接错误:', error.message);
});
ws.onClose((code, reason) => {
console.log(`连接关闭: ${code} - ${reason.toString()}`);
});
// 启动连接
ws.connect();