aboutsummaryrefslogtreecommitdiff
path: root/src/database/postgres.ts
blob: 2ea19bd92b91a49b266291730fdbe057e82fba80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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);
    });
}