triggerdotdev / trigger.dev

Trigger.dev is the open source background jobs platform for TypeScript.

Home Page:https://trigger.dev/changelog

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: runTaskSuperjson

rechenberger opened this issue · comments

Is your feature request related to a problem? Please describe.

When running custom task with io.runTask the return value of the callback is piped through JSON.parse(JSON.stringify(value)). I understand that this is necessary to serialize the value for caching. In Typescript this is also reflected by doing JSON<T> with the return-type.

For me, this was cumbersome as I wanted to pass object with for example Dates and DX would fall apart.

Describe the solution you'd like to see

I created the following function to serialize the value with superjson. Superjson is similar to JSON.stringify and JSON.parse but allow for dates etc to survive.
For me and my team this function solves the Issue, but maybe there is way for this to end up directly in the @trigger.dev/sdk:

import { IO, RunTaskOptions } from '@trigger.dev/sdk'
import superjson from 'superjson'

type ServerTask = Parameters<Parameters<IO['runTask']>[1]>[0]

export const runTaskSuperjson = async <T>(
  io: IO,
  cacheKey: string,
  callback: (task: ServerTask, io: IO) => Promise<T>,
  options?: RunTaskOptions,
) => {
  const encodedResponse = await io.runTask(
    cacheKey,
    async (task, io) => {
      const response = await callback(task, io)
      const encoded = superjson.stringify(response)
      return encoded
    },
    options,
  )
  const response = superjson.parse<T>(encodedResponse)
  return response
}

Describe alternate solutions

Alternatively this little helper function could be hinted at in the docs.

Additional information

No response