{"id":13673361,"url":"https://github.com/lau1944/bunrest","last_synced_at":"2025-04-04T14:09:18.487Z","repository":{"id":54466678,"uuid":"522107667","full_name":"lau1944/bunrest","owner":"lau1944","description":"An express-like API for bun server","archived":false,"fork":false,"pushed_at":"2024-05-01T03:12:28.000Z","size":126,"stargazers_count":300,"open_issues_count":5,"forks_count":31,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T13:11:11.625Z","etag":null,"topics":["bun","bunjs","express","http","javascript","nodejs","rest-api","server","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lau1944.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"patreon":"ruidot"}},"created_at":"2022-08-07T03:32:50.000Z","updated_at":"2025-03-22T00:19:31.000Z","dependencies_parsed_at":"2024-03-08T03:24:22.894Z","dependency_job_id":"45ba1810-c1fb-4294-9029-25561d5448be","html_url":"https://github.com/lau1944/bunrest","commit_stats":{"total_commits":73,"total_committers":4,"mean_commits":18.25,"dds":0.2191780821917808,"last_synced_commit":"ef68ef48c301b009fa60fc0cf421489af5039361"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lau1944%2Fbunrest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lau1944%2Fbunrest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lau1944%2Fbunrest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lau1944%2Fbunrest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lau1944","download_url":"https://codeload.github.com/lau1944/bunrest/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247190254,"owners_count":20898702,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bun","bunjs","express","http","javascript","nodejs","rest-api","server","typescript"],"created_at":"2024-08-02T10:00:38.533Z","updated_at":"2025-04-04T14:09:18.465Z","avatar_url":"https://github.com/lau1944.png","language":"TypeScript","funding_links":["https://patreon.com/ruidot"],"categories":["Extensions","TypeScript","Frameworks \u0026 Libraries"],"sub_categories":["Libraries"],"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://bun.sh\"\u003e\u003cimg src=\"https://img.icons8.com/external-victoruler-flat-victoruler/344/external-baozi-chinese-new-year-victoruler-flat-victoruler.png\" alt=\"Logo\" height=200\u003e\u003c/a\u003e\n  \u003cbr /\u003e\n\u003c/p\u003e\n\n# 🧄 bunrest\n\n[![NPM Version][npm-version-image]][npm-url]\n[![CodeFactor](https://www.codefactor.io/repository/github/lau1944/bunrest/badge/main)](https://www.codefactor.io/repository/github/lau1944/bunrest/overview/main)\n![NPM Downloads][npm-downloads-image]\n\n## What is bunrest  👀\n\n### bunrest is an ExpressJs-like API for [bun](https://github.com/oven-sh/bun) http server.\n\n## Features\n\n1. ⚡ BLAZING FAST. Bun is super fast...\n\n2.   0️⃣   dependencies, work seamlessly with Bun\n\n3.   0️⃣   learning curve. If you know ExpressJs, you can start a bun server.\n\n## Table of Contents\n\n- [Set up](#get-started)\n- [Usage](#usage)\n- [Router](#router)\n- [Middlewares](#middlewares)\n- [Error handling](#error-handling)\n- [Request and Response object](#request-and-response-object)\n- [Websocket](#websocket)\n\n\n### Get started\n\nTo download bun\n\n```shell\ncurl -fsSL https://bun.sh/install | bash\n```\n\nTo create a bun project \n\n```shell\nbun init\n```\n\nThis will create a blank bun project\n\nsee reference [here](https://github.com/oven-sh/bun#bun-create)\n\n### Server set up\n\nDownload the package\n\n```shell\nbun install bunrest\n```\n\n\n```js\nimport server from \"bunrest\";\nconst app = server();\n```\n\n### Usage \n\nAfter that, you can write http method just like on `express`\n\n```js\napp.get('/test', (req, res) =\u003e {\n  res.status(200).json({ message: req.query });\n});\n\napp.put('/test/:id', (req, res) =\u003e {\n  res.status(200).json({ message: req.params.id });\n});\n\napp.post('/test/:id/:name', (req, res) =\u003e {\n  res.status(200).json({ message: req.params });\n});\n```\n\n### Router\nThe same as above, we create a router by calling `server.Router()`\n\nAfter creation, we attach the router to server by calling `server.use(your_router_reference)`\n\n```js\n// add router\nconst router = app.router();\n\nrouter.get('/test', (req, res) =\u003e {\n  res.status(200).json({ message: 'Router succeed' });\n})\n\nrouter.post('/test', (req, res) =\u003e {\n  res.status(200).json({ message: 'Router succeed' });\n})\n\nrouter.put('/test', (req, res) =\u003e {\n  res.status(200).json({ message: 'Router succeed' });\n})\n\napp.use('/your_route_path', router);\n```\n\n### Middlewares\n\nWe have two ways to add middlewares\n\n1. `use` : Simply call `use` to add the middleware function.\n\n2. Add middleware at the middle of your request function parameters.\n\n```js\n// use\napp.use((req, res, next) =\u003e {\n  console.log(\"middlewares called\");\n  // to return result\n  res.status(500).send(\"server denied\");\n});\n\napp.use((req, res, next) =\u003e {\n  console.log(\"middlewares called\");\n  // to call next middlewares\n  next();\n})\n\n// or you can add the middlewares this way\napp.get('/user', \n    (req, res, next) =\u003e {\n      // here to handle middleware for path '/user'\n    },\n    (req, res) =\u003e {\n      res.status(200).send('Hello');\n    });\n```\n\n### Error handling\n\nTo 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.\n\n```js\napp.use((req, res, next, err) =\u003e {\n    res.status(500).send('Error happened');\n });\n\n```\n\nAt this time, if we throw an error on default path `/`\n\n```js\napp.get('/', (req, res) =\u003e {\n  throw new Error('Oops');\n})\n```\n\nIt will call the `error handler callback function` and return a `response`. \nBut 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](https://github.com/oven-sh/bun#error-handling)\n\n\n### Start the server, listen to port\n\n```js\napp.listen(3000, () =\u003e {\n  console.log('App is listening on port 3000');\n});\n```\n\n\u003cbr /\u003e\n\n### Request and Response object\n\nTo simulate the `ExpressJs` API, the default `request` and `response` object on `bunjs` is not ideal.\n\nOn `bunrest`, we create our own `request` and `response` object, here is the blueprint of these two objects.\n\n\nRequest interface\n\n```js\nexport interface BunRequest {\n  method: string;\n  request: Request;\n  path: string;\n  header?: { [key: string]: any };\n  params?: { [key: string]: any };\n  query?: { [key: string]: any };\n  body?: { [key: string]: any };\n  blob?: any;\n}\n```\n\nResponse interface\n```js\nexport interface BunResponse {\n    status(code: number): BunResponse;\n    option(option: ResponseInit): BunResponse;\n    statusText(text: string): BunResponse;\n    json(body: any): void;\n    send(body: any): void;\n    // nodejs way to set headers\n    setHeader(key: string, value: any);\n    // nodejs way to get headers\n    getHeader();this.options.headers;\n    headers(header: HeadersInit): BunResponse;\n    getResponse(): Response;\n    isReady(): boolean;turn !!this.response;\n}\n```\n\nThe `req` and `res` arguments inside every handler function is with the type of `BunRequest` and `BunResponse`.\n\nSo you can use it like on Express\n\n```js\nconst handler = (req, res) =\u003e {\n  const { name } = req.params;\n  const { id } = req.query;\n  res.setHeader('Content-Type', 'application/text');\n  res.status(200).send('No');\n}\n```\n\n# websocket\n\n\u003cbr\u003e To handle websocket request, just a few steps to do \u003c/br\u003e\n\n```js\napp.ws\u003c{str: string}\u003e((ws, msg) =\u003e {\n    // here to handle incoming message\n    ws.send(msg)\n    // get web socket data\n    console.log(ws.data)\n}, {\n    open: (ws) =\u003e {\n        console.log('Websocket is turned on')\n    }, close: (ws) =\u003e {\n        console.log('Websocket is closed')\n    }, drain: (ws) =\u003e {\n        console.log('Websocket is drained')\n    }\n},\n(req) =\u003e ({str: \"socket-data\"}))\n```\n\n\u003cbr\u003e To connect to your websocket server \u003c/br\u003e\n\n```js\nconst socket = new WebSocket(\"ws://localhost:3000\");\n            const msg = 'Hello world'\n            // message is received\n            socket.addEventListener(\"message\", event =\u003e {\n                console.log(event.data)\n            });\n\n            // socket opened\n            socket.addEventListener(\"open\", event =\u003e {\n                console.log('Open')\n                // here to send message\n                socket.send(msg)\n            });\n\n            // socket closed\n            socket.addEventListener(\"close\", event =\u003e {\n                console.log('Close')\n            });\n\n            // error handler\n            socket.addEventListener(\"error\", event =\u003e {\n                console.log('Error')\n            });\n```\n\n[npm-url]: https://www.npmjs.com/package/bunrest\n[npm-version-image]: https://badgen.net/npm/v/bunrest\n[npm-downloads-image]: https://badgen.net/npm/dm/bunrest\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flau1944%2Fbunrest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flau1944%2Fbunrest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flau1944%2Fbunrest/lists"}