UNPKG

1.95 kBJavaScriptView Raw
1/* eslint-disable no-console */
2const path = require('path')
3const fs = require('fs')
4const URL = require('url')
5const api = require('insights-api/lib/app').default
6const express = require('express')
7const bodyParser = require('body-parser')
8
9module.exports = function startInsights({
10 host = process.env.INSIGHTS_HOST || '127.0.0.1',
11 port = process.env.INSIGHTS_PORT || 8000,
12
13 publicUrl = process.env.INSIGHTS_PUBLIC_URL || `http://${host}:${port}`,
14 staticRoot = process.env.INSIGHTS_STATIC_ROOT || path.join(__dirname, '..', 'web-build'),
15
16 apiPath = process.env.INSIGHTS_API_PATH || `/api`,
17 // TODO: no way to configure socketPath yet, must stay at "/socket.io"
18 socketPath = process.env.INSIGHTS_SOCKET_PATH || '/socket.io'
19} = {}) {
20 console.log({
21 host,
22 port,
23 publicUrl,
24 staticRoot,
25 socketPath,
26 apiPath
27 })
28
29 let indexHtml
30
31 const getIndex = (req, res) => {
32 if (!indexHtml) {
33 const html = fs.readFileSync(path.join(staticRoot, 'index.html'), 'utf8')
34 const insightsConfig = {
35 apiPath,
36 socketPath,
37 publicUrl,
38 noLogin: api.get('authentication').authStrategies.includes('noLogin')
39 }
40 indexHtml = html.replace("</head>", `<script>window.__INSIGHTS_CONFIG__ = ${JSON.stringify(insightsConfig)}</script></head>`)
41 }
42 res.send(indexHtml)
43 }
44
45 const app = express()
46 app.use(bodyParser.json())
47 app.use(bodyParser.urlencoded({extended: true}))
48 app.get('/', getIndex)
49 app.get(apiPath, getIndex) // redirect /api -> /
50 app.use(apiPath, api)
51 app.use(express.static(staticRoot))
52 app.get('*', getIndex)
53
54 console.info(`Starting insights on ${host} port ${port}`)
55
56 const server = app.listen(port, host)
57 api.setup(server)
58
59 process.on('unhandledRejection', (reason, p) =>
60 console.error('Unhandled Rejection at: Promise ', p, reason)
61 )
62
63 server.on('listening', () => {
64 console.info(`--> ${publicUrl}`)
65 })
66
67 return app
68}