• Stars
    star
    283
  • Rank 146,066 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An express-like API for bun server

Logo

🧄 bunrest

NPM Version CodeFactor NPM Downloads

What is bunrest 👀

bunrest is an ExpressJs-like API for bun http server.

Features

  1. BLAZING FAST. Bun is super fast...

  2. 0️⃣ dependencies, work seamlessly with Bun

  3. 0️⃣ learning curve. If you know ExpressJs, you can start a bun server.

Table of Contents

Get started

To download bun

curl -fsSL https://bun.sh/install | bash

To create a bun project

bun init

This will create a blank bun project

see reference here

Server set up

Download the package

bun install bunrest
import server from "bunrest";
const app = server();

Usage

After that, you can write http method just like on express

app.get('/test', (req, res) => {
  res.status(200).json({ message: req.query });
});

app.put('/test/:id', (req, res) => {
  res.status(200).json({ message: req.params.id });
});

app.post('/test/:id/:name', (req, res) => {
  res.status(200).json({ message: req.params });
});

Router

The same as above, we create a router by calling server.Router()

After creation, we attach the router to server by calling server.use(your_router_reference)

// add router
const router = app.router();

router.get('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

router.post('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

router.put('/test', (req, res) => {
  res.status(200).json({ message: 'Router succeed' });
})

app.use('/your_route_path', router);

Middlewares

We have two ways to add middlewares

  1. use : Simply call use to add the middleware function.

  2. Add middleware at the middle of your request function parameters.

// use
app.use((req, res, next) => {
  console.log("middlewares called");
  // to return result
  res.status(500).send("server denied");
});

app.use((req, res, next) => {
  console.log("middlewares called");
  // to call next middlewares
  next();
})

// or you can add the middlewares this way
app.get('/user', 
    (req, res, next) => {
      // here to handle middleware for path '/user'
    },
    (req, res) => {
      res.status(200).send('Hello');
    });

Error handling

To add a global handler, it's really similar to express but slightly different. The fourth argument is the error object, but I only get [native code] from error object, this might related to bun.

app.use((req, res, next, err) => {
    res.status(500).send('Error happened');
 });

At this time, if we throw an error on default path /

app.get('/', (req, res) => {
  throw new Error('Oops');
})

It will call the error handler callback function and return a response. But if we have not specified a response to return, a error page will be displayed on the browser on debug mode, check more on bun error handling

Start the server, listen to port

app.listen(3000, () => {
  console.log('App is listening on port 3000');
});

Request and Response object

To simulate the ExpressJs API, the default request and response object on bunjs is not ideal.

On bunrest, we create our own request and response object, here is the blueprint of these two objects.

Request interface

export interface BunRequest {
  method: string;
  request: Request;
  path: string;
  header?: { [key: string]: any };
  params?: { [key: string]: any };
  query?: { [key: string]: any };
  body?: { [key: string]: any };
  blob?: any;
}

Response interface

export interface BunResponse {
    status(code: number): BunResponse;
    option(option: ResponseInit): BunResponse;
    statusText(text: string): BunResponse;
    json(body: any): void;
    send(body: any): void;
    // nodejs way to set headers
    setHeader(key: string, value: any);
    // nodejs way to get headers
    getHeader();this.options.headers;
    headers(header: HeadersInit): BunResponse;
    getResponse(): Response;
    isReady(): boolean;turn !!this.response;
}

The req and res arguments inside every handler function is with the type of BunRequest and BunResponse.

So you can use it like on Express

const handler = (req, res) => {
  const { name } = req.params;
  const { id } = req.query;
  res.setHeader('Content-Type', 'application/text');
  res.status(200).send('No');
}

Next

Server rendering, websocket

More Repositories

1

shark

A Flutter server rendering framework
Dart
72
star
2

Zoom-Drag-Rotate-ImageView

Zoom, Drag & Rotate ImageView (可拉伸,托拉和旋转的imageview)
Java
15
star
3

just_audio_cache

Collection of extension function of just_audio package for auto-handle caching
Dart
11
star
4

Yolo-face-detection

Generate meme photos using machine learning - Yolo人脸识别(狗头overlay)
Python
7
star
5

moyu_app

摸鱼应用flutter小项目
Dart
7
star
6

snowow

A low code web service build on top of Spring
Java
6
star
7

chatgpt-spring-boot

A ChatGPT chatbot template in spring boot
Java
4
star
8

Biometric-Flutter

A new authentication flutter plugin with latest biometric library
Kotlin
3
star
9

flutter_in_app_billing

A Flutter plugin for google play in-app-billing
Kotlin
3
star
10

Load-balancer-in-java

Implementation of popular load balancing algorithms in Java
Java
2
star
11

github-web-scraper

A Github Page Web Scraper Rest Api Using Flask (Github网页爬虫)
Python
2
star
12

AppManager-Kotlin

App Manager - An Android App with clean architecture & Jetpack components (MVVM 软体架构,Jetpack套件)
Kotlin
2
star
13

sa_progress_bar

A simple progress bar controller
Dart
2
star
14

shark-server

A shark framework server sample
TypeScript
2
star
15

Image-Processing-Homework

Python Opencv
Python
1
star
16

Chinese-Android-Push-Service

简要概略国内Android厂商Push服务的相关信息
1
star
17

chatview

A ChatView Library for Android
Kotlin
1
star
18

idialer

A dialer android app with iOS style
Kotlin
1
star
19

ColorBlue_Control_Object

Using OpenCV2 detects blue color , control images position on screen (put the right color in the box !)
Python
1
star
20

intentparser

An easier way to pass objects between android activies
Kotlin
1
star