kwhitley / itty-router

A little router.
MIT License
1.7k stars 77 forks source link

DRAFT: "AutoRouter" to reduce router initialization boilerplate #195

Closed kwhitley closed 3 months ago

kwhitley commented 7 months ago

Description

Adds flow(router: Router, options?: FlowOptions): Response to reduce boilerplate. This function makes the following assumptions (with override controls):

// BEFORE/WITHOUT FLOW
import { Router, json, error } from 'itty-router'

const router = Router()

router
  .get('/my-items', () => [1, 2, 3])
  .get('*', () => error(404))

export default {
  fetch: (...args) => router
                        .handle(...args)
                        .then(json)
                        .catch(error)
}
// AFTER/WITH FLOW
import { Router, flow } from 'itty-router'

const router = Router()

router.get('/my-items', () => [1, 2, 3])

export default {
  fetch: flow(router)
}

// or even

export default flow(router)
// WITH FLOW, OVERRIDES (including CORS)
import { Router, flow, error } from 'itty-router'

const router = Router()

router.get('/my-items', () => [1, 2, 3])

export default {
  fetch: flow(router, {
    cors: true,
    notFound: (req) => error(404, `The path "${req.url}" was not found.`),
  })
}

API (options)

Option Name Default Valid Choices
cors false false (off/ignore), true (default createCors()), CorsOptions
format json false (off/ignore), Function<Response>
errors error false (off/ignore), Function<Response>
notFound () => error(404) false (off/ignore), Function<Response>

Type of Change (select one and follow subtasks)

kwhitley commented 6 months ago

Adding to the discussion here... flow has been shelved for an arguably better router approach. Notes to follow.

kwhitley commented 3 months ago

Killed in favor of #222