T
TanStack7mo ago
genetic-orange

Porting existing Api structure to queryOptions

Hi! I have an existing structure in my codebase that's been around for a few years and is used everywhere internally. It is automatically generated from the backend and has a call structure like Api.Settings.Foo.read({ fooId }). Behind the scenes, it is mapped to an endpoint like so:
export const read = (d: FooIdDto, signal?: AbortSignal) =>
performPost<SettingsFooDto, FooIdDto>('/frontend-api/settings/foo/read', d, signal);
export const read = (d: FooIdDto, signal?: AbortSignal) =>
performPost<SettingsFooDto, FooIdDto>('/frontend-api/settings/foo/read', d, signal);
Knowing these two informations, I often end up with boilerplate that simply maps the name to the query key:
const example = queryOptions({
queryKey: ['Settings', 'Foo', 'read', fooId ],
queryFn: () => Api.Settings.Foo.read({ fooId })
})
const example = queryOptions({
queryKey: ['Settings', 'Foo', 'read', fooId ],
queryFn: () => Api.Settings.Foo.read({ fooId })
})
Could I somehow create a helper function that creates consistent queryKey naming and ensures parameters are passed?
2 Replies
adverse-sapphire
adverse-sapphire7mo ago
I would generate the key from the request url so that a request towards /frontend-api/settings/foo/read becomes the key ['frontend-api', 'settings', 'foo', 'read', { params: d }] or something like that
genetic-orange
genetic-orangeOP7mo ago
Sounds like a plan! I'll give it a try tomorrow.

Did you find this page helpful?