aboutsummaryrefslogtreecommitdiff
path: root/src/server/database.ts
blob: 5c70da931296f2216df1ad8ef9fd01855377de76 (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
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;

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

    public update(id: string, value: any, callback: () => void) {
        if (this.db) {
            let collection = this.db.collection('documents');
            const prom = this.currentWrites[id];
            let newProm: Promise<void>;
            const run = (): Promise<void> => {
                return new Promise<void>(resolve => {
                    collection.updateOne({ _id: id }, { $set: value }, { upsert: true }
                        , (err, res) => {
                            if (err) {
                                console.log(err.message);
                                console.log(err.errmsg);
                            }
                            // if (res) {
                            //     console.log(JSON.stringify(res.result));
                            // }
                            if (this.currentWrites[id] === newProm) {
                                delete this.currentWrites[id];
                            }
                            resolve();
                            callback();
                        });
                });
            };
            newProm = prom ? prom.then(run) : run();
            this.currentWrites[id] = newProm;
        }
    }

    public delete(id: string, collectionName = Database.DocumentsCollection) {
        this.db && this.db.collection(collectionName).remove({ id: id });
    }

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

    public insert(kvpairs: any, collectionName = Database.DocumentsCollection) {
        this.db && this.db.collection(collectionName).insertOne(kvpairs, (err, res) =>
            err // &&  console.log(err)
        );
    }

    public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = Database.DocumentsCollection) {
        this.db && this.db.collection(collectionName).findOne({ id: id }, (err, result) =>
            fn(result ? ({ id: result._id, type: result.type, data: result.data }) : undefined))
    }

    public getDocuments(ids: string[], fn: (result: Transferable[]) => void, collectionName = Database.DocumentsCollection) {
        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 => ({ id: doc._id, type: doc.type, data: doc.data })));
        });
    }

    public searchQuery(ids: string[], collectionName = Database.DocumentsCollection): Promise<any> {
        return new Promise<any>(resolve => {
            this.db && this.db.collection(collectionName).find({ "data.field": { "$in": ids } }).toArray((err, docs) => {
                if (err) {
                    console.log(err.message);
                    console.log(err.errmsg);
                }
                resolve(docs);
            });
        });
    }

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