-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbsync.js
83 lines (72 loc) · 2.23 KB
/
dbsync.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
'use strict'
require('dotenv').load({ silent: true })
const db = require('./server/dataAccess')
const enums = require('./common/enums')
const { calculateExchangeRate } = require('./server/utils/math')
let force = false
// Sync DB
if (process.env.NODE_APP_INSTANCE === 'live') {
force = false
}
if (!process.env.DEVELOPMENT_SCRIPT) {
throw new Error('Cant run without DEVELOPMENT_SCRIPT env')
}
db.sequelize.sync({ force })
.then(() => db.sequelize.transaction({ autocommit: false }, dbTransaction => insertCommodities(dbTransaction)
.then(() => insertInitialExchangeRates(dbTransaction))
.then(() => insertDefaultGame(dbTransaction))))
.then(() => {
console.log('DB is synced.')
return process.exit(0)
})
.catch(err => {
console.error(err)
return process.exit(1)
})
function insertInitialExchangeRates(dbTransaction) {
const exchangeRates = []
for (const key in enums.COMMODITIES) {
if (enums.COMMODITIES.hasOwnProperty(key)) {
if (!enums.COMMODITIES[key] || !enums.COMMODITIES[key].id || !enums.COMMODITIES[key].name) {
continue
}
exchangeRates.push({
commodityId: enums.COMMODITIES[key].id,
time: new Date().toISOString(),
value: 0,
exchangeRate: calculateExchangeRate(0, enums.COMMODITIES[key].median),
})
}
}
return db.ExchangeRate.bulkCreate(exchangeRates, { transaction: dbTransaction })
}
function insertCommodities(dbTransaction) {
const commodities = createIdNameData(enums.COMMODITIES)
return db.Commodity.bulkCreate(commodities, { transaction: dbTransaction })
}
function insertDefaultGame(dbTransaction) {
const defaultGame = {
start: new Date('2017-11-08T10:00:00.000Z').toISOString(),
end: new Date('2017-11-08T11:30:00.000Z').toISOString(),
}
return db.Game.create(defaultGame, { transaction: dbTransaction })
}
function createIdNameData(ENUM) {
const data = []
for (const key in ENUM) {
if (ENUM.hasOwnProperty(key)) {
if (!ENUM[key] || !ENUM[key].id || !ENUM[key].name) {
continue
}
const temp = {
id: ENUM[key].id,
name: ENUM[key].name,
}
if (ENUM[key].median) {
temp.median = ENUM[key].median
}
data.push(temp)
}
}
return data
}