kwhitley / itty-router

A little router.
MIT License
1.78k stars 78 forks source link

Deno compatibility #80

Closed max-lt closed 2 years ago

max-lt commented 2 years ago

Hello, I loved using itty-router with Cloudflare workers, I'd like to make it work with Deno/Deno Deploy workers too; there is almost no changes to apply as it already works with it (see below)

// import { Router } from 'https://raw.githubusercontent.com/kwhitley/itty-router/master/src/itty-router.js';

import { Router } from './itty-router.js';

const router = Router();
router.get('/todos', () => new Response('Todos Index!'));
router.get('/todos/:id', ({ params }) => new Response(`Todo #${params.id}`));
router.all('*', () => new Response('Not Found.', { status: 404 }));

const server = Deno.listen({ port: 8080 });

for await (const conn of server) {
  const httpConn = Deno.serveHttp(conn);
  for await (const requestEvent of httpConn) {
    requestEvent.respondWith(router.handle(requestEvent.request));
  }
}

To only probem is about the module export, "module" is not defined in the deno runtime as the module system differs a bit, I removed the module.exports = { Router } (last line) and set the first line as follows :

export const Router = ({ base = '', routes = [] } = {}) => ({

It works like a charm as is. I don't know what this change would imply for the package but it should be ok as webpack can import such modules.

kwhitley commented 2 years ago

Hey @max-lt! Def appreciate the suggestion, and you're not alone (unfortunately). I think the change you suggest would be a break for people using standard require (CommonJS modules without a bundler), so the solution seems to be a hybrid module (one export for CommonJS, one for ES modules)... I'm about to be out on a climb for a few weeks, so I'll have to tackle this once I return mid-January!

kwhitley commented 2 years ago

Should be considered closed with upcoming release...