From 63f425056c6ecea007a93753b0c86fca54b37985 Mon Sep 17 00:00:00 2001 From: Tau Date: Sun, 28 Apr 2019 20:53:03 -0400 Subject: [PATCH] Add database utility functions --- src/db.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/db.ts diff --git a/src/db.ts b/src/db.ts new file mode 100644 index 0000000..89e5620 --- /dev/null +++ b/src/db.ts @@ -0,0 +1,30 @@ +import { randomBytes } from "crypto"; +import { Pool, PoolClient } from "pg"; + +const pool = new Pool(); + +export function connect(): Promise { + return pool.connect(); +} + +export function generateId(): bigint { + const buf = randomBytes(8); + + buf[0] &= 0x7f; // Force number to be non-negative + + // Let's not depend on Node v12 for the sake of 3 LoC just yet. + + const hi = buf.readUInt32BE(0); + const lo = buf.readUInt32BE(4); + + return (BigInt(hi) << 32n) | BigInt(lo); +} + +/** Generate a random 32-bit ID for use in external protocol messages */ +export function generateExtId(): number { + const buf = randomBytes(4); + + buf[0] &= 0x7f; // Force number to be non-negative + + return buf.readUInt32BE(0); +}