-
Notifications
You must be signed in to change notification settings - Fork 152
/
util-google-cloud-datastore.js
61 lines (51 loc) · 1.26 KB
/
util-google-cloud-datastore.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
const { Datastore } = require('@google-cloud/datastore')
const { readConfigurationFromFile } = require('./util-file')
const datastore = new Datastore()
const key = datastore.key(['configuration', 1])
const getConfiguration = async callback => {
try {
const [entity] = await datastore.get(key)
if (typeof entity !== 'undefined') {
callback(null, entity)
} else {
callback(new Error('configuration invalid, entity not found'))
}
} catch (error) {
return callback(error)
}
}
const createConfigurationIfNotExists = () => {
hasConfiguration(error => {
if (error) {
readConfigurationFromFile().then(configurationAsString => {
const entity = {
key: key,
data: JSON.parse(configurationAsString)
}
datastore.save(entity).then(result => {
console.log('entity successfully created, configuration saved')
}).catch(error => { console.log(error) })
})
}
})
}
const setConfiguration = async (configuration, callback) => {
const entity = {
key: key,
data: configuration
}
try {
await datastore.upsert(entity)
callback(null)
} catch (error) {
callback(error)
}
}
const hasConfiguration = callback => {
getConfiguration(callback)
}
module.exports = {
createConfigurationIfNotExists,
getConfiguration,
setConfiguration
}