-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
155 lines (134 loc) · 3.68 KB
/
database.js
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
const debug = require("debug")("enforce-database")
const config = require(process.env.DB_ENFORCE_CONFIG || "./config.json")
const {
createConnection
} = require("mysql")
const moduleName = "Enforce Database System"
class BufferType {
constructor(datatype, data) {
this.datatype = datatype
this.data = data
}
}
const tables = Object.freeze(config.tables)
debug("Booting %s", moduleName)
let con = null
/**
* @description Database class, a wrapper for mysql methods
*/
class DataBase {
/**
* @param {{missionPrefix?: string, loopInterval?: number, bufferLimit?: number}} options
*/
constructor(options) {
this.options = Object.assign({}, config, options)
if (!("loopInterval" in this.options)) this.options.loopInterval = 10
if (!("bufferLimit" in this.options)) this.options.bufferLimit = 80000
con = createConnection(Object.assign({
insecureAuth: true
}, options))
debug(`Connecting to database...`)
con.connect(err => {
if (err) {
debug(`ERROR: ${err.message}`)
return debug(`Can't connect to msql`)
}
debug("Connected!")
})
this.mission = this.options.missionPrefix || "enf"
this.buffer = []
this._startdbLoop()
}
/**
* @description To call before the start of every mission to generate the mission id
*/
startMission(missionID) {
let now = new Date().getTime().toString()
this.mission += now
if (missionID) this.mission = missionID
debug(`Starting mission: ${this.mission}`)
return this._insert("missions", {
time: now
})
}
/**
* @param {"humidity"|"temperature"|"position"|"orientation"|"pressure"} datatype
* @param {PositionData | number | OrientationData} data
*/
_insert(datatype, data) {
if (this.buffer.length > this.options.bufferLimit) return debug(`Buffer full :: data loss ::`)
this.buffer.push(new BufferType(datatype, data))
}
save(data) {
Object.keys(data).forEach(key => {
if (key in tables) {
if (data[key] instanceof Object) {
this._insert(key, data[key])
} else {
let obj = Object.defineProperty({}, key, {
value: data[key],
enumerable: true,
writable: true
})
if ("missionID" in data) {
obj = Object.defineProperty(obj, "missionID", {
value: data.missionID,
enumerable: true,
writable: true
})
}
this._insert(key, obj)
}
}
})
}
_startdbLoop() {
this.to = setTimeout(() => {
if (!this.connected() || this.buffer.length === 0) return this._startdbLoop()
this._firstPhase(this.buffer.shift())
this._startdbLoop()
}, this.options.loopInterval)
}
/**
* @param {BufferType} buffertype
*/
_firstPhase(buffertype) {
Object.keys(tables).forEach(key => {
if (buffertype.datatype === key) this._trueInsert(tables[key], buffertype.data)
})
}
/**
* @param {"humidity"|"temperature"|"position"|"orientation"|"missions"|"pressure"} table
* @param {{}} data
* @returns {Promise<void>}
*/
_trueInsert(table, data) {
return new Promise((resolve, reject) => {
if (!this.connected()) {
debug(`Database not connected :: data loss ::`);
return reject(`Database not connected :: data loss ::`)
}
debug(`Inserting into ${table}...`)
con.query({
sql: `INSERT INTO ?? SET ?`,
values: [table, Object.assign({
missionID: this.mission,
time: new Date().getTime()
}, data)]
},
(error) => {
if (error) return reject(`ERROR: ${error.message}`)
debug(`Done.`)
resolve()
})
})
}
connected() {
return con.state === "authenticated"
}
}
module.exports = DataBase
/**
* @typedef {{ latitude: number, longitude: number, altitude:number }} PositionData
* @typedef {{ w: number, x: number, y: number, z: number, scale: number }} OrientationData
*/