85 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-04-18 16:40:08 -04:00
import express, { Express, NextFunction, Request, Response } from "express"
import dotenv from "dotenv"
import { createServer } from "http"
import { Server } from "socket.io"
import { z } from "zod"
2024-04-21 22:55:49 -04:00
import { User } from "./types"
2024-04-26 02:10:37 -04:00
import getSandboxFiles from "./getSandboxFiles"
2024-04-18 16:40:08 -04:00
dotenv.config()
const app: Express = express()
const port = process.env.PORT || 4000
// app.use(cors())
const httpServer = createServer(app)
const io = new Server(httpServer, {
cors: {
origin: "*",
},
})
2024-04-21 22:55:49 -04:00
const handshakeSchema = z.object({
userId: z.string(),
sandboxId: z.string(),
EIO: z.string(),
transport: z.string(),
})
2024-04-18 16:40:08 -04:00
io.use(async (socket, next) => {
const q = socket.handshake.query
console.log("middleware")
2024-04-21 22:55:49 -04:00
const parseQuery = handshakeSchema.safeParse(q)
if (!parseQuery.success) {
console.log("Invalid request.")
2024-04-18 16:40:08 -04:00
next(new Error("Invalid request."))
2024-04-21 22:55:49 -04:00
return
}
const { sandboxId, userId } = parseQuery.data
2024-04-21 22:55:49 -04:00
2024-04-26 02:10:37 -04:00
const dbUser = await fetch(`http://localhost:8787/api/user?id=${userId}`)
2024-04-21 22:55:49 -04:00
const dbUserJSON = (await dbUser.json()) as User
console.log("dbUserJSON:", dbUserJSON)
if (!dbUserJSON) {
console.log("DB error.")
next(new Error("DB error."))
return
2024-04-18 16:40:08 -04:00
}
2024-04-26 02:10:37 -04:00
const sandbox = dbUserJSON.sandbox.find((s) => s.id === sandboxId)
2024-04-18 16:40:08 -04:00
2024-04-21 22:55:49 -04:00
if (!sandbox) {
console.log("Invalid credentials.")
2024-04-18 16:40:08 -04:00
next(new Error("Invalid credentials."))
2024-04-21 22:55:49 -04:00
return
}
2024-04-26 02:10:37 -04:00
socket.data = {
id: sandboxId,
userId,
2024-04-18 16:40:08 -04:00
}
next()
})
io.on("connection", async (socket) => {
2024-04-21 22:55:49 -04:00
const data = socket.data as {
userId: string
2024-04-26 02:10:37 -04:00
id: string
2024-04-21 22:55:49 -04:00
}
2024-04-26 02:10:37 -04:00
const sandboxFiles = await getSandboxFiles(data.id)
2024-04-18 16:40:08 -04:00
socket.emit("loaded", sandboxFiles.files)
2024-04-18 16:40:08 -04:00
})
httpServer.listen(port, () => {
console.log(`Server running on port ${port}`)
})