When using getObjectById on objects with recursive relationships (e.g., a user whose bestFriend is also a user), you may encounter infinite recursion errors or receive undefined.
To prevent this and control the returned structure, pass a second argument to getObjectById representing the desired data structure. The actual values in this structure do not matter (e.g., use empty strings); only the data types are important.
Benefits of providing a structure:
- Prevents infinite recursion: Limits the depth of denormalization.
- Controls structure: Returns only the specific fields you need.
- TypeScript support: Automatically provides proper typing for the returned object based on the structure provided.
// Example: Preventing infinite recursion in a user/friend relationship
const user = normalizer.getObjectById('1', {
id: '',
name: '',
bestFriend: { id: '', name: '' },
});
// Resulting structure:
// {
// id: '1',
// name: 'X',
// bestFriend: { id: '2', name: 'Y' }
// }