This commit is contained in:
seb
2026-07-27 02:18:07 +02:00
parent 10c4269da0
commit e9f29dc569
4 changed files with 36 additions and 1 deletions

View File

@@ -13,11 +13,19 @@ export function readBody(req) {
});
}
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400',
};
export function sendJson(res, statusCode, body) {
const responseBody = JSON.stringify(body);
res.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(responseBody),
...CORS_HEADERS,
});
res.end(responseBody);
}
@@ -26,10 +34,19 @@ export function sendBinary(res, statusCode, buffer, contentType) {
res.writeHead(statusCode, {
'Content-Type': contentType,
'Content-Length': buffer.length,
...CORS_HEADERS,
});
res.end(buffer);
}
export function sendCorsPreflight(res) {
res.writeHead(204, {
'Content-Length': 0,
...CORS_HEADERS,
});
res.end();
}
export function normalizePath(pathname) {
return pathname.replace(/^\/api(?=\/v1\/)/, '');
}

View File

@@ -1,5 +1,5 @@
import { endpoints } from './endpoints/index.js';
import { normalizePath, readBody, sendJson } from './http.js';
import { normalizePath, readBody, sendCorsPreflight, sendJson } from './http.js';
function buildConfig(config = {}) {
return {
@@ -18,6 +18,10 @@ export function createJtlPosServer(pairingStore, config = {}) {
const routes = new Map(endpoints.map((endpoint) => [`${endpoint.method} ${endpoint.path}`, endpoint]));
async function handle(req, res) {
if (req.method === 'OPTIONS') {
return sendCorsPreflight(res);
}
const url = new URL(req.url, 'https://localhost');
const pathname = normalizePath(url.pathname);
const routeKey = `${req.method} ${pathname}`;