schangxiang@126.com
2025-09-19 0821aa23eabe557c0d9ef5dbe6989c68be35d1fe
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
const EventEmitter = require('events').EventEmitter;
 
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;
 
const linkDb = Symbol('#linkDb');
 
let dbProxy = module.exports = class extends EventEmitter {
    constructor(config) {
        super();
 
        if (!config.hosts || !config.db) {
            let err = new Error('host, port & db is required in config.');
 
            this.emit('error', err);
 
            throw err;
        }
 
        let url = 'mongodb://';
 
        if (config.username) {
            if (config.password) {
                url += `${config.username}:${config.password}@`;
            } else {
                url += `${config.username}@`;
            }
        }
 
        url += `${config.hosts}/${config.db}`;
 
        if (config.query) {
            url += `?${config.query}`;
        }
 
        this.ObjectId = this.ObjectID = ObjectId;
 
        this.dbname = config.db || 'test';
        this.url = url;
        this[linkDb] = null;
        this.destory = false;
    }
 
    connect() {
        return MongoClient.connect(this.url, {useNewUrlParser: true}).then(client => {
            const db = client.db(this.dbname);
            this[linkDb] = db;
 
            this.emit('connect');
 
            db.on('reconnect', err => {
                this.emit('reconnect', err || null);
            });
 
            db.on('close', err => {
                if (err) {
                    this.emit('error', err);
                }
 
                this.emit('close', err);
 
                this[linkDb] = null;
                this.destory = true;
            });
 
            db.on('error', err => {
                this.emit('error', err);
 
                db.close();
 
                this[linkDb] = null;
            });
 
        }).catch(err => this.emit('error', err));
    }
 
    collection(name) {
        if (this.destory) {
            let err = new Error('db proxy has been destroyed.');
 
            return this.emit('error', err);
        }
 
        return this[linkDb].collection(name);
    }
 
    close() {
        return this[linkDb].close();
    }
};