apps/api/src/app.ts (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
import cors from "@elysia/cors";
import openapi from "@elysia/openapi";
import serverTiming from "@elysia/server-timing";
import config from "@stealth-developers/config";
import { getUser } from "@stealth-developers/db";
import { Elysia, t } from "elysia";
import { join } from "node:path";
import { authPlugin } from "./lib/auth";
import { getLinkedActors } from "./lib/db";
import { sanitiseActors, sanitiseUser } from "./lib/sanitise";
import { ActorWithGuildSchema, ErrorSchema, UserSchema } from "./lib/schemas";
import * as routes from "./routes";
export const app = new Elysia()
.onError(({ error, set, request }) => {
set.status = 500;
console.error(request.url, error);
if (error instanceof Error) return { message: error.message ?? "Internal Server Error" };
return { message: "Unknown Error" };
})
.use(openapi())
.use(cors())
.use(authPlugin)
.use(serverTiming())
.use(routes.authRoutes)
.group("/api", (app) =>
app
.get("/health", () => "ok")
.resolve(({ session, status }) => {
if (!session) return status(401, { message: "unauthorized" });
return { session };
})
.get(
"/me",
// @ts-expect-error watever
async ({ session }) => {
const [user, actors] = await Promise.all([
getUser(session.userId),
getLinkedActors(session.userId),
]);
return {
user: user ? sanitiseUser(user) : null,
actors: sanitiseActors(actors, false),
};
},
{
response: {
200: t.Object({
user: t.Nullable(UserSchema),
actors: t.Array(ActorWithGuildSchema),
}),
401: ErrorSchema,
500: ErrorSchema,
},
tags: ["auth"],
},
)
.use(routes.guildRoutes),
)
.get("*", async ({ path, set }) => {
const isExcluded =
path === "/api" || path.startsWith("/api/") || path === "/auth" || path.startsWith("/auth/");
if (isExcluded) {
set.status = 404;
return { message: "Not Found" };
}
if (path.includes("..")) {
set.status = 400;
return { message: "Bad Request" };
}
if (path !== "/") {
const staticFile = Bun.file(join(config.api.publicDir, path));
if (await staticFile.exists()) {
if (path.startsWith("/assets/")) {
set.headers["cache-control"] = "public, max-age=31536000, immutable";
}
return staticFile;
}
}
set.headers["cache-control"] = "no-store, no-cache, must-revalidate, proxy-revalidate";
return Bun.file(join(config.api.publicDir, "index.html"));
});
export type App = typeof app;
export type {
ErrorResponse,
GuildAccess,
SanitisedActor,
SanitisedActorWithGuild,
SanitisedGuild,
SanitisedTicket,
SanitisedTicketAttachment,
SanitisedTicketComment,
SanitisedTicketMessage,
SanitisedTicketParticipant,
SanitisedUser,
OverallStats,
LeaderboardEntry,
LeaderboardResponse,
} from "./lib/schemas";
|