serialize.ts
Overview
serialize.ts provides a utility function serialize that processes a given cache key into a normalized string form along with its original arguments. This transformation facilitates consistent key management, particularly useful in caching or data-fetching scenarios where keys can be strings, arrays, or functions returning keys. The primary goal is to produce a stable, serialized key string that uniquely identifies a resource or request, along with the original key arguments passed, enabling downstream fetchers or cache mechanisms to operate reliably.
Detailed Documentation
Function: serialize
serialize(key: Key): [string, Arguments]
Description
Converts a key into a tuple [serializedKey, originalArgs].
If the
keyis a function, it attempts to invoke it to obtain the actual key. If invocation fails (e.g., dependencies not ready), it falls back to an empty string.The
argsreturned are the original key before serialization, which may be a string, an array of values, or empty.The
keyis then transformed into a stable hash string if it is an array or non-string value, or left as-is if it is already a string.If the key is falsy or an empty array, it returns an empty string for the serialized key.
This tuple is useful in caching or data fetching libraries where:
The serialized string acts as a cache key or identifier.
The original arguments are passed to the fetcher function.
Parameters
Name | Type | Description |
|---|---|---|
|
| The input key representing the resource/request. It can be: |
| ||
| ||
|
Key is imported from the project's type definitions and is generally a union type covering these possibilities.
Returns
Type | Description |
|---|---|
| A tuple where: |
| |
|
Usage Example
import { serialize } from './serialize'
// Using a string key
const [key1, args1] = serialize('user:123')
console.log(key1) // 'user:123'
console.log(args1) // 'user:123'
// Using an array key
const [key2, args2] = serialize(['user', 123, { active: true }])
console.log(key2) // a stable hash string like 'a1b2c3d4...' representing the array content
console.log(args2) // ['user', 123, { active: true }]
// Using a function that returns a key
const [key3, args3] = serialize(() => ['post', 42])
console.log(key3) // stable hash of ['post', 42]
console.log(args3) // ['post', 42]
// Using a function that throws
const [key4, args4] = serialize(() => { throw new Error('not ready') })
console.log(key4) // ''
console.log(args4) // ''
Implementation Details
The function first checks if the
keyis a function using the helperisFunctionfrom./shared. If so, it attempts to invoke it safely using atry-catchblock to avoid runtime errors when dependencies are not ready.The original
key(post-function evaluation) is stored inargs.The serialization step:
If the key is a string, it is used as is.
If the key is an array and not empty, it is passed to
stableHashfrom./hashto generate a consistent string hash.If the key is falsy or an empty array, it serializes to an empty string.
This approach ensures that complex keys (such as arrays containing objects or nested values) can be reliably converted to a unique string representation which can be used as a cache key or identifier.
Interaction with Other Parts of the System
./hash(stableHash): ThestableHashfunction generates a consistent hash string for complex keys (arrays or objects). This ensures that the same key content always produces the same serialized string, which is crucial for cache stability and avoiding collisions../shared(isFunction): This utility checks if the input is a function, enabling safe invocation of dynamic keys.../types(Key, Arguments): Provides type safety and clarity for input keys and argument types across the system.Caching/Data Fetching Layer: The output of
serializeis typically consumed by data-fetching or caching utilities that need a consistent string key to store or retrieve cached data and need the original arguments to pass to the fetcher function.
Mermaid Diagram: Flowchart of serialize Function
flowchart TD
A[Input: key (Key)] --> B{Is key a function?}
B -- Yes --> C[Try to invoke key()]
C --> D{Invocation successful?}
D -- Yes --> E[Set key = result of function]
D -- No --> F[Set key = '' (empty string)]
B -- No --> E[Use key as is]
E --> G[Set args = key]
G --> H{Type of key}
H -- string --> I[Use key as serialized key]
H -- array and non-empty --> J[Generate stableHash(key)]
H -- falsy or empty array --> K[Set serialized key = '']
I --> L[Return [serialized key, args]]
J --> L
K --> L
Summary
serialize.ts provides a crucial utility function to normalize and serialize cache keys in a consistent, stable manner supporting strings, arrays, and function-generated keys. It ensures that keys are safely handled even when dependencies are missing or keys are dynamic. This functionality is vital for caching or data-fetching systems requiring robust and collision-resistant keys to identify resources or requests.
End of Documentation