From 747097af03e422c72c2fe0065637e59a1685d219 Mon Sep 17 00:00:00 2001 From: kartofen Date: Sun, 23 Oct 2022 21:34:48 +0300 Subject: nearly completed, forgot to make a repo --- src/database/postgres.ts | 74 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/database/postgres.ts (limited to 'src/database') diff --git a/src/database/postgres.ts b/src/database/postgres.ts new file mode 100644 index 0000000..2ea19bd --- /dev/null +++ b/src/database/postgres.ts @@ -0,0 +1,74 @@ +import { Client } from 'pg'; +var connectionString = "postgres://scale:secret@db/scale?sslmode=disable"; +let client: Client; + +export function InitPostgres() { + client = new Client(connectionString); + client.connect(); +} + +export function ClosePostgres() { + client.end(); +} + +export function CustomQuery(query: string, callback: (r: { status: number, data: any }) => void) { + client.query(query, (err, res) => { + let r: { status: number, data: any } = { status: 500, data: undefined }; + if (err) { + r.data = err.message; + } else { + r.status = 200; r.data = res.rows; + } + callback(r); + }); +} + +export function GetBoards(callback: (r: { status: number, data: any }) => void) { + let query = ` +select s.nspname as board +from pg_catalog.pg_namespace s +where nspname != 'pg_toast' and nspname != 'pg_catalog' +and nspname != 'public' and nspname != 'information_schema';`; // to remove the default schemas + + client.query(query, (err, res) => { + let r: { status: number, data: any } = { status: 500, data: undefined }; + if (err) { + r.status = 404; r.data = err.message; + } else { + r.status = 200; r.data = []; + for(let board of res.rows) + r.data.push(board.board); + } + callback(r); + }); +} + +export function CreateBoard(name: string, callback: (r: { status: number, data: any }) => void) { + let query = ` +create schema ${name}; +create table ${name}.threads( + id serial primary key, + timestamp bigint, + title text, + content text, + image text, + imagetype text +); +create table ${name}.comments( + id serial primary key, + timestamp bigint, + content text, + image text, + imagetype text +);`; + + client.query(query, (err, res) => { + let r: { status: number, data: any } = { status: 500, data: undefined }; + if (err) { + r.data = err.message; + } else { + r.status = 200; + } + callback(r); + }); +} -- cgit v1.2.3