Skip to content

Instantly share code, notes, and snippets.

@ebeloded
Created June 6, 2023 07:53
Show Gist options
  • Save ebeloded/6cf71bfc23c28ec92f750d860ce80ad5 to your computer and use it in GitHub Desktop.
Save ebeloded/6cf71bfc23c28ec92f750d860ce80ad5 to your computer and use it in GitHub Desktop.
dbPath.ts
type PathConfig = { [key: string]: PathConfig }
type Collection<T extends PathConfig> = ((id?: string) => string) & {
[K in keyof T]: Collection<T[K]> & ((id?: string) => string)
}
function collection<T extends PathConfig>(
basePath: string,
name: string,
subCollections?: T
): Collection<T> {
const newPath = basePath + (name ? '/' + name : '')
const handler = {
apply: (target: any, thisArg: any, argArray?: any) => {
return newPath + (argArray[0] ? '/' + argArray[0] : '')
},
get: (target: any, property: string) => {
if (property in target) {
return target[property]
}
if (subCollections && property in subCollections) {
target[property] = collection(
newPath,
property,
subCollections[property]
)
return target[property]
}
if (typeof property === 'string') {
target[property] = collection(newPath, property)
return target[property]
}
return undefined
},
}
return new Proxy(() => {}, handler) as Collection<T>
}
const dbPath = collection('', '', {
workspaces: {
accounts: {},
categories: {
subcategories: {},
},
transactions: {},
},
})
dbPath.workspaces() /*?*/
dbPath.workspaces('asdf') /*?*/
dbPath.workspaces['w1'].categories() /*?*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment