1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Component');
|
7 |
|
8 | module.exports = class Database extends Base {
|
9 |
|
10 | static getConstants () {
|
11 | return {
|
12 | EVENT_OPEN_CONNECTION: 'openConnection',
|
13 | EVENT_CLOSE_CONNECTION: 'closeConnection',
|
14 | EVENT_ERROR: 'error',
|
15 | EVENT_COMMAND: 'command'
|
16 | };
|
17 | }
|
18 |
|
19 | static normalizeId (id) {
|
20 | return id;
|
21 | }
|
22 |
|
23 | constructor (config) {
|
24 | super(config);
|
25 | this._connection = null;
|
26 | this._builder = this.spawn(this.QueryBuilder, {db: this});
|
27 | }
|
28 |
|
29 | async init () {
|
30 | await this.open();
|
31 | }
|
32 |
|
33 | async open () {
|
34 | if (this._connection) {
|
35 | throw new Error(`Connection is already opened: ${this.getUri()}`);
|
36 | }
|
37 | this._connection = await this.openConnection();
|
38 | this.log('info', `Connection opened: ${this.getUri()}`);
|
39 | await this.trigger(this.EVENT_OPEN_CONNECTION);
|
40 | }
|
41 |
|
42 | async close () {
|
43 | if (!this._connection) {
|
44 | throw new Error(`Connection is already closed: ${this.getUri()}`);
|
45 | }
|
46 | await this.closeConnection();
|
47 | this._connection = null;
|
48 | this.log('info', `Connection closed: ${this.getUri()}`);
|
49 | await this.trigger(this.EVENT_CLOSE_CONNECTION);
|
50 | }
|
51 |
|
52 | async openConnection () {
|
53 | throw new Error('Open connection');
|
54 | }
|
55 |
|
56 | async closeConnection () {
|
57 | throw new Error('Close connection');
|
58 | }
|
59 |
|
60 | normalizeId (id) {
|
61 | return this.constructor.normalizeId(id);
|
62 | }
|
63 |
|
64 | getUri (withPassword) {
|
65 | const {database, host, port, user, password} = this.settings;
|
66 | const auth = user ? (user +':'+ (withPassword ? password : '*') +'@') : '';
|
67 | return `${this.schema}://${auth}${host}:${port}/${database}`;
|
68 | }
|
69 |
|
70 | logCommand (command, data) {
|
71 | this.log('trace', `${this.settings.database}: ${command}`, data);
|
72 | }
|
73 |
|
74 | afterError (message, data) {
|
75 | this.log('error', message, data);
|
76 | return this.trigger(this.EVENT_ERROR, {message, data});
|
77 | }
|
78 |
|
79 | buildCondition (condition) {
|
80 | return this._builder.buildWhere(condition);
|
81 | }
|
82 |
|
83 | async buildQuery (query) {
|
84 | await query.prepare();
|
85 | return this._builder.build(query);
|
86 | }
|
87 |
|
88 | dropAllByName (name) {
|
89 |
|
90 | }
|
91 | }; |
\ | No newline at end of file |