aboutsummaryrefslogtreecommitdiff
path: root/src/server/database.ts
blob: 7f53319982e8cd8610953277f8ab03f209b2a3a9 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import * as mongodb from 'mongodb';
import { Transferable } from './Message';

export class Database {
    public static DocumentsCollection = 'documents';
    public static Instance = new Database();
    private MongoClient = mongodb.MongoClient;
    private url = 'mongodb://localhost:27017/Dash';
    private currentWrites: { [id: string]: Promise<void> } = {};
    private db?: mongodb.Db;
    private onConnect: (() => void)[] = [];

    constructor() {
        this.MongoClient.connect(this.url, (err, client) => {
            this.db = client.db();
            this.onConnect.forEach(fn => fn());
        });
    }

    public update(id: string, value: any, callback: () => void, upsert = true, collectionName = Database.DocumentsCollection) {
        if (this.db) {
            let collection = this.db.collection(collectionName);
            const prom = this.currentWrites[id];
            let newProm: Promise<void>;
            const run = (): Promise<void> => {
                return new Promise<void>(resolve => {
                    collection.updateOne({ _id: id }, value, { upsert }
                        , (err, res) => {
                            if (this.currentWrites[id] === newProm) {
                                delete this.currentWrites[id];
                            }
                            resolve();
                            callback();
                        });
                });
            };
            newProm = prom ? prom.then(run) : run();
            this.currentWrites[id] = newProm;
        } else {
            this.onConnect.push(() => this.update(id, value, callback, upsert, collectionName));
        }
    }

    public delete(query: any, collectionName?: string): Promise<mongodb.DeleteWriteOpResultObject>;
    public delete(id: string, collectionName?: string): Promise<mongodb.DeleteWriteOpResultObject>;
    public delete(id: any, collectionName = Database.DocumentsCollection) {
        if (typeof id === "string") {
            id = { _id: id };
        }
        if (this.db) {
            const db = this.db;
            return new Promise(res => db.collection(collectionName).deleteMany(id, (err, result) => res(result)));
        } else {
            return new Promise(res => this.onConnect.push(() => res(this.delete(id, collectionName))));
        }
    }

    public deleteAll(collectionName = Database.DocumentsCollection): Promise<any> {
        return new Promise(res => {
            if (this.db) {
                this.db.collection(collectionName).deleteMany({}, res);
            } else {
                this.onConnect.push(() => this.db && this.db.collection(collectionName).deleteMany({}, res));
            }
        });
    }

    public insert(value: any, collectionName = Database.DocumentsCollection) {
        if (this.db) {
            if ("id" in value) {
                value._id = value.id;
                delete value.id;
            }
            const id = value._id;
            const collection = this.db.collection(collectionName);
            const prom = this.currentWrites[id];
            let newProm: Promise<void>;
            const run = (): Promise<void> => {
                return new Promise<void>(resolve => {
                    collection.insertOne(value, (err, res) => {
                        if (this.currentWrites[id] === newProm) {
                            delete this.currentWrites[id];
                        }
                        resolve();
                    });
                });
            };
            newProm = prom ? prom.then(run) : run();
            this.currentWrites[id] = newProm;
        } else {
            this.onConnect.push(() => this.insert(value, collectionName));
        }
    }

    public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = Database.DocumentsCollection) {
        if (this.db) {
            this.db.collection(collectionName).findOne({ _id: id }, (err, result) => {
                if (result) {
                    result.id = result._id;
                    delete result._id;
                    fn(result);
                } else {
                    fn(undefined);
                }
            });
        } else {
            this.onConnect.push(() => this.getDocument(id, fn, collectionName));
        }
    }

    public getDocuments(ids: string[], fn: (result: Transferable[]) => void, collectionName = Database.DocumentsCollection) {
        if (this.db) {
            this.db.collection(collectionName).find({ _id: { "$in": ids } }).toArray((err, docs) => {
                if (err) {
                    console.log(err.message);
                    console.log(err.errmsg);
                }
                fn(docs.map(doc => {
                    doc.id = doc._id;
                    delete doc._id;
                    return doc;
                }));
            });
        } else {
            this.onConnect.push(() => this.getDocuments(ids, fn, collectionName));
        }
    }

    public query(query: { [key: string]: any }, projection?: { [key: string]: 0 | 1 }, collectionName = "newDocuments"): Promise<mongodb.Cursor> {
        if (this.db) {
            let cursor = this.db.collection(collectionName).find(query);
            if (projection) {
                cursor = cursor.project(projection);
            }
            return Promise.resolve<mongodb.Cursor>(cursor);
        } else {
            return new Promise<mongodb.Cursor>(res => {
                this.onConnect.push(() => res(this.query(query, projection, collectionName)));
            });
        }
    }

    public updateMany(query: any, update: any, collectionName = "newDocuments") {
        if (this.db) {
            const db = this.db;
            return new Promise<mongodb.WriteOpResult>(res => db.collection(collectionName).update(query, update, (_, result) => res(result)));
        } else {
            return new Promise<mongodb.WriteOpResult>(res => {
                this.onConnect.push(() => this.updateMany(query, update, collectionName).then(res));
            });
        }
    }

    public print() {
        console.log("db says hi!");
    }
}