itdogapi / server.mjs
StarrySkyWorld's picture
Create server.mjs
72eebaa verified
import http from 'node:http';
import {Client} from 'itdog-web-api';
const port = Number.parseInt(process.env.PORT || '7860', 10);
const client = new Client();
const sendJson = (res, statusCode, payload) => {
const body = JSON.stringify(payload, null, 2);
res.writeHead(statusCode, {
'content-type': 'application/json; charset=utf-8',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET,POST,OPTIONS',
'access-control-allow-headers': 'content-type',
});
res.end(body);
};
const readJsonBody = (req) => new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) {
reject(new Error('Request body too large'));
req.destroy();
}
});
req.on('end', () => { if (!data) {
resolve({});
return;
}
try {
resolve(JSON.parse(data));
} catch {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', (err) => reject(err));
}); const pickAPIResult = (result) => ({
task_id: result.task_id,
wss_url: result.wss_url,
taskToken: result.taskToken,
});
const runWS = async (runner) => {
const messages = [];
const final = await runner((data) => {
messages.push(data);
});
return {
result: pickAPIResult(final.result),
messages,
};
};
const routes = {
'POST /ping': (body) => runWS((onMessage) => client.ping(body, onMessage)),
'POST /pingv6': (body) => runWS((onMessage) => client.pingV6(body, onMessage)),
'POST /tcping': (body) => runWS((onMessage) => client.tcping(body, onMessage)),
'POST /tcpingv6': (body) => runWS((onMessage) => client.tcpingV6(body, onMessage)),
'POST /http': (body) => runWS((onMessage) => client.http(body, onMessage)),
'POST /httpv6': (body) => runWS((onMessage) => client.httpV6(body, onMessage)),
'POST /httping': (body) => runWS((onMessage) => client.httping(body, onMessage)),
'POST /httpingv6': (body) => runWS((onMessage) => client.httpingV6(body, onMessage)),
'POST /traceroute': (body) => runWS((onMessage) => client.traceRoute(body, onMessage)),
'POST /traceroutev6': (body) => runWS((onMessage) => client.traceRouteV6(body, onMessage)),
'POST /dns': (body) => runWS((onMessage) => client.dns(body, onMessage)),
'POST /batch-tcping': (body) => runWS((onMessage) => client.batchTCPing(body, onMessage)),
'POST /generic': async (body) => {
if (!body?.endpoint) {
throw new Error('Missing "endpoint" in body');
}
const method = body.method || 'POST';
const params = body.params || {};
return runWS((onMessage) => client.generic(body.endpoint, method, params, onMessage));
},
};
const server = http.createServer(async (req, res) => {
if (!req.url || !req.method) {
sendJson(res, 400, {error: 'Invalid request'});
return;
}
if (req.method === 'OPTIONS') {
sendJson(res, 204, {});
return;
}
if (req.method === 'GET' && req.url === '/') {
sendJson(res, 200, {
ok: true,
service: 'itdog-web-api',
endpoints: Object.keys(routes).map((key) => key.replace('POST ', '')),
});
return;
}
const routeKey = `${req.method} ${req.url}`;
const handler = routes[routeKey];
if (!handler) {
sendJson(res, 404, {error: 'Not found'});
return;
}
try {
const body = await readJsonBody(req);
const data = await handler(body);
sendJson(res, 200, data);
} catch (error) {
sendJson(res, 400, {error: error instanceof Error ? error.message : 'Unknown error'});
}
});
server.listen(port, () => { console.log(`Server listening on http://0.0.0.0:${port}`);
});