bunjs-common
v1.1.0
Published
A utility library for implementing rest API with Bun
Readme
Rest Api Decorators with Bun.js.
Step 1 : Install the package
Step 2 : Create a Controller
import { Controller, Delete, Get, Post, Put } from "bunjs-common";
@Controller("cars")
export class CarsController {
@Get()
async getCars(): Promise<Response> {
const cars = [
{ id: 1, model: "Toyota" },
{ id: 2, model: "Ford" },
];
return Response.json(cars);
}
@Get("new")
async getCarsNew(): Promise<Response> {
const cars = [
{ id: 1, model: "Toyota" },
{ id: 2, model: "Ford" },
{ id: 3, model: "Mercedes" },
{ id: 4, model: "BMW" },
];
return Response.json(cars);
}
@Get(":id")
async getCarById(_req: Request, params: { id: string }): Promise<Response> {
const car = { id: params.id, model: "Mercedes" };
return Response.json(car);
}
@Post()
async createCar(req: Request): Promise<Response> {
const body = await req.json();
return new Response(`Created car with data: ${JSON.stringify(body)}`, {
status: 201,
});
}
@Put(":id")
async updateCar(req: Request, params: { id: string }): Promise<Response> {
const body = await req.json();
return new Response(
`Updated car ${params.id} with data: ${JSON.stringify(body)}`,
{
status: 201,
}
);
}
@Delete(":id")
async deleteCar(_req: Request, params: { id: string }): Promise<Response> {
return new Response(`Deleted car with ID ${params.id}`, { status: 200 });
}
}- Step 3 :
In your server.ts
const routes = createRoutes([CarsController]);
const server = serve({
port: 5555,
async fetch(req) {
const url = new URL(req.url);
const method = req.method;
for (const route of routes) {
if (route.method === method) {
const matched = route.matchFn(url.pathname);
if (matched) {
return await route.handler(
req,
matched.params as Record<string, string>
);}
}
}
return new Response("Not Found", { status: 404 });
},
});
console.log(Listening on http://localhost:${server.port});- Step 4 :
bun run server.ts