Skip to content

Commit

Permalink
Better types for scheduled handler
Browse files Browse the repository at this point in the history
  • Loading branch information
rmarscher committed Feb 1, 2024
1 parent 1586e49 commit bc69bae
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 21 deletions.
18 changes: 18 additions & 0 deletions packages/api/src/scheduled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { match } from 'ts-pattern'
import { createContext } from './context'
import { Bindings } from './worker'

const scheduled: ExportedHandlerScheduledHandler<Bindings> = async (event, env, _) => {
console.log('Running cron', event.cron)
const ctx = await createContext(env)
await match({ event, ctx })
.with({ event: { cron: '15 2 0 * *' } }, async ({ ctx }) => {
await ctx.auth.deleteExpiredSessions()
console.log('Deleted expired sessions')
})
.otherwise(async () => {
console.log('Unhandled cron event', event)
})
}

export default scheduled
22 changes: 2 additions & 20 deletions packages/api/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { appRouter } from '@t4/api/src/router'
import { cors } from 'hono/cors'
import { createContext } from '@t4/api/src/context'
import { trpcServer } from '@hono/trpc-server'
import { match } from 'ts-pattern'
import scheduled from './scheduled'

export type Bindings = Env & {
JWT_VERIFICATION_KEY: string
Expand Down Expand Up @@ -58,25 +58,7 @@ app.use('/trpc/*', async (c, next) => {
})(c, next)
})

// https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/#syntax
interface ScheduledEvent {
cron: string // The value of the Cron Trigger that started the ScheduledEvent
type: 'scheduled'
scheduledTime: number // milliseconds since epoch
}

export default {
...app,
async scheduled(event: ScheduledEvent, env: Bindings) {
const ctx = await createContext(env)
console.log('Running cron', event.cron)
await match({ event, ctx })
.with({ event: { cron: '15 2 0 * *' } }, async ({ ctx }) => {
await ctx.auth.deleteExpiredSessions()
console.log('Deleted expired sessions')
})
.otherwise(async () => {
console.log('Unhandled cron event', event)
})
},
scheduled,
}
2 changes: 1 addition & 1 deletion packages/api/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ migrations_dir = "migrations"
# - At 11:59PM on the last weekday of the month
# crons = [ "*/3 * * * *", "0 15 1 * *", "59 23 LW * *" ]
# For now, we're using "15 2 0 * *" to delete expired sessions from the database weekly
# Test locally with "http://localhost:3000/__scheduled?cron=15+2+0+*+*"
# Test locally with "http://localhost:8787/__scheduled?cron=15+2+0+*+*"
crons = [ "15 2 0 * *" ]


Expand Down

0 comments on commit bc69bae

Please sign in to comment.