Good Practices
Svelte Query
The @tanstack/svelte-query package offers a powerful asynchronous state management for your API calls in Svelte.
We recommend using it in all of your API calls.
Good Practices
The @tanstack/svelte-query package offers a powerful asynchronous state management for your API calls in Svelte.
We recommend using it in all of your API calls.
import { type PostsInterface } from '$lib/models/posts';
import { createQuery, Query, type QueryObserverOptions } from '@tanstack/svelte-query';
import { configureService } from '../../boot';
import { ServiceAbstract } from '@tanglemedia/svelte-starter-core';
class Posts extends ServiceAbstract {}
export type PostsQuery = Query<PostsInterface>;
type CreateOpt = {
enabled?: QueryObserverOptions['enabled'];
};
const postsServiceClient = configureService<PostsInterface>(Posts, {
path: 'post',
transform: (data) => data,
adapterKey: 'directus-client'
});
export default postsServiceClient;
export const findPostsKey = (query: PostsQuery) => ['post', query];
export const findPosts = (query: PostsQuery, createOpt: CreateOpt = {}) =>
createQuery({
queryKey: findPostsKey(query),
queryFn: async () => postsServiceClient.find(query).then((res) => res.data),
...createOpt
});
export const totalPostsKey = ({ filter, search }: PostsQuery) => ['total', filter, search, 'post'];
export const totalPosts = (query: PostsQuery, createOpt: CreateOpt = {}) =>
createQuery({
queryKey: totalPostsKey(query),
queryFn: async () => postsServiceClient.aggregate(query).then((res) => res.data),
select: (data) => (data && data.length ? Number(data[0].count.id) : 0),
...createOpt
});