This repository has been archived by the owner on Jul 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.ts
76 lines (62 loc) · 1.78 KB
/
server.ts
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
// JS
import { readFileSync } from 'fs'
import { resolve } from 'path'
import { default as express } from 'express'
import { default as expressWs } from 'express-ws'
import { default as serveFavicon } from 'serve-favicon'
import { getOnMessage } from './getOnMessage'
// Type
import { Express } from 'express'
import { Client, Pony } from '@pixelpony/shared'
import { Registry } from './registry'
export interface ServerParam {
client: Client
app?: Express
}
export type Server = (param: ServerParam) => expressWs.Application
export const server: Server = (param) => {
let { client, app } = param
app = app || express()
let { location } = client
let faviconPath = resolve(location, client.favicon)
let htmlRootPath = resolve(location, client.htmlRoot)
let publicPath = resolve(location, client.public)
let ews = expressWs(app)
let wss = ews.getWss()
// let { app } = ews
// Favicon
app.use(
serveFavicon(faviconPath, {
redirect: false,
}),
)
// Known ponies
let registry = new Registry<unknown, Pony>()
// Ws Routes
ews.app.ws('/websocket', (ws, req) => {
let { onmessage } = getOnMessage({ registry, ws, wss })
ws.onmessage = (event) => {
let { type } = event
if (type === 'message') {
// ^ Maybe unecessary verification - idk ox
onmessage(event)
} else {
console.log('type !== "message" -- the verification is usefull')
}
}
})
// Static Routes
app.get('/', (req, res) => {
res.sendFile(htmlRootPath)
})
let favicon = readFileSync(faviconPath)
app.get('/favicon', (req, res) => {
res.send(favicon)
})
app.use(
express.static(publicPath, {
redirect: false,
}),
)
return ews.app
}