This repository was archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathimportVotings.js
70 lines (61 loc) · 2.04 KB
/
importVotings.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
//
// This script imports additional votings
//
// usage
// cf_server cat script/data/votings.json | node script/importVotings.js
//
const PgDb = require('../lib/pgdb')
const rw = require('rw')
require('dotenv').config()
PgDb.connect().then(async (pgdb) => {
const input = JSON.parse(rw.readFileSync('/dev/stdin', 'utf8'))
if (!input || !input.votings) {
console.error('input.votings required')
process.exit(1)
}
console.log(`importing new votings...`)
const transaction = await pgdb.transactionBegin()
try {
for (let voting of input.votings) {
const {name, beginDate, endDate, options} = voting
const existingVoting = await transaction.public.votings.findOne({name})
let newVoting
if (existingVoting) { // update existing
newVoting = await transaction.public.votings.updateAndGetOne({id: existingVoting.id}, {
beginDate: beginDate ? new Date(beginDate) : undefined,
endDate: endDate ? new Date(endDate) : undefined,
updatedAt: new Date()
}, {skipUndefined: true})
} else {
newVoting = await transaction.public.votings.insertAndGet({
name,
beginDate: beginDate ? new Date(beginDate) : undefined,
endDate: endDate ? new Date(endDate) : undefined
}, {skipUndefined: true})
}
for (let option of options) {
const existingOption = await transaction.public.votingOptions.findOne({
votingId: newVoting.id,
name: option.name
})
if (!existingOption) {
await transaction.public.votingOptions.insert({
votingId: newVoting.id,
name: option.name
})
}
}
}
await transaction.transactionCommit()
console.log('done! New votings:')
console.log(await pgdb.public.votings.find({}, {orderBy: ['createdAt desc']}))
} catch (e) {
console.log('error in transaction! rolledback!')
console.log(e)
await transaction.transactionRollback()
}
}).then(() => {
process.exit()
}).catch(e => {
console.log(e)
})