-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.ts
79 lines (67 loc) · 2.47 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
77
78
79
import { parseArgs } from "./deps.ts"
import { serveFile } from "./deps.ts"
import { ClientHandler } from "./server/clientHandler.ts"
export class Server {
private port: string
private clientHandler: ClientHandler
private publicFolder = "./client/public"
private publicFiles: string[] = []
constructor(serverConfigs: any) {
const argPort: number = parseArgs(Deno.args).port
const herokuPort = Deno.env.get("PORT")
this.port = herokuPort ? Number(herokuPort) : argPort ? Number(argPort) : serverConfigs.defaultPort
this.clientHandler = new ClientHandler(serverConfigs)
}
public async reqHandler(req: Request) {
if (req.headers.get("upgrade") != "websocket") {
return await this.handleNonWsRequests(req)
}
const { socket: ws, response } = Deno.upgradeWebSocket(req)
this.clientHandler.handleClient(ws)
return response
}
public init(): void {
const portInt = Number(this.port)
this.setPublicFilesList(this.publicFolder)
Deno.serve({ port: portInt }, this.reqHandler.bind(this))
}
public async handleNonWsRequests(req: Request): Promise<Response> {
const url = new URL(req.url)
let cleanedUrl = url.pathname
let response: Response = new Response()
if(req.url.includes('?')) {
cleanedUrl = req.url.split('?')[0]
}
if (req.method === "GET" && cleanedUrl === "/") {
response = await serveFile(req, "./client/public/index.html")
}
if (req.method === "GET" && cleanedUrl === "/favicon.ico") {
response = await serveFile(req, "./client/public/favicon.ico")
}
if (req.method === "GET" && cleanedUrl === "/[email protected]") {
response = await serveFile(req, "./client/public/[email protected]")
}
for (const file of this.publicFiles) {
if (req.method === "GET" && cleanedUrl === `/js/${file}`) {
response = await serveFile(req, `./client/public/${file}`)
}
}
return response
}
public setPublicFilesList(path: string): void {
for (const dirEntry of Deno.readDirSync(path)) {
if (dirEntry.isDirectory) {
this.setPublicFilesList(`${path}/${dirEntry.name}`)
} else {
let pathToRemove = this.publicFolder
let outputFile = dirEntry.name
if (this.publicFolder !== path) {
pathToRemove += "/"
outputFile = `/${outputFile}`
}
const outputPath = path.replace(`${pathToRemove}`, "")
this.publicFiles.push(`${outputPath}${outputFile}`)
}
}
}
}