sstur / nbit

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers
65 stars 4 forks source link

Implement onRequest, onRouteMatch and allow transforming response #19

Open sstur opened 7 months ago

sstur commented 7 months ago

This implements a way to add a listener for incoming requests (or only requests that match a route) and modify the response object, e.g. add CORS headers.

import { createApplication, HttpError } from '@nbit/bun';

const { defineRoutes, attachRoutes } = createApplication({
  onRequest: (event) => {
    const request = event.request;
    // Check the request if you need to, then add a listener to modify the response.
    event.addListener('response', (response) => {
      response.headers.set('Access-Control-Allow-Methods', 'GET, HEAD, POST, OPTIONS');
      response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Accept');
      response.headers.set('Access-Control-Allow-Origin', 'https://example.com');
    });
  },
  getContext: (request) => ({ ... }),
});

const routes = defineRoutes((app) => [
  // ...
]);

Alternatively you can do this only if a route matches.

const { defineRoutes, attachRoutes } = createApplication({
  onRouteMatch: (event) => {
    const { request, route } = event;
    const { pattern, params } = route;
    // The `pattern` will be like "/foo/:bar"
    // The `params` will be like `{ bar: 'abc' }`
    event.addListener('response', (response) => {
      response.headers.set('Access-Control-Allow-Methods', 'GET, HEAD, POST, OPTIONS');
      response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Accept');
      response.headers.set('Access-Control-Allow-Origin', 'https://example.com');
    });
  },
  getContext: (request) => ({ ... }),
});

If it's useful, we could expose a helper like so:

import { createApplication, HttpError, enableCors } from '@nbit/bun';

const { defineRoutes, attachRoutes } = createApplication({
  ...enableCors(),
  getContext: (request) => ({ ... }),
});

TODO:

svnty commented 5 months ago

@sstur Any chance you could publish this?

sstur commented 5 months ago

Will do. I need to take one more pass at this to evaluate if the API is right and I need to see why the tests are failing. Will get on that as soon as possible.

svnty commented 5 months ago

Will do. I need to take one more pass at this to evaluate if the API is right and I need to see why the tests are failing. Will get on that as soon as possible.

I love you bro, you're the goat