-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsettings.js
88 lines (72 loc) · 2.2 KB
/
settings.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
const AWS = require('aws-sdk')
const SQL = require('@nearform/sql')
const crypto = require('crypto')
const querystring = require('querystring')
const { unflatten } = require('flat')
const { withDatabase, getAssetsBucket, runIfDev } = require('./utils')
async function getSettingsBody(client) {
const sql = SQL`SELECT is_language, settings_key, settings_value FROM settings`
const { rows } = await client.query(sql)
const result = {
exposures: {},
language: {}
}
for (const {
is_language: isLanguage,
settings_key: settingsKey,
settings_value: settingsValue
} of rows) {
result[isLanguage ? 'language' : 'exposures'][settingsKey] = settingsValue
}
return unflatten(result)
}
async function isChanged(s3, bucket, key, hash) {
try {
const { TagSet } = await s3
.getObjectTagging({ Bucket: bucket, Key: key })
.promise()
for (const { Key, Value } of TagSet) {
if (Key === 'Hash') {
return Value !== hash
}
}
return true
} catch (error) {
return true
}
}
async function updateIfChanged(s3, bucket, key, data) {
const md5 = crypto.createHash('md5')
const hash = md5.update(JSON.stringify(data)).digest('hex')
if (await isChanged(s3, bucket, key, hash)) {
console.log(`writing ${key} with hash ${hash}`)
const object = {
ACL: 'private',
Body: Buffer.from(JSON.stringify({ generatedAt: new Date(), ...data })),
Bucket: bucket,
ContentType: 'application/json',
Key: key,
Tagging: querystring.stringify({
Hash: hash
})
}
await s3.putObject(object).promise()
} else {
console.log(`file ${key} has not changed`)
}
}
exports.handler = async function () {
const s3 = new AWS.S3({ region: process.env.AWS_REGION })
const bucket = await getAssetsBucket()
return await withDatabase(async (client) => {
const { exposures, language } = await getSettingsBody(client)
await updateIfChanged(s3, bucket, 'exposures.json', exposures)
await updateIfChanged(s3, bucket, 'language.json', language)
await updateIfChanged(s3, bucket, 'settings.json', {
...exposures,
...language
})
return { exposures, language }
})
}
runIfDev(exports.handler)