npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@epimodev/bun-bricks

v0.0.9

Published

## What is bun-bricks?

Downloads

12

Readme

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" }),
);