explode-self-service/server.ts

95 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import express, { Request, Response } from "express"
import { json as bodyParserJson, urlencoded as bodyParserUrlEncoded } from "body-parser"
import cookieParser from "cookie-parser"
import { Axios } from "axios"
const app = express()
app.use(bodyParserJson())
app.use(bodyParserUrlEncoded({ extended: true }))
app.use(cookieParser())
app.use(express.static(__dirname + "/public"))
app.get("/", (req: Request, res: Response) => {
res.render("layout")
})
app.post("/register", async (req: Request, res: Response) => {
let isRegistered = req.cookies.isRegistered
if(isRegistered) {
return res.send("服务器正在探索:利维坦,涅索斯轨道")
}
let username: string = req.body.RegisterUsername
let password: string = req.body.RegisterPassword
if(!username || !password) {
return res.status(400).send("注册失败:无效的用户名或密码!")
}
if(username.length < 4) {
return res.status(400).send("账号太短啦~")
}
if(password.length < 4) {
return res.status(400).send("密码太短啦~")
}
if(await explode_does_user_exists(username)) {
return res.status(400).send("名字撞车啦!")
}
let hasId = await explode_register(username, password)
if(hasId != null) {
// 使用 cookie 避免重复注册
res.cookie("isRegistered", "1", {
expires: new Date(Date.now() + 9000000),
httpOnly: true
})
return res.send(`注册成功用户ID${hasId._id}。要记住哦!`)
} else {
return res.status(500).send("出错啦,注册失败了。")
}
})
const server = app.listen(8090, () => console.log("Server is running..."))
const _axios = new Axios({})
type HasId = {
_id: string
}
async function explode_graphql<T>(query: string) {
return _axios.post<T>("http://43.142.173.63:10483/graphql", JSON.stringify({
"operationName": "",
"query": query,
variables: {}
}), {
// idk why is this happening, but it just happened that
// the response is string which should be transformed to JSON auto.
transformResponse: (resp) => JSON.parse(resp)
})
}
async function explode_register(username: string, password: string) {
let response = await explode_graphql<{
data: {
registerUser: HasId
}
}>(`mutation { registerUser(username: "${username}", password: "${password}") { _id } }`)
return response.data.data.registerUser
}
async function explode_does_user_exists(username: string) {
let response = await explode_graphql<{
data: {
userByUsername: HasId | undefined
}
}>(`query { userByUsername(username: "${username}") { _id } }`)
return !!response.data.data.userByUsername
}