0.0.9 • Published 7 months ago

@epimodev/bun-bricks v0.0.9

Weekly downloads
-
License
-
Repository
-
Last release
7 months ago

bun-bricks

What is bun-bricks?

bun-bricks is a toolkit for building bun applications.
it simplify the process of creating web server with utilities to create file system based routing API, static server, websocket server, and more.

Installation

bun install @epimodev/bun-bricks

Available utilities

src/fileSystemApiRouter.ts

This module contains functions helping to create file system based routing API.

How to use:
First you should create a folder containing API functions, for example src/api.
In this folder you can create a file for each API function. Each file should export a function with the following signature:

// src/api/test.ts
import { ApiHandler } from "@epimodev/bun-bricks/src";

// query, body, cookies, headers are parsed from request
// publish is a function to publish message to websocket clients
const handler: ApiHandler = ({ query, body, cookies, headers, publish }) => {
  return {
    body: {
      message: "Response from src/api/test.ts",
    },
    headers: {}, // you can set custom headers
    status: 200, // default status is 200 but you can set custom status
  };
};

export default handler;

Then you can create a router using createFileSystemApiRouter function.
This router can be use to create a request handler for your server.

import {
  createFileSystemApiRouter,
  createFileSystemApiRouterRequestHandler,
} from "@epimodev/bun-bricks/src";

const server = Bun.serve({
  port: 3000,
  async fetch(request) {
    // returns undefined if there isn't any file matching the request url
    const response = apiHandler(request);
    return response ?? new Response("Not found", { status: 404 });
  },
  websocket: {
    open(ws) {},
    message(ws, message) {},
    close(ws) {},
  },
});

const apiRouter = await createFileSystemApiRouter({
  dir: "src/api", // folder containing API functions
  pathnamePrefix: "/api", // path prefix to access API function from client
});
// Websocket functions is generated by createWebsocketHandlers function.
// More info below in src/websocket.ts section
// If you don't use websocket, you can replace websocketFunctions.publish with () => 0
// This function stays require to ensure people who use websocket don't forget this param
const apiHandler = createFileSystemApiRouterRequestHandler(apiRouter, websocketFunctions.publish);

src/apiRouter.ts

This module contains functions helping to create API routing.

How to use:
You can create a router using createApiRouter function like this.

import { createApiRouter, createApiRouterRequestHandler } from "@epimodev/bun-bricks/src";

const apiRouter = createApiRouter({
  "/hello": {
    GET: () => ({
      body: {
        message: "Hello world!",
      },
    }),
    POST: ({ body }) => ({
      body: {
        message: "Hello world!",
        input: body,
      },
    }),
  },
  "/hello/:message": {
    GET: ({ params }) => ({
      body: {
        message: `Hello ${params.message}!`,
        input: params,
      },
    }),
  },
});

// Websocket functions is generated by createWebsocketHandlers function.
// More info below in src/websocket.ts section
// If you don't use websocket, you can replace websocketFunctions.publish with () => 0
// This function stays require to ensure people who use websocket don't forget this param
const apiHandler = createApiRouterRequestHandler(apiRouter, websocketFunctions.publish);

src/staticFiles.ts

This module contains a request handler for serving static files.
How to use:

import { handleStaticFiles } from "@epimodev/bun-bricks/src";

const server = Bun.serve({
  port: 3000,
  async fetch(request) {
    // returns response with file content if file exists
    // returns undefined if file doesn't exist
    const response = handleStaticFiles({ dir: "src/static" })(request);
    return response ?? new Response("Not found", { status: 404 });
  },
  websocket: {
    open(ws) {},
    message(ws, message) {},
    close(ws) {},
  },
});

src/websocket.ts

This module contains utilities to setup websocket with channels easily.
How to use:

import { createWebsocketHandlers } from "@epimodev/bun-bricks/src";

const server = Bun.serve({
  port: 3000,
  async fetch(request) {
    // return connected result if request.url matches connectPathname
    // return number of connection by channel if request.url matches `${connectPathname}/count`
    // otherwise returns undefined
    const response = websocketFunctions.handleRequest(request);
    return response ?? new Response("Not found", { status: 404 });
  },
  websocket: {
    open(ws) {
      // @ts-expect-error - `ws` data type is ensured by createWebsocketHandlers
      websocketFunctions.open(ws);
    },
    message(ws, message) {},
    close(ws) {
      // @ts-expect-error - `ws` data type is ensured by createWebsocketHandlers
      websocketFunctions.close(ws);
    },
  },
});

const websocketFunctions = createWebsocketHandlers({
  connectPathname: "/ws", // makes the websocket server listen to /ws path
  server,
});

// you can publish message to a channel using websocketFunctions.publish(channelName, message)

src/requestHandler.ts

If you want an API able to handle both static files and API functions, you can use combineHandlers function.
It will return a response from the first handler matching the request.

import {
  combineHandlers,
  createApiRouterRequestHandler,
  createFileSystemApiRouter,
  handleStaticFiles,
} from "@epimodev/bun-bricks/src";

const server = Bun.serve({
  port: 3000,
  async fetch(request) {
    // returns undefined if all handlers return undefined
    const response = handleRequest(request);
    return response ?? new Response("Not found", { status: 404 });
  },
  websocket: {
    open(ws) {},
    message(ws, message) {},
    close(ws) {},
  },
});

const apiRouter = await createFileSystemApiRouter({
  dir: "src/api",
  pathnamePrefix: "/api",
});
const handleRequest = combineHandlers(
  createApiRouterRequestHandler(apiRouter, () => 0),
  handleStaticFiles({ dir: "src/static" }),
);
0.0.9

7 months ago

0.0.8

7 months ago

0.0.7

7 months ago

0.0.6

7 months ago

0.0.5

7 months ago

0.0.4

7 months ago

0.0.3

7 months ago

0.0.2

7 months ago

0.0.1

7 months ago