Utilizing a firestore database, I have established a schema to structure my data:
type FirestoreCollection<T> = {
documentType: T;
subcollections?: {
[key: string]: FirestoreCollection<object>;
};
};
type FirestoreSchema<
T extends { [key: string]: U },
U = FirestoreCollection<object>
> = T;
export type FirestoreModel = FirestoreSchema<{
'chat-messages': {
documentType: ChatMessage;
};
chats: {
documentType: Chat;
subcollections: {
'chat-participants': {
documentType: ChatParticipant;
};
};
};
}>;
This schema is functioning smoothly.
Now, I aim to devise a type that combines all the keys from the model, interconnected by a /
, followed by a string
(a document id), and then iterate recursively through all subcollections in the model.
The desired output for this type is as follows:
type DocumentPath =
| `chat-messages/${string}`
| `chats/${string}`
| `chats/${string}/chat-participants/${string}`;
Although here's my current attempt at it, I sense there's still room for improvement:
type DocumentPath<
T extends { [key: string]: U },
U = FirestoreCollection<object>
> = {
[key in keyof T]:
| `${key & string}/${string}/${DocumentPath<T[key]['subcollections']>}`
| `${key & string}/${string}`;
}[keyof T];
Any suggestions to enhance this? Feel free to share your thoughts.