mirror of
https://github.com/Floriansylvain/space-game-api.git
synced 2026-08-19 11:43:19 +02:00
Initial commit
This commit is contained in:
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,48 @@
|
||||
import express from "express";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "../app";
|
||||
|
||||
export const scoreRouter = express.Router();
|
||||
|
||||
const scorePostValidator = z.object({
|
||||
nickname: z.string(),
|
||||
score: z.number(),
|
||||
});
|
||||
|
||||
const scoreGetNicknameValidator = z.object({
|
||||
nickname: z.string(),
|
||||
});
|
||||
|
||||
scoreRouter.post("/", async (req, res) => {
|
||||
try {
|
||||
const data = scorePostValidator.parse(req.body);
|
||||
|
||||
const scores = await prisma.score.findMany({});
|
||||
scores.sort((a, b) => a.score + b.score);
|
||||
|
||||
let i = 0;
|
||||
for (const score of scores) {
|
||||
if (score.score < data.score) break;
|
||||
i++;
|
||||
}
|
||||
const newScore = await prisma.score.create({
|
||||
data: { ...data, position: i },
|
||||
});
|
||||
res.json(newScore);
|
||||
} catch (e) {
|
||||
res.send(e);
|
||||
}
|
||||
});
|
||||
|
||||
scoreRouter.get("/", async (req, res) => {
|
||||
try {
|
||||
const scores = await prisma.score.findMany({
|
||||
take: 5,
|
||||
orderBy: [{ score: "desc" }],
|
||||
});
|
||||
res.json(scores);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
res.send(e);
|
||||
}
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import express from "express";
|
||||
import cors from "cors";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { scoreRouter } from "./api/score";
|
||||
import "dotenv/config";
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(cors({ origin: "*" }));
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json());
|
||||
|
||||
function initRoutes() {
|
||||
app.get("/v1", (_, res) =>
|
||||
res.json({ message: "space-game-api", version: "1.0.0" })
|
||||
);
|
||||
app.use("/v1/score", scoreRouter);
|
||||
}
|
||||
|
||||
async function initServer() {
|
||||
initRoutes();
|
||||
|
||||
app.listen(process.env.API_PORT, () => {
|
||||
console.log(`Server listening on :${process.env.API_PORT}`);
|
||||
});
|
||||
}
|
||||
|
||||
initServer();
|
||||
Reference in New Issue
Block a user