Effect CommunityEC
Effect Community3y ago
17 replies
matias

Fire and forget long running process within an Effect

I have an endpoint that is triggered by a webhook. One requirement is to return a 200 early as possible

This endpoint is used to initiate a long running process that is wrapped in an Effect too.

How can I fire that processor effect and immediately return a response?

The entire endpoint is also an Effect

export const POST: RequestHandler = async ({ request }) => {
  const program = Effect.gen(function*($) {
    // Check Secret
    yield* $(verifySignature(request))
    const order = yield* $(getOrder(request))
    // Here it should return the response but trigger the job effect
    const { jobId } = order.meta.custom_data

    runTheJob(jobId) // --> THIS IS THE FIRE AND FORGET EFFECT

    return true // --> Immediate response
  })
  const res = await Effect.runPromiseExit(program)
  return Exit.match(res, {
    onFailure(error) {
      return new Response(JSON.stringify({ error: error._tag }), { status: 500 })
    },
    onSuccess(success) {
      return new Response(JSON.stringify({ success: true }), { status: 200 })
    }
  })

}

declare function runTheJob(jobId: number): Effect<never, StorageError | DbError | ParseError | UnknownError, Job>
Was this page helpful?