Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: runTaskSuperjson #889

Open
rechenberger opened this issue Feb 8, 2024 · 0 comments
Open

feat: runTaskSuperjson #889

rechenberger opened this issue Feb 8, 2024 · 0 comments

Comments

@rechenberger
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant