150 lines
2.8 KiB
JavaScript
150 lines
2.8 KiB
JavaScript
import { join } from "path";
|
|
import { fileURLToPath } from "url";
|
|
import express from "express";
|
|
import RandExp from "randexp";
|
|
import { HTTPError } from "./HTTPError.js";
|
|
|
|
const { randexp } = RandExp;
|
|
|
|
const dirname = fileURLToPath(new URL(".", import.meta.url));
|
|
const app = express();
|
|
|
|
const apiKeys = [
|
|
"c4game"
|
|
];
|
|
|
|
const dataPath = "/api/data";
|
|
const parametrizedDataPath = "/api/data/:id";
|
|
|
|
/**
|
|
* The data provided by the api.
|
|
*
|
|
* @type {Record<string, unknown>}
|
|
*/
|
|
let data = {};
|
|
|
|
/**
|
|
* Creates a new guid.
|
|
*
|
|
* @returns {string}
|
|
* The newly created guid.
|
|
*/
|
|
function createGuid()
|
|
{
|
|
return randexp(/[0-9a-f]{8}(-[0-9a-f]{4}){4}[0-9a-f]{8}/);
|
|
}
|
|
|
|
app.use(express.static(join(dirname, "..", "..", "game", "lib", "static")));
|
|
app.use("/api", express.json());
|
|
|
|
app.use(
|
|
"/api",
|
|
(request, response, next) =>
|
|
{
|
|
const keyParam = "token";
|
|
|
|
if (keyParam in request.query)
|
|
{
|
|
let key = request.query[keyParam];
|
|
|
|
if (typeof key === "string" && apiKeys.includes(key))
|
|
{
|
|
next();
|
|
}
|
|
else
|
|
{
|
|
next(new HTTPError(401, "The specified API token is invalid"));
|
|
}
|
|
}
|
|
else
|
|
{
|
|
next(new HTTPError(401, "An API token is required"));
|
|
}
|
|
});
|
|
|
|
app.get(
|
|
parametrizedDataPath,
|
|
(request, response, next) =>
|
|
{
|
|
let id = request.params.id;
|
|
console.log(`Data ID \`${id}\` requested`);
|
|
|
|
if (id in data)
|
|
{
|
|
response.send(data[id]);
|
|
}
|
|
else
|
|
{
|
|
next();
|
|
}
|
|
});
|
|
|
|
app.post(
|
|
dataPath,
|
|
(request, response, next) =>
|
|
{
|
|
let id = createGuid();
|
|
data[id] = request.body;
|
|
response.send({ id });
|
|
});
|
|
|
|
app.put(
|
|
parametrizedDataPath,
|
|
(request, response, next) =>
|
|
{
|
|
let id = request.params.id;
|
|
|
|
if (id in data)
|
|
{
|
|
data[id] = request.body;
|
|
response.send(data[id]);
|
|
}
|
|
else
|
|
{
|
|
next();
|
|
}
|
|
});
|
|
|
|
app.delete(
|
|
parametrizedDataPath,
|
|
(request, response, next) =>
|
|
{
|
|
let id = request.params.id;
|
|
|
|
if (id in data)
|
|
{
|
|
delete data[id];
|
|
response.send();
|
|
response.status(204);
|
|
}
|
|
else
|
|
{
|
|
next();
|
|
}
|
|
});
|
|
|
|
app.use(
|
|
[
|
|
(error, request, response, next) =>
|
|
{
|
|
response.send(`${error}`);
|
|
response.status(error instanceof HTTPError ? error.status : 500);
|
|
}
|
|
]);
|
|
|
|
app.use(
|
|
"/api",
|
|
(request, response) =>
|
|
{
|
|
response.send({ error: "Not Found" });
|
|
response.status(404);
|
|
});
|
|
|
|
app.use(
|
|
(request, response) =>
|
|
{
|
|
response.send("Not Found");
|
|
response.status(404);
|
|
});
|
|
|
|
app.listen(1337);
|