GithubHelp home page GithubHelp logo

lau1944 / bunrest Goto Github PK

View Code? Open in Web Editor NEW
268.0 1.0 28.0 115 KB

An express-like API for bun server

License: MIT License

JavaScript 0.15% TypeScript 99.85%
bun express javascript http rest-api server nodejs typescript bunjs

bunrest's Introduction

Hi, I'm Jimmy

Welcome to my world 👨🏻‍💻

JImmy leo | Medium JImmy leo | Medium

I'm a full stack developer from China
Java 🧡   | Kotlin 💜   | Flutter 💙   | Spring 💚 | Nodejs 🤎

Top Langs

Lau1944's GitHub stats

Snake animation

bunrest's People

Contributors

davood-n avatar djfil avatar lau1944 avatar luismalhadas avatar m-grig avatar nielsvantslot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

bunrest's Issues

`undefined is not an object (evaluating 'tree.get')` when using `app.router()`

Source:

import server from 'bunrest'

const app = server()
const router = app.router()

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

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

Error:
undefined is not an object (evaluating 'tree.get')
λ() node_modules/bunrest/src/server/server.ts:132:21

      async fetch(req1: Request) {
        const req: BunRequest = await that.bunRequest(req1);
        const res = that.responseProxy();
        const tree: TrieTree<string, Handler> =
          that.requestMap[req.method.toLowerCase()];
        const leaf = tree.get(req.path);
        /*          ^ happened here    */

Stack trace:

  λ() node_modules/bunrest/src/server/server.ts:132:21

Info:

bun v0.2.2
macOS 13.2.0 (Apple Silicon)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15
Pathname: /

This works (no router):

import server from 'bunrest'

const app = server()

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

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

Simple server throws error from bunrest module

The following code

import server from `bunrest`
const app = server()
app.get(`/`, (req,res) => {
  res.status(200).json({message: `hello world`})
})
app.listen(8888, ()=>{
  console.log(`Listening on port 8888`)
})

triggers the following logs when the route is hit

(base) [dp@fedora bunrest]$ bun run server.js 
/
Listening on port 8888
235 |     searchParams.forEach((v, k) => {
236 |       newReq.query[k] = v;
237 |     });
238 | 
239 |     // append body
240 |     const body: { [key: string]: any } = await req.json();
                                                   ^
SyntaxError: Unexpected end of JSON input
      at /home/dp/dev/bun/bunrest/node_modules/bunrest/src/server/server.ts:240:47
      at bunRequest (/home/dp/dev/bun/bunrest/node_modules/bunrest/src/server/server.ts:222:27)
      at /home/dp/dev/bun/bunrest/node_modules/bunrest/src/server/server.ts:132:38
      at fetch (/home/dp/dev/bun/bunrest/node_modules/bunrest/src/server/server.ts:131:33)
GET - http://127.0.0.1:8888/ failed
^C
(base) [dp@fedora bunrest]$ 

Websocket server doesn't work

Bun version: 1.0.22
Bunrest Version: 1.3.7

Reproduce:

index.ts:

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

app.get("/", (req, res) => {
	res.send("Hello World!");
});

app.ws(
	(ws, msg) => {
		ws.send(msg);
	},
	{
		open: (ws) => {
			console.log("Websocket is turned on");
		},
		close: (ws) => {
			console.log("Websocket is closed");
		},
		drain: (ws) => {
			console.log("Websocket is drained");
		},
	}
);

app.listen(3000, () => {
	console.log("Server listening on port 3000");
});

client.ts

import WebSocket from "ws";

const url = "ws://localhost:3000";
const connection = new WebSocket(url);

connection.onopen = () => {
	connection.send("Hello!");
};

connection.onerror = (error) => {
	console.log(`WebSocket error: ${error}`);
};

connection.onmessage = (e) => {
	console.log(e.data);
};

connection.onclose = () => {
	console.log("WebSocket closed");
};

Are there any solutions to solve the CORS problem?

Hi, Developers.
Hope you are doing well.
I am developing Restful API using bunrest framework.
The problem I facing is CORS issue.
I tried to solve the issue using cors npm like in express.js

Here are some of my code snaps.

import { Server } from 'bunrest'
import cors from 'cors'

const app = new Server();
app.use(cors());

app.get('/api/endpoint', (req, res) => {
// handler here
)

The errors I got is like this:

if (Array.isArray(header)) {
149 | applyHeaders(header, res);
150 | } else if (header.key === 'Vary' && header.value) {
151 | vary(res, header.value);
152 | } else if (header.value) {
153 | res.setHeader(header.key, header.value);
^
TypeError: res.setHeader is not a function. (In 'res.setHeader(header.key, header.value)', 'res.setHeader' is undefined)
at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:153:10)
at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:149:10)
at applyHeaders (/home/legend/aib-bot/node_modules/cors/lib/index.js:149:10)
at cors (/home/legend/aib-bot/node_modules/cors/lib/index.js:187:6)
at /home/legend/aib-bot/node_modules/cors/lib/index.js:224:16
at /home/legend/aib-bot/node_modules/cors/lib/index.js:214:14
at /home/legend/aib-bot/node_modules/cors/lib/index.js:219:12
at /home/legend/aib-bot/node_modules/cors/lib/index.js:199:8
at corsMiddleware (/home/legend/aib-bot/node_modules/cors/lib/index.js:204:6)
at /home/legend/aib-bot/node_modules/bunrest/src/utils/chain.ts:7:12
at /home/legend/aib-bot/node_modules/bunrest/src/utils/chain.ts:19:23
at fetch (/home/legend/aib-bot/node_modules/bunrest/src/server/server.ts:1

Please let me know how to fix the issue?

Kindly Regards

There is no path matches HEAD

132 | const res = that.responseProxy();
133 | const tree: TrieTree<string, Handler> =
134 | that.requestMap[req.method.toLowerCase()];
135 |
136 | if (!tree) {
137 | throw new Error(There is no path matches ${req.method});
^
error: There is no path matches HEAD
at /home/runner/test/node_modules/bunrest/src/server/server.ts:137:16

Add Standard Error Handling for undefined Routes

Hi, great work with this library!
When the user access a route not defined it throws an error from bun server.ts:

Cannot GET /something
λ() node_modules/bunrest/src/server/server.ts:210:16

        // append req route params
        req.params = leaf.routeParams;

        // fix (issue 4: unhandle route did not throw an error)
        if (!handlers || handlers.length === 0) {
          throw new Error(`Cannot ${req.method} ${req.path}`);
          /*   ^ happened here                               */

Stack trace:

  λ() node_modules/bunrest/src/server/server.ts:210:16

Info:

bun v1.0.3
linux #33~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Sep 7 10:33:52 UTC 2 (x64)
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36
Pathname: /something

While in epxressjs it gives a "nice" standard
Cannot GET /something with a 404

Most importantly, no error in the console and therefore logs.

Would be great if that could be a implemented.

Trailslashes removing

Hello,
Great work with this package, really appreciate your effort

when i am trying

router.get("/", (req, res) => ...)

and import router to sever

app.use("/user" ,router)

you have to send your request to "user/" and only "user" will not work


router.ts

private delegate(localPath: string, method: string, handlers: Handler[]) {
// Remove trailing slash if any
localPath = localPath.endsWith("/") ? localPath.slice(0, -1) : localPath

for (let i = 0; i < handlers.length; ++i) {
  const handler = handlers[i]
  if (i == handlers.length - 1) {
    this.submitToMap(method.toLowerCase(), localPath, handler)
    break
  }

trie-tree.ts

private dig(
node: Node<k, v>,
paths: string[],
params: { [key: string]: any }
): Node<k, v> | null {
// remove trailing slashs
paths = paths.filter((path, index) => path !== "" || index < 2)

if (paths.length === 0) {
  return node
}

and this will simulate the expressjs behavior

Catch 404 request.

Hi Developers,

I would like to know if there is a way to catch bad requests?

Let's say I have this code:

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

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

export default app;

Obviously calling localhost:3000/ gives me {"message":"API Root"}.

But if I try to reach a non-handled route (like localhost:3000/abcd), it gives me that:
Welcome to Bun! To get started, return a Response object.

Is there a way to catch bad requests as in express?

Like in this example: https://expressjs.com/en/starter/faq.html by adding a middleware function at the very bottom of the stack (below all other functions):

app.use((req, res, next) => {
  res.status(404).send("Sorry can't find that!")
})

Best Regards

Async middleware not working correctly

When using async middleware it starts the execution and jumps right back to the next one before it finishes.

import server from "bunrest";
const app = server();
const port = 3000;

const asyncMiddleware = async (req, res, next) => {
  console.log(new Date(), "start");
  await Bun.sleep(2000);
  console.log(new Date(), "end");
  res.status(429).send("Too many requests");
};

app.get("/user", asyncMiddleware, (req, res) => {
  console.log(new Date(), "user endpoint");
  res.status(200).json({ message: "ok" });
});

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

Output:

App is listening on port 3000
2023-11-09T18:54:44.563Z start
2023-11-09T18:54:44.563Z user endpoint
2023-11-09T18:54:46.563Z end
284 |         if (
285 |           typeof target[prop] === "function" &&
286 |           (prop === "json" || prop === "send") &&
287 |           target.isReady()
288 |         ) {
289 |           throw new Error("You cannot send response twice");
                    ^
error: You cannot send response twice
      at get (.../node_modules/bunrest/src/server/server.ts:289:16)

Expected output (processing should end when middleware sends 429):

App is listening on port 3000
2023-11-09T18:54:44.563Z start
2023-11-09T18:54:46.563Z end

Other Relevant Info:
Bun version: v1.0.2
bunrest version: v1.3.7
platform: ubuntu 20.04
node installed: yes
node version: v18.12.0

websocket fails

websocket api fails, I think it might need this to work properly again

async fetch(req1: Request) {

const success = server.upgrade(req1); if (success) { // Bun automatically returns a 101 Switching Protocols // if the upgrade succeeds return undefined; }

Incorrect type definitions and switched variable for errorHandler

In this example the middleware is "wrongly" classed as a Handler and not a MiddlewareFunc

(method) BunServer.use(middleware: Handler): void
app.use((req: BunRequest, res: BunResponse, next: ((err?: Error | undefined) => {}) | undefined) => {
  console.log("middlewares called");
  next!(); // Results in next() possible undefined
})

What it should classify it as src/server/request.ts

11 export type MiddlewareFunc = (
12   req: Request,
13   res: BunResponse,
14   next: (err?: Error) => {}
15 ) => void;

The errorhandler in src/server/server.ts also switches the err and next function around based on the type definitions from src/server/request.ts

4 export type Handler = (
5   req: BunRequest,
6   res: BunResponse,
7   next?: (err?: Error) => {},
8   err?: Error
9 ) => void | Promise<any>;

src/server/server.ts

229 that.errorHandlers.forEach((handler) => {
230   // * no request object pass to error handler
231   handler.apply(that, [null, res, err, next]);
232 });

Typescript

I got an error from typescript when i try to use it

Cannot find module 'bunrest'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?

bun version: 0.1.13

router * not working check page 404

I set * to match all routers that don't exist but it doesn't work

app.get('*', (req, res) => {
res.status(404).send({ url: ${req.originalUrl} not found });
});

Can't Have Hyphenated Route Names

I am running BunRest on Bun v0.1.13, and there seems to be an issue with the route names containing hyphens. All routes paths that start with the word before the hyphen and onwards on the hyphenated route will resolve to the hyphenated endpoint. Ex. if the '/api' route is requested, "hello world" with a status of 200 will be the response. The same for '/api-', '/api-e', '/api-en...', and '/api-endpoint-any-other-text-after_doesntneedtobehyphenated'.

Code to reproduce this error:

import server from "bunrest";

const app = server();
app.get('/api-endpoint', (request, response) => {
    response.status(200).json({message:"hello world!"});
});
app.get('/api', (request, response) => {
    response.status(500).json({message: "error!"});
});

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

console output:

[davidn000@linux]$ bun buntest.js 
App is listening on port 3000 

SyntaxError: Unexpected end of JSON input

Using the example code from the README.

/test or /login/test

/login/test
/login/test
/login/test
App is listening on port 3000
235 |     searchParams.forEach((v, k) => {
236 |       newReq.query[k] = v;
237 |     });
238 | 
239 |     // append body
240 |     const body: { [key: string]: any } = await req.json();
                                                   ^
SyntaxError: Unexpected end of JSON input

How to make it work with async functions or Promises?

I am using great.db as my database and all their functions return Promises. When I try to return some data from the database that got returned via a Promise, I get this message: Welcome to Bun! To get started, return a Response object.

I tried both async and Promises, here's the code:

// with Promises
router.get('/projects', (req, res) => {
    const data = Table.project.get('id', undefined, true).then(() => {
        res.status(200).json(data);
    });
});

// using async
router.get('/projects', async (req, res) => {
    const data = await Table.project.get('id', undefined, true);
    res.status(200).json(data);
});

Neither seems to return anything except the message mentioned earlier. How do I make this work with async fetching from database?

Testing is not working as expected

I am probably doing it wrong, but I need some help, because it's just the test that is not working...
The following test:

import { expect, test, beforeAll, afterAll, afterEach, beforeEach} from "bun:test";
import server from "bunrest";

const app = server();
let service;

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

afterAll(async () => {
    service.stop();
});

test("should respond OK for ping", async () => {
    try {
        const res = await fetch('http://localhost:3000/ping');
        expect(res.status).toBe(200);
        expect(await res.text()).toBe('OK')
    } catch (e) {
        throw e;
    } 
});

The index.ts:

import server from "bunrest";
import cors from "cors";
import router from "./src/core/Router.js";

const app = server();
const port = 3000;

// add router
//const router = app.router();
app.use('/', router);

app.use(cors());

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

For the route.ts:

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

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

router.get('/ping', (req, res) => {
    //console.log("[/ping] RECEIVED: ", req);
    res.status(200).send('OK');
});

These are the reduced versions.
Running bun test outputs:

Router.test.ts:
App is listening on port 3000
133 |         const res = that.responseProxy();
134 |         const tree: TrieTree<string, Handler> =
135 |           that.requestMap[req.method.toLowerCase()];
136 | 
137 |         if (!tree) {
138 |           throw new Error(`There is no path matches ${req.method}`);
                    ^
error: There is no path matches GET
      at /Users/luismal/Projects/Sia_AA/node_modules/bunrest/src/server/server.ts:138:16
GET - http://localhost:3000/ping failed
Database connection to  mongodb://localhost:27017/SIA  established.
20 |     console.log(result);
21 |     expect(result).toBe("OK");
22 |     */
23 |     try {
24 |         const res = await fetch('http://localhost:3000/ping');
25 |         expect(res.status).toBe(200);
            ^
error: expect(received).toBe(expected)

Expected: 200
Received: 500

      at /Users/luismal/Projects/Sia_AA/tests/Router.test.ts:25:8
✗ should respond OK for ping

dies on start + typescript errors

when i try using bunrest following the directions in the readme, the app seems to just skip over bunrest and terminates:

my code:

import server from 'bunrest'

const app = server()
const router = app.router()

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

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

console.log('hello!')

the result:

» bun run src/index.ts
hello!

i tried compiling the typescript to see if that would work and this happened:

12:51:58 AM » tsc src/**/*.ts
node_modules/bunrest/src/router/router.ts:10:8 - error TS1259: Module '"path"' can only be default-imported using the 'esModuleInterop' flag

10 import path from "path";
          ~~~~

  node_modules/@types/node/path.d.ts:178:5
    178     export = path;
            ~~~~~~~~~~~~~~
    This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

node_modules/bunrest/src/server/response.ts:21:34 - error TS2339: Property 'json' does not exist on type '{ new (body?: BodyInit, init?: ResponseInit): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number): Response; }'.

21         this.response = Response.json(body, this.options);
                                    ~~~~

node_modules/bunrest/src/server/server.ts:33:14 - error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.

33   static get instance() {
                ~~~~~~~~

node_modules/bunrest/src/server/server.ts:118:12 - error TS2304: Cannot find name 'Bun'.

118     return Bun.serve({
               ~~~


Found 4 errors in 3 files.

Errors  Files
     1  node_modules/bunrest/src/router/router.ts:10
     1  node_modules/bunrest/src/server/response.ts:21
     2  node_modules/bunrest/src/server/server.ts:33

Unexpected end of JSON input

`
SyntaxError
Unexpected end of JSON input
λ() node_modules/bunrest/src/server/server.ts:240:47

    searchParams.forEach((v, k) => {
      newReq.query[k] = v;
    });

    // append body
    const body: { [key: string]: any } = await req.json();
    /*                                        ^ happened here */

Stack trace:

  λ()          node_modules/bunrest/src/server/server.ts:240:47
  `bunRequest` node_modules/bunrest/src/server/server.ts:222:27
  λ()          node_modules/bunrest/src/server/server.ts:132:38
  `fetch`      node_modules/bunrest/src/server/server.ts:131:33

Info:

bun v1.0.0
wsl #1 SMP Fri Jan 27 02:56:13 UTC 2023 (x64)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.76
Pathname: /
Screenshot 2023-09-12 133329

`

Middleware not running on route with parameter

Issue

when running on localhost:5555/test/1 middleware does not run.

when registering middleware to a route which takes a parameter the middleware will be assigned directly to:
http://localhost:5555/test/:id

expected is that the middleware will run on
http://localhost:5555/test/1
http://localhost:5555/test/2
http://localhost:5555/test/3
and so on...

import server from 'bunrest';
const app = server();
let router = app.router();

router.get('/:id',
  (req, res, next) => {
    console.log('middleware running');
  }, (req, res) => {
    res.status(200).json({ message: 'middleware gets ignored' });
  }
);

// router.get('/',
//   (req, res, next) => {
//     console.log('middleware running');
//   }, (req, res) => {
//     res.status(200).json({ message: 'middleware will run' });
//   }
// );

app.use(`/test`, router);

app.listen(5555, () =>
    console.log(`Listening on port 5555!`),
);

Potential fix

It seems to work on my environment however this needs further testing.

src/server/server.ts:179
replace:

if (target.path === req.path) {
  middlewares.push(target);
  break;
}

with:

const targetPathSegments = target.path.split('/');
const reqPathSegments = req.path.split('/');

if (targetPathSegments.length === reqPathSegments.length) {
  const params = {};

  for (let i = 0; i < targetPathSegments.length; i++) {
    const targetSegment = targetPathSegments[i];
    const reqSegment = reqPathSegments[i];

    if (targetSegment.startsWith(':')) {
      // This is a parameter, extract its value
      const paramName = targetSegment.slice(1);
      params[paramName] = reqSegment;
    } else if (targetSegment !== reqSegment) {
      // Segments don't match
      break;
    }

    if (i === targetPathSegments.length - 1) {
      // Reached the end of the loop, paths match
      middlewares.push({ ...target, params });
    }
  }
}

Bun installation

I need to install bun binaries to use this package right?
Or simple package. Json file file with bun module will do the work?
I wan to take risk using this in production for one of mu very mvp

Cannot GET /

I don't have a get route defined at /, but I do have

app.use((req, res, next, err) => {
  res.status(404).send('Not found');
});

So why is the app throwing an error, is this intentional?

189 |         // fix (issue 4: unhandle route did not throw an error)
190 |         if (!handlers || handlers.length === 0) {
191 |           throw new Error(`Cannot ${req.method} ${req.path}`);
                    ^
error: Cannot GET /
      at /home/runner/test/node_modules/bunrest/src/server/server.ts:191:16

189 |         // fix (issue 4: unhandle route did not throw an error)
190 |         if (!handlers || handlers.length === 0) {
191 |           throw new Error(`Cannot ${req.method} ${req.path}`);
                    ^
error: Cannot GET /favicon.ico
      at /home/runner/test/node_modules/bunrest/src/server/server.ts:191:16

No redirect function on response

router.get('/', (req, res) => {
    return res.redirect('/wherever', 301)
})

Property 'redirect' does not exist on type 'BunResponse'.

Handlers Failing to Chain

Update 2 | Notes for Global Use

Global use seems to be failing for handlers that have a middleware with the following type: (req: BunRequest, res: BunResponse, next?: (err?: Error) => {}, err?: Error) => void | Promise<any> . Once I removed the err?: Error from my cors handler it was registering globally. I could then proceed to use it as follows:

app.use(cors());

Update 1 | Fix for Chaining

Got a solution for the chaining:

bunrest/src/server.ts

private openServer(...args): Server {
   // other code
  
   // middlewares hander
   if (that.middlewares.length !== 0) {
      const plainMid = that.middlewares.filter(mid => req.path.startsWith(mid.path) || mid.path === '*');

      // rest of code
   }
}

Slightly altering the plainMid variable makes all the difference. Now middlewares in route handlers chain such as:

app.get("/path", middleware1, middleware2, async (req, res) => {
   // code
});

Original Issue

So I was having issues with the Express cors package and began creating one that is fully compatible and typed with bunrest (ideally for release as a package down the road). That being said, my middlewares are not chaining. I have a custom auth middleware to handle API keys and what not which is crucial, however, my cors is only being hit when there's a preflight (I have to specifically add it to router.options). Here is what I have:

auth.ts
authRouter.post(
	"/logout",
	cors({
		allowedHeaders: ["X-API-KEY", "X-AUTH-TOKEN"],
		methods: ["GET", "POST", "PATCH"],
		origins: ["https://www.test.dev"],
	}),
	authMiddleware,
	async (req, res) => {
		try {
			await doSomething();

			res.status(200).json({ success: true });
		} catch (ex) {
			res.status(500).json({ success: false });
		}
	}
);

cors.ts

NOTE: this is a stripped down version

export default function cors(options?: CorsOptions) {

	const _isOrigin = (header: string): boolean => {
		if (Array.isArray(origins)) return origins.includes(header);
		else return true;
	};

	const middelware: Handler = (req, res, next?, err?) => {
				console.log("hit");

				// @ts-ignore
				const host = req.headers["host"];
				const isvalidOriginNoPreflight = _isOrigin(host);

				if (!isvalidOriginNoPreflight) {
					res.status(400).send("");
				}

				// @ts-ignore
				next();
		}
	};

	return middelware;
}

authMiddleware.ts
export const authMiddleware: Handler = (req, res, next?, err?) => {
	const isValid = validateStuff();

	if (!isValid) {
			res.status(401).json({
				message: "Access Denied",
			});
		} else {

			// @ts-ignore
			next();
		}
	} else {
		res.status(400).json({ message: "Invalid credentials provided." });
	}
};

I am sending my request from Postman localhost, so when I only include the cors middleware it rejects my request due to the host not being part of the origins. Equally, when I only include the authMiddleware it does what it should. However, when I chain them, only the last middleware works. So if it goes cors, then authMiddleware; only the auth middleware will run and vice versa.

Additionally, the global app.use(req, res, next?, err?) => {...} does not hit the cors (express or my custom one) middleware if I put it in there.

Other Relevant Info:
Bun version: v1.0.7
bunrest version: v1.3.6
platform: ubuntu 20.04 (docker image)
node installed: yes
node version: v18.18.2

Sessions?

I am trying to convert my app from express to bunrest. Right now, I use express-session for my sessions. But when I do req.session it says session isn't apart of bunret. So How do I handle sessions?

type issue

while trying :

app.get("/", (req, res) => {
const { id } = req.query;
res.send("hello world!")
})

i get Property "id" doesn't exist on type { [key: string]: any }

Raw request body?

Hi there, I was playing around with bunrest a bit for a weekend project and I've found myself in a situation where I need to access the raw request body. I'm not seeing anything immediately obvious in the docs, and trying to access things via req.request.body eventually end up with an error that Body is already used.

Any ideas?

Middlewares Activating for All Methods of a Route

I have a path that can be accessed via GET or POST, for differing reasons. I have an auth middleware on the GET handler, however, the middleware is also being applied to the POST handler. See the code below:

authRouter.post("", async (req, res) => {
   // stuff
   res.status(200).json({ data });
});

authRouter.get("", authMiddleware, async (req, res) => {
   // stuff
   res.status(200).json({ data });
});

app.use("/analytics", authRouter);

Other Relevant Info:
Bun version: v1.0.7
bunrest version: v1.3.6
platform: ubuntu 20.04 (docker image)
node installed: yes
node version: v18.18.2

Cant get custom response

New to this so probably missed something really obvious, no matter what i do i cant seem to get a custom response back when pusing put

app.put('/api/data', async (req, res) => {
  const { ComputerName, AgentVer, DateScanned, SummaryJSON } = req.body;

  // write a query to insert the data into the database
  const query = {
    text: 'INSERT INTO ICTSignal(ComputerName, AgentVer, DateCreated, SummaryJSON) VALUES($1, $2, $3, $4)',
    values: [ComputerName, AgentVer, DateScanned, JSON.stringify(SummaryJSON)],
  };

  // execute the query
  await client.query(query, (err) => {
    if (err) {
      console.log(err.stack);
      res.status(500).json({ message: 'Error in database operation' });
    } else {console.log(res.status)
      res.status(200).json({ message: 'Data inserted successfully' });
    }
  });
});

image

what am i doing wrong here

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.