UNPKG

1.94 kBJavaScriptView Raw
1/* eslint-disable import/no-unresolved, import/no-extraneous-dependencies, global-require */
2
3const { hasPackage } = require('@sharyn/check-setup')
4
5hasPackage('koa', true)
6hasPackage('koa-router', true)
7const Koa = require('koa')
8const router = new (require('koa-router'))()
9
10const colors = require('colors/safe')
11const exitHook = require('exit-hook')
12
13const PREFIX = colors.cyan('[sharyn/koa]')
14const { NODE_ENV } = process.env
15const PORT = process.env.PORT || 8000
16
17let server
18
19const stopServer = options => {
20 if (server) {
21 if (!(options && options.silent)) {
22 // eslint-disable-next-line no-console
23 console.log() // cross-os newline
24 // eslint-disable-next-line no-console
25 console.log(`${PREFIX} Server stopped`)
26 }
27 if (hasPackage('@sharyn/db')) {
28 require('@sharyn/db').knex.destroy()
29 }
30 return server.close()
31 }
32 throw Error('Tried to stop the server but no server was running')
33}
34
35const startServer = (routing, options) => {
36 if (!routing) {
37 throw Error('You must pass a routing function to startServer')
38 }
39
40 if (!(options && options.silent)) {
41 // eslint-disable-next-line no-console
42 console.log(`${PREFIX} Server running on port ${PORT} ${NODE_ENV ? `(${NODE_ENV})` : ''}`)
43 exitHook(() => stopServer())
44 }
45
46 const app = new Koa()
47
48 if (hasPackage('koa-compress')) {
49 app.use(require('koa-compress')())
50 }
51
52 if (hasPackage('koa-mount') && hasPackage('koa-static')) {
53 const mount = require('koa-mount')
54 const serveStatic = require('koa-static')
55 app.use(mount('/static', serveStatic('dist'))).use(mount('/static', serveStatic('public')))
56 }
57
58 if (hasPackage('koa-favicon')) {
59 app.use(require('koa-favicon')(`./public/img/favicon.ico`))
60 }
61
62 routing(router)
63 app.use(router.routes()).use(router.allowedMethods())
64
65 server = app.listen((options && options.port) || PORT)
66}
67
68exports.startServer = startServer
69exports.stopServer = stopServer