Skip to content

Latest commit

 

History

History

README.md

key-hierarchy

A tiny TypeScript library for managing key hierarchies. The perfect companion for TanStack Query.

Documentation

CI NPM Coverage MIT

Features

  • Centralized key management for TanStack Query
  • Collision-free by design
  • Declarative and intuitive API
  • Type-safe static and dynamic keys
  • Tiny at less than 1 kB gzip

Installation

pnpm add key-hierarchy

Usage

This library provides a declarative API for defining key hierarchies. Key hierarchies can contain both static and dynamic segments, with dynamic segments being defined through dynamic and its generic parameter.

This approach and API ensure type-safety and collision-free key management. With this centralized declaration of keys, no key collisions can occur, and all keys are guaranteed to be unique. As such, it is ideal for managing TanStack Query queryKeys in large applications with multiple developers.

import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    getAll: true,
    create: true,
    byId: dynamic<number>().extend({
      get: true,
      update: true,
      delete: true,
    }),
  },
  posts: {
    byUserId: dynamic<number>(),
  },
}))

// Static keys
const getAllUsersKey = keys.users.getAll // readonly ['users', 'getAll']

// Dynamic keys with continued hierarchy
const updateUserKey = keys.users.byId(42).update // readonly ['users', ['byId', number], 'update']

// Partial keys with `__key`
const userByIdKey = keys.users.byId(42).__key // readonly ['users', ['byId', number]]

// Dynamic keys as terminal segment
const postsByUserIdKey = keys.posts.byUserId(42) // readonly ['posts', ['byUserId', number]]

Modularization

Should key hierarchy definitions grow too big to manage them within a single file, defineKeyHierarchyModule can be used to create modular key hierarchies. Defining modules this way retains type inference and ensures that keys are still unique when accessed from the root hierarchy.

// user-keys.ts
import { defineKeyHierarchyModule } from 'key-hierarchy'

export const userKeyModule = defineKeyHierarchyModule((dynamic) => ({
  getAll: true,
  create: true,
  byId: dynamic<number>().extend({
    get: true,
    update: true,
    delete: true,
  }),
}))

// post-keys.ts
import { defineKeyHierarchyModule } from 'key-hierarchy'

export const postKeyModule = defineKeyHierarchyModule((dynamic) => ({
  byIdUserId: dynamic<number>(),
}))

// keys.ts
import { defineKeyHierarchy } from 'key-hierarchy'

export const keys = defineKeyHierarchy({
  users: userKeyModule,
  posts: postKeyModule,
  config: true,
})

Options

The following options can be configured through the optional second parameter of defineKeyHierarchy. All options are optional with default values as described below.

freeze: boolean

Defaults to false.

If set to true, the generated keys will be frozen, preventing any modifications. This ensures immutability at runtime in your key hierarchy.

  • The return type of defineKeyHierarchy already prevents modification in TypeScript, even with freeze: false.
  • Object.freeze() will be called on the generated keys and all nested objects or arrays.
  • structuredClone will be used to create a deep copy of any key arguments before freezing them to ensure the original arguments remain unchanged.
import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy(
  (dynamic) => ({
    posts: {
      create: true,
      byUser: dynamic<{ id: number }>(),
    },
  }),
  { freeze: true },
)

// Throws with `freeze: true`
keys.posts.create.push('newSegment')

// Prevents modifications with `freeze: true`
keys.posts.create = ['newSegment']

// Prevents modification of arguments
const postsByUserKey = keys.posts.byUser({ id: 42 }) // readonly ['posts', ['byUser', DeepReadonly<{ id: number }>]]
// Throws with `freeze: true`
postsByUserKey[1][1].id = 7

method: 'proxy' | 'precompute'

Defaults to 'proxy'.

By default, the key hierarchy is created dynamically with Proxy objects. If this is not suitable, the method: 'precompute' option can be used to generate the keys at build time instead of runtime. This can improve performance in scenarios where the key hierarchy is large or complex, at the cost of a more extensive upfront computation.

TanStack Query Integration

This library works seamlessly with TanStack Query. Below are examples for React and Vue.

@tanstack/react-query

import { useQuery } from '@tanstack/react-query'
import { defineKeyHierarchy } from 'key-hierarchy'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    byId: dynamic<number>().extend({
      get: true,
    }),
  },
}))

export function useUserByIdQuery(userId: number) {
  return useQuery({
    queryKey: keys.users.byId(userId).get,
    queryFn: () => fetchUserById(userId),
  })
}

@tanstack/vue-query

Important: When using defineKeyHierarchy with @tanstack/vue-query, the freeze option may not be true if query key arguments are reactive.

import { useQuery } from '@tanstack/vue-query'
import { defineKeyHierarchy } from 'key-hierarchy'
import { MaybeRefOrGetter, toValue } from 'vue'

const keys = defineKeyHierarchy((dynamic) => ({
  users: {
    byId: dynamic<MaybeRefOrGetter<number>>().extend({
      get: true,
    }),
  },
}))

export function useUserByIdQuery(userId: MaybeRefOrGetter<number>) {
  return useQuery({
    queryKey: keys.users.byId(userId).get,
    queryFn: () => fetchUserById(toValue(userId)),
  })
}

Development

# install dependencies
$ pnpm install

# build for production
$ pnpm build

# lint project files
$ pnpm lint

# run tests
$ pnpm test

License

MIT - Copyright © Jan Müller