@t3ned/channel
v1.4.2-beta
Published
Ergonomic, chaining-based Typescript framework for quick API development for Fastify
Downloads
15
Maintainers
Readme
Ergonomic, chaining-based Typescript framework for quick API development for Fastify
Installation
> pnpm add @t3ned/channel
Usage
// index.ts
import { Application } from "@t3ned/channel";
import fastify from "fastify";
const server = fastify();
const app = new Application(server)
.setRouteDirPath(__dirname, "api")
.setEnvFilePath(process.cwd(), ".env")
.setDevelopmentEnvName("DEVELOPMENT")
.setRoutePrefix("/api")
.setDefaultVersionPrefix("v")
.setDefaultVersion(1);
app.listen(3000, "0.0.0.0")
.then(() => console.log(`Listening on port ${app.port}`))
.catch((error) => console.error(error));
// api/example.ts
import { HttpStatus, ApiError, Get, env } from "@t3ned/channel";
import { z } from "zod";
const getExampleParamsSchema = z.object({
id: z.string().uuid(),
});
process.env.AUTHORIZATION = "EXAMPLE";
export const getExample = Get("/:id")
.version(1)
.status(HttpStatus.Found)
.params(getExampleParamsSchema)
.status(HttpStatus.Ok)
.preHandler((req, _reply, done) => {
const { authorization } = req.headers;
if (authorization !== env("AUTHORIZATION")) {
throw new ApiError() //
.setCode(0)
.setStatus(HttpStatus.Unauthorized)
.setMessage("Unauthorized");
}
return done();
})
.handler(({ parsed }) => {
return {
id: parsed.params.id,
};
});