90 lines
2.2 KiB
TypeScript
90 lines
2.2 KiB
TypeScript
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
|
|
import {createBundle} from "./bundler.ts";
|
|
import {Context} from "https://deno.land/x/oak@v12.2.0/context.ts";
|
|
import {Ballot} from "./shared.ts";
|
|
|
|
const router = new Router();
|
|
|
|
const clientBundle = createBundle(
|
|
new URL("./client.ts", import.meta.url),
|
|
new URL("../import_map.json", import.meta.url),
|
|
false,
|
|
);
|
|
|
|
|
|
router.get("/", (context) => {
|
|
context.response.body = `
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>title</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css" rel="stylesheet">
|
|
</head>
|
|
<body>
|
|
<script type="module" src="client.js"></script>
|
|
</body>
|
|
</html>
|
|
`;
|
|
});
|
|
|
|
function getUserIndex(userId: string, ballotId: string, questionId: string){
|
|
return ["tatoo-vote",
|
|
"v1",
|
|
"results",
|
|
"user",
|
|
userId,
|
|
"ballot",
|
|
ballotId,
|
|
"question",
|
|
questionId]
|
|
}
|
|
|
|
async function persistBallots(userId: any, ballots: Ballot[]): Promise<void> {
|
|
const kv = await Deno.openKv();
|
|
for(const ballot of ballots){
|
|
for(const question of Object.keys(ballot.scores)){
|
|
const k = getUserIndex(userId, ballot.id, question);
|
|
const v = {value: ballot.scores[question]};
|
|
await kv.set(k, v);
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
router.post("/api/v1/vote/:userid", async (ctx: Context)=> {
|
|
const userId = ctx?.params?.userid??"";
|
|
if(!ctx.request.hasBody){
|
|
ctx.throw(415);
|
|
}
|
|
const body = await ctx.request.body().value;
|
|
const ballots = body as Ballot[];
|
|
await persistBallots(userId, ballots);
|
|
console.log(body);
|
|
ctx.response.body = userId;
|
|
|
|
});
|
|
|
|
router.get("/client.js", async (context): Promise<void> => {
|
|
context.response.body = await createBundle(
|
|
new URL("./client.ts", import.meta.url),
|
|
new URL("../import_map.json", import.meta.url),
|
|
false,
|
|
);
|
|
context.response.type = "application/javascript";
|
|
});
|
|
|
|
|
|
|
|
const app = new Application();
|
|
app.use(router.routes());
|
|
|
|
|
|
app.use((ctx) => {
|
|
ctx.response.body = "Hello World!";
|
|
});
|
|
|
|
await app.listen({ port: 3333 });
|
|
|
|
|