This repository has been archived by the owner on Aug 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (65 loc) · 1.77 KB
/
index.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
/**
* MPD Web API
*
* @author Jared Allard <[email protected]>
* @license MIT
* @version 1
*/
const express = require('express')
const bodyp = require('body-parser')
const dm = require('debug')
const fs = require('fs-extra')
const path = require('path')
const cors = require('cors')
const { MPC } = require('mpc-js')
const debug = dm('api:main')
const API_VERSION = process.env.API_VERSION || 'v1'
const ROUTES_DIR = path.join(__dirname, `routes/${API_VERSION}`)
const MPC_HOST = process.env.MPC_HOST || '127.0.0.1'
const MPC_PORT = process.env.MPC_PORT || 6600
const app = express()
app.use(bodyp.json())
app.use(cors())
app.use((req, res, next) => {
res.error = data => res.send({
success: false,
...data
})
res.success = data => res.send({
success: true,
data
})
next();
});
require('express-ws')(app)
const mpc = new MPC()
mpc.connectTCP(MPC_HOST, MPC_PORT)
// FIXME: We need to timeout.
mpc.on('ready', async () => {
debug('mpc->ready')
debug('starting init')
if(!await fs.exists(ROUTES_DIR)) {
throw new Error(`'${ROUTES_DIR}' not found.`)
}
const routes = await fs.readdir(ROUTES_DIR)
routes.forEach(route => {
const routeFile = path.join(ROUTES_DIR, route)
/* eslint global-require: 0, import/no-dynamic-require: 0 */
const fn = require(routeFile)
const { name } = path.parse(route)
const logger = dm(`api:endpoint:${API_VERSION}:${name}`)
const newRouter = express.Router()
try {
fn(newRouter, mpc, logger)
} catch(err) {
debug('err', err)
}
const mountPath = `/${API_VERSION}/${name}`
debug(`${route} -> (/api)?${mountPath}`)
app.use(mountPath, newRouter)
app.use(`/api${mountPath}`, newRouter)
});
app.listen(8100, () => {
debug('listening on port 8100')
})
})