0.11.7 β€’ Published 8 months ago

@query-key-gen/generator v0.11.7

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

Query key Generator

Generated for Vite

1. Installation

pnpm add @query-key-gen/generator

2. Setup

// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import QueryKeyGeneratorPlugin from '@query-key-gen/generator';

export default defineConfig({ plugins: [react(), QueryKeyGeneratorPlugin()] });

πŸ“˜ Query Key Generator – Configuration Guide

@query-key-gen/generator is a Vite plugin that automatically generates queryKey definitions by scanning your project files. You can customize the behavior of the plugin through its configuration options.


πŸ”§ Configuration Options

All options are optional. If not specified, default values will be used.

OptionTypeDefaultRequiredDescription
outputstring'./src/queryKeys.ts'❌Path to the output file where generated query keys will be written.
globalQueryKeyNamestring'globalQueryKeys'❌Name of the global query key object exported from the generated file.
separatorstring'-'❌Separator used when building query key strings. E.g., user-detail.
ignoreFilesstring[]['.d.ts', 'query-key-used-info.ts']❌List of file names or extensions to exclude from query key generation.
factoryPrefixstring''❌Prefix for generated factory function names (e.g., userQueryKey`).

⚠️ Caution: Using with query-key-used-generator

If you're using @query-key-gen/used-generator together with this plugin, make sure to exclude its output file to prevent circular analysis or duplication.

βœ… Example

QueryKeyGeneratorPlugin({
  // ./src/query-key-used-info.ts
  ignoreFiles: ['query-key-used-info.ts']
});

#### πŸ›  Example

```ts
// vite.config.ts

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import QueryKeyGeneratorPlugin from '@query-key-gen/generator';

export default defineConfig({
    plugins: [
        react(),
        QueryKeyGeneratorPlugin({
            output: './src/utils/queryKeys.ts',
            globalQueryKeyName: 'queryKeys',
            separator: '_',
            ignoreFiles: ['**/test/**', 'legacy.ts'],
            factoryPrefix: 'QueryKey'
        })
    ]
});

3 βš™οΈ How Query Keys Are Generated

When you use 'useQuery','useSuspenseQuery','useInfiniteQuery','useQueries', 'useSuspenseQueries' and provide a queryKey directly in your code, the plugin will statically analyze it and automatically generate a corresponding query key factory in your output file.

πŸ” Example: Source Code

import { useInfiniteQuery, useQueries, useQuery, useSuspenseQuery } from '@tanstack/react-query';

export function useUserQuery() {
    useQuery({
        queryKey: ['user']
    });
}
export function useUserByIdQuery(id: number) {
    useQuery({
        queryKey: ['user', id]
    });
}

export function useUserListQuery(paging: { page: number; size: 0 }) {
    useQuery({
        queryKey: ['user', 'list', paging]
    });
}

export function usePostAndPostByIdQuery(id: number) {
    useQueries({
        queries: [
            {
                queryKey: ['post'],
                queryFn: () => {
                    return Promise.resolve([]);
                }
            },
            {
                queryKey: ['post', id],
                queryFn: () => {
                    return Promise.resolve([]);
                }
            }
        ]
    });
}

export function useUserInfiniteQuery(paging: { page: number; size: 0 }) {
    useInfiniteQuery({
        queryKey: ['user', 'infinite', paging],
        queryFn: () => {
            return Promise.resolve([]);
        },
        initialPageParam: 0,
        getNextPageParam: (lastPage, pages) => {
            return lastPage.length > 0 ? pages.length + 1 : undefined;
        }
    });
}

export function useUserSuspenseQuery() {
    useSuspenseQuery({
        queryKey: ['user', 'suspense']
    });
}

/src/queryKeys.ts

const user = {
    def: ['user'],
    '{id}': (id: number) => ['user', id],
    'list-{paging}': (paging: { page: number; size: 0 }) => ['user', 'list', paging],
    'infinite-{paging}': (paging: { page: number; size: 0 }) => ['user', 'infinite', paging],
    suspense: ['user', 'suspense']
} as const;

const post = {
    def: ['post'],
    '{id}': (id: number) => ['post', id]
} as const;

export const globalQueryKeys = {
    user,
    post
} as const;

4. ♻️ Using globalQueryKeys with queryClient.invalidateQueries

Using globalQueryKeys with React Query’s queryClient.invalidateQueries() allows you to invalidate cache in a type-safe and typo-proof way using strongly typed query keys.


import { useQueryClient } from '@tanstack/react-query';
import { globalQueryKeys } from '@/queryKeys'; // generated file

const queryClient = useQueryClient();

queryClient.invalidateQueries({
    queryKey: globalQueryKeys.user.def
});
0.11.7

8 months ago

0.11.6

8 months ago

0.11.5

8 months ago

0.11.4

8 months ago

0.11.3

8 months ago

0.11.2

8 months ago

0.11.1

8 months ago

0.11.0

8 months ago

0.10.0

8 months ago

0.9.0

8 months ago

0.8.1

8 months ago

0.8.0

8 months ago

0.7.0

8 months ago

0.5.0

8 months ago

0.4.0

8 months ago

0.3.0

8 months ago

0.2.0

8 months ago

0.1.0

8 months ago

0.0.0

8 months ago