49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
'use strict';
|
|
|
|
const http = require('node:http');
|
|
const { parse } = require('./registry');
|
|
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
|
|
function createServer() {
|
|
return http.createServer((request, response) => {
|
|
if (request.method === 'GET' && request.url === '/health') {
|
|
response.writeHead(200, { 'content-type': 'application/json' });
|
|
response.end(JSON.stringify({ ok: true }));
|
|
return;
|
|
}
|
|
if (request.method !== 'POST' || request.url !== '/v1/parse') {
|
|
response.writeHead(404).end();
|
|
return;
|
|
}
|
|
let bytes = 0;
|
|
const chunks = [];
|
|
request.on('data', chunk => {
|
|
bytes += chunk.length;
|
|
if (bytes > MAX_BODY_BYTES) {
|
|
response.writeHead(413).end();
|
|
request.destroy();
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
request.on('end', () => {
|
|
if (bytes > MAX_BODY_BYTES) return;
|
|
try {
|
|
const { plugin, operation, input } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
const output = parse(plugin, operation, input);
|
|
response.writeHead(200, { 'content-type': 'application/json' });
|
|
response.end(JSON.stringify(output));
|
|
} catch (error) {
|
|
response.writeHead(400, { 'content-type': 'application/json' });
|
|
response.end(JSON.stringify({ error: error.message }));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
if (require.main === module) {
|
|
createServer().listen(Number(process.env.SOURCE_PLUGIN_PORT || 8094), process.env.SOURCE_PLUGIN_HOST || '127.0.0.1');
|
|
}
|
|
|
|
module.exports = { createServer };
|