kwhitley / itty-router

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

Setting up cron trigger? #203

Closed osseonews closed 6 months ago

osseonews commented 9 months ago

Describe the Issue

how would you set up a route with itty router that can serve as a cron trigger route? Cron triggers use the scheduled handler per the docs (https://developers.cloudflare.com/workers/examples/multiple-cron-triggers/), but I'm not sure how to set this up in a classic itty router example, with other get and post requests.

Example Router Code

Given the basic itty router set up as per below, how do we add a cron trigger? Do we just create route using .scheduled? And then how does it return?

import {
  error,      // creates error responses
  json,       // creates JSON responses
  Router,     // the ~440 byte router itself
  withParams, // middleware: puts params directly on the Request
} from 'itty-router'
import { todos } from './external/todos'

// create a new Router
const router = Router()

router
  // add some middleware upstream on all routes
  .all('*', withParams)

  // GET list of todos
  .get('/todos', () => todos)

  // GET single todo, by ID
  .get(
    '/todos/:id',
    ({ id }) => todos.getById(id) || error(404, 'That todo was not found')
  )

  // 404 for everything else
  .all('*', () => error(404))

// Example: Cloudflare Worker module syntax
export default {
  fetch: (request, ...args) =>
    router
      .handle(request, ...args)
      .then(json)     // send as JSON
      .catch(error),  // catch errors
}

Expected Behavior

should be able to add a route to itty router that runs a cloudflare cron.

kwhitley commented 9 months ago

Hmmm... so, I've certainly shared a [single] cron with a Worker that contained an itty API:

export default {
  fetch: router.handle,
  scheduled: cronHandler,
}

But using itty to route multiple crons may be tricky, due to the characters used in cron syntax...

kwhitley commented 6 months ago

So to add on to what was show above, any of the routers in the v5.x release can accept pass-through options, or even just allow themselves to be modified after instantiation. With this in mind, you can export the routers directly, including a scheduled event.

import { AutoRouter } from 'itty-router'

const router = AutoRouter({
  scheduled: (request) => { 
    // do something
  }
})

export default router

or...

import { AutoRouter } from 'itty-router'

const router = AutoRouter()

router.scheduled = (request) => {
  // do something
}

export default router

Hope this helps!