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

@bunlyfans/rest

v0.1.2

Published

Simple server for you to REST, powered by Bun

Downloads

6

Readme

@bunlyfans/rest

Bun Version Version Build Status Test Coverage

Use Bun so you can REST. 😴

  • 🐰 100% Bun
  • ⚡️ 100% TypeScript
  • 🪄 100% magic
  • 🛫 0 dependencies
  • 💩🚫 0 bullshit

Contribution appreciated! 🙏

If you have any ideas / thougts / feature requests or want to contribute - feel free to create an issue or pull request!

Usage

See example directory for more details.

bun add @bunlyfans/rest

Create folder directory:

- src/
  - routes/
    - users/
      - [id].routes.ts
  - index.ts

Add next content to index.ts:

import { Router, DebugMiddleware } from "@bundlyfans/rest";

const router = new Router({
  dir: "/routes/",
  debug: true, // to preview identified routes on app start/restart
});

router.register(new DebugMiddleware());

Bun.serve({
  fetch: router.handle,
  port: process.env.PORT || 3000,
});

Add next content to routes/users/[id].routes.ts:

import { JSON, Param } from "@bunlyfans/rest";

export const middlewares = [new MyCustomMiddleware()];

GET.middlewares = [new UserExistsMiddleware()];
// This function will handle `GET /users/[id]` request
export function GET(id: Param<number>) { 
  // ..
  return Response.json(user);
}

DELETE.middlewares = [new AllowFor([USER_ROLES.ADMIN])];
export async function DELETE(id: Param<number>, user: JSON<unknown>) {
  // ..
  return new Response('User deleted');
}

export async function POST(user: JSON<User>) {
  // ..
  return Response.json(user, { status: 201 });
}

Router

Main concept about router is that each entity is located in its own folder/file. Each folder can contain multiple files that will be used as endpoints. So File System path represents URL path.

Route handlers can be described only as Functions Declarations! So you can't use arrow functions or anonymous functions.

Usage of methods as names may be found as a bit weird, but it's done on purpose, so it will force you to split your routes according to REST principles.

If you want to create custom endpoint - create file /routes/users/[id]/reset-password.routes.ts and it will be available as /users/[id]/reset-password. Now create a handle with function in this file:

// Replace POST with GET, PUT, DELETE, etc. to use another method
export async function POST(id: Param<number>) { // Id will be automatically parsed
  // That is it! Just write your logic to reset password
}

Sometimes you may need index route, if folder for entity was already created and you do not want any params, then just use routes.ts filename. Note: In future such routes may become deprecated or renamed.

Supported argument sources

As you may noticed - arguments are parsed automatically by generic types. For now only fixed types are supported, but in future it will be possible to use custom types.

| Type | Description | | --- | --- | | arg1 JSON<T> | Body of request. Will be parsed to JSON. | | arg2 Param<T> | Parameter extracted from request. Will be parsed to specified type, but default - fallback to string. NOTE: arg2 is a name of the route param, so your path should look like /entity/[arg2].routes.ts or /entity/[arg2]/custom.routes.ts. | | arg3 Query<T> | Argument will extract arg3 from request query. |

If T is number, example Param<number> - it will be parsed as a number automatically.

If T is boolean, example Query<boolean> - it will be parsed as a number automatically.

Response

Just use Response.json(body) to return JSON object, or new Response('text'). See Bun documentation for more details.

Middleware

Create middleware by implementing PreMiddleware or PostMiddleware interface, or both.

export class DebugMiddleware implements PreMiddleware, PostMiddleware {
  preProcess(context: RequestContext): void | Promise<void> {
    // Context provides access to request, logger, matched route
  }

  postProcess(context: RequestContext, response: Response): void | Promise<void> | Response | Promise<Response> {
    // ...
    // You can modify or create new response, if nothing is returned - default response will be used
  }
}

Global

It will be applied to all routes in the app/router.

router.register(new DebugMiddleware());

Module

It will be applied to all methods in the router file from which it is exported.

export const middlewares = [new MyCustomMiddleware()];

Local

It will be applied to specific method in the router file.

DELETE.middlewares = [new AllowFor([USER_ROLES.ADMIN])];
export async function DELETE(id: Param<number>, user: JSON<unknown>) {