-
Notifications
You must be signed in to change notification settings - Fork 262
/
Copy paththemeServer.js
87 lines (73 loc) · 1.95 KB
/
themeServer.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
// @flow
const fs = require('fs')
const os = require('os')
const express = require('express')
const bodyParser = require('body-parser')
const ifaces = os.networkInterfaces()
const PORT = 8090
const envFile = './env.json'
const OVERRIDE_THEME_FILE = './overrideTheme.json'
let address = ''
let envJSON = { THEME_SERVER: {} }
function mylog(...args) {
const now = new Date().toISOString()
console.log(`${now}:`, ...args)
}
try {
envJSON = JSON.parse(fs.readFileSync(envFile, 'utf8'))
} catch (e) {
console.log(e)
}
try {
// Get Local Host Address
Object.keys(ifaces).forEach(function (ifname) {
let found = false
ifaces[ifname].forEach(function (iface) {
if (iface.family !== 'IPv4' || iface.internal !== false) {
// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
return
}
if (found) return
address = iface.address
found = true
})
})
// Set env.json with correct path
envJSON.THEME_SERVER = {
host: `http://${address}`,
port: `${PORT}`
}
fs.writeFileSync(envFile, JSON.stringify(envJSON, null, 2))
} catch (e) {
console.log(e)
}
// Run the logging server
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(function (req, res, next) {
const method = req?.method ?? 'NO_METHOD'
const path = req?.path ?? 'NO_PATH'
mylog(`${method} ${path}`)
next() // make sure we go to the next routes and don't stop here
})
app.get('/theme', function (req, res) {
try {
const theme = JSON.parse(fs.readFileSync(OVERRIDE_THEME_FILE, 'utf8'))
res.json(theme)
} catch (e) {
res.json(e)
}
})
app.post('/theme', function (req, res) {
try {
const jsonString = JSON.stringify(req.body, null, 2)
mylog('\n' + jsonString)
fs.writeFileSync(OVERRIDE_THEME_FILE, jsonString)
res.sendStatus(200)
} catch (e) {
res.json(e)
}
})
app.listen(PORT)
console.log(`Theme server listening on ${address}:${PORT}`)