T
TanStack4mo ago
quickest-silver

define server function output type / validation?

How people doing that? Usually, when designing server side I prefer to decide id advance what types should be for what endpoints and then just implement the code according to that types. Doing it with createServerFn for now is like:
interface MyResponse {
id: string,
name: string | null,
posts: number
}

const $someServerFn = createServerFn().handler( async ({data}) => {
// do stuff...
const result: MyResponse = // ...
return response
})
interface MyResponse {
id: string,
name: string | null,
posts: number
}

const $someServerFn = createServerFn().handler( async ({data}) => {
// do stuff...
const result: MyResponse = // ...
return response
})
it is little cumbersome. Is there any place in generics where I could insert the desired output type? Or maybe like the input validation, validation of output?
1 Reply
plain-purple
plain-purple3mo ago
I am new to TanStack and TypeScript ( late to the party ) but this is what I have been doing in a project I am building.

import { createServerFn } from '@tanstack/react-start'
import type { TGlobal, TStrapiResponseSingle } from '@/types'
import { sdk } from '@/data/strapi-sdk'

const getGlobal = async () =>
sdk.single('global').find() as Promise<TStrapiResponseSingle<TGlobal>>

export const getGlobalData = createServerFn({
method: 'GET',
}).handler(async (): Promise<TStrapiResponseSingle<TGlobal>> => {
const response = await getGlobal()
console.log(response)
return response
})

import { createServerFn } from '@tanstack/react-start'
import type { TGlobal, TStrapiResponseSingle } from '@/types'
import { sdk } from '@/data/strapi-sdk'

const getGlobal = async () =>
sdk.single('global').find() as Promise<TStrapiResponseSingle<TGlobal>>

export const getGlobalData = createServerFn({
method: 'GET',
}).handler(async (): Promise<TStrapiResponseSingle<TGlobal>> => {
const response = await getGlobal()
console.log(response)
return response
})

Did you find this page helpful?