Created
November 25, 2023 23:14
-
-
Save max/bccf4cbd1ea3e2840619f1492444383a to your computer and use it in GitHub Desktop.
elysia-example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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