58 lines
2.2 KiB
TypeScript
58 lines
2.2 KiB
TypeScript
// import { InfluxDB, Point } from '@influxdata/influxdb-client';
|
|
import pg from 'pg';
|
|
const { Client } = pg;
|
|
const client = new Client(process.env.DATABASE_URL);
|
|
await client.connect();
|
|
|
|
// export const influx = new InfluxDB({ url: process.env.INFLUX_URL!, token: process.env.INFLUX_TOKEN! });
|
|
// export const writeApi = influx.getWriteApi(process.env.INFLUX_ORG!, process.env.INFLUX_BUCKET!, 's');
|
|
|
|
const fields = ['id', 'call', 'prefix', 'mode', 'band', 'state', 'section', 'country', 'initials', 'operator', 'class', 'computer', 'time'];
|
|
|
|
const server = Bun.serve({
|
|
hostname: process.env.HOST || '0.0.0.0',
|
|
port: process.env.PORT ? parseInt(process.env.PORT) : 9992,
|
|
async fetch (req) {
|
|
const path = new URL(req.url).pathname;
|
|
console.log('-> Recieved logs, parsing...');
|
|
if (req.method !== 'POST') new Response('Invalid method', { status: 405 });
|
|
if (process.env.AUTH_TOKEN && req.headers.get('Authorization') === process.env.AUTH_TOKEN) new Response('Unauthorized', { status: 401 });
|
|
if (req.headers.get('Content-Type') !== 'application/json') new Response('Invalid content type', { status: 404 });
|
|
|
|
try {
|
|
const newRows: any[] = await req.json();
|
|
const query = `INSERT INTO contacts (${fields.join(', ')}) VALUES (${fields.map((_, i) => `$${i + 1}`).join(', ')}) ON CONFLICT (id) DO UPDATE SET ${fields.map((f, i) => `${f} = $${i + 1}`).slice(1).join(', ')}`
|
|
|
|
for (const row of newRows) {
|
|
const data: Record<string, string> = {
|
|
id: row.fldPrimaryKey,
|
|
call: row.fldCall,
|
|
prefix: row.fldPrefix,
|
|
mode: row.fldModeContest,
|
|
band: row.fldBand,
|
|
state: row.fldState,
|
|
section: row.fldSection,
|
|
country: row.fldCountryWorked,
|
|
initials: row.fldInitials,
|
|
operator: row.fldOperator,
|
|
class: row.fldClass,
|
|
computer: row.fldComputerName,
|
|
time: `${row.fldDateStr.replaceAll('/', '-')} ${row.fldTimeOnStr}+00`
|
|
};
|
|
await client.query(query, fields.map((f) => data[f]));
|
|
}
|
|
|
|
// await writeApi.close();
|
|
console.log(`<- Wrote ${newRows.length.toLocaleString()} row(s)!`);
|
|
} catch (e) {
|
|
console.log('!! Failed to push');
|
|
console.error(e);
|
|
new Response('Server error', { status: 500 });
|
|
}
|
|
|
|
return new Response('Okay!');
|
|
}
|
|
})
|
|
|
|
console.log(`Listening on ${server.url}`);
|