Skip to content

Instantly share code, notes, and snippets.

@max
Created November 25, 2023 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max/bccf4cbd1ea3e2840619f1492444383a to your computer and use it in GitHub Desktop.
Save max/bccf4cbd1ea3e2840619f1492444383a to your computer and use it in GitHub Desktop.
elysia-example
import { Elysia, ErrorHandler, t } from "elysia";
import { logger } from "./lib/logger";
import bearer from "@elysiajs/bearer";
import config from "./lib/config";
import swagger from "@elysiajs/swagger";
import { OverlandSchema } from "./lib/overland";
class UnauthorizedError extends Error {
code = "UNAUTHORIZED";
status = 403;
constructor(message: string) {
super(message);
}
}
const handleError: ErrorHandler = ({ code, error }) => {
logger.error(error);
return {
code,
message: error.message,
};
};
const logRequest = (context: { [x: string]: any }) => {
const { request } = context;
logger.info(
`${request.method} ${request.url} - ${request.headers.get("user-agent")}`
);
};
const apiRouter = new Elysia().group("/api", (app) =>
app.use(swagger()).guard(
{
headers: t.Object({
authorization: t.String(),
}),
},
(app) =>
app
.use(bearer())
.on("beforeHandle", ({ bearer, set }) => {
if (bearer !== config.api.token) {
set.status = 403;
throw new UnauthorizedError("Invalid token");
}
})
.post("/locations", async ({ body }) => body, {
body: OverlandSchema,
})
)
);
export const app = new Elysia()
.onError(handleError)
.on("beforeHandle", logRequest)
.use(apiRouter)
.listen(process.env.PORT || 3000);
logger.info(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment