UNPKG

2.52 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('../base/Component');
7
8module.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 open: ${this.getUri()}`);
36 }
37 this.log('info', `Connection is opening: ${this.getUri()}`);
38 this._connection = await this.openConnection();
39 this.log('info', 'Connection is open');
40 await this.trigger(this.EVENT_OPEN_CONNECTION);
41 }
42
43 async close () {
44 if (!this._connection) {
45 throw new Error(`Connection is already closed: ${this.getUri()}`);
46 }
47 await this.closeConnection();
48 this._connection = null;
49 this.log('info', `Connection closed: ${this.getUri()}`);
50 await this.trigger(this.EVENT_CLOSE_CONNECTION);
51 }
52
53 async openConnection () {
54 throw new Error('Open connection');
55 }
56
57 async closeConnection () {
58 throw new Error('Close connection');
59 }
60
61 normalizeId (id) {
62 return this.constructor.normalizeId(id);
63 }
64
65 getUri (withPassword) {
66 const {database, host, port, user, password} = this.settings;
67 const auth = user ? (user +':'+ (withPassword ? password : '*') +'@') : '';
68 return `${this.schema}://${auth}${host}:${port}/${database}`;
69 }
70
71 traceCommand (command, data) {
72 this.log('trace', `${this.settings.database}: ${command}`, data);
73 }
74
75 afterError (message, data) {
76 this.log('error', message, data);
77 return this.trigger(this.EVENT_ERROR, {message, data});
78 }
79
80 buildCondition (condition) {
81 return this._builder.buildWhere(condition);
82 }
83
84 async buildQuery (query) {
85 await query.prepare();
86 return this._builder.build(query);
87 }
88
89 dropAllByName (name) {
90 }
91};
\No newline at end of file