Skip to content

Instantly share code, notes, and snippets.

@ebeloded
Last active June 9, 2023 23:24
Show Gist options
  • Save ebeloded/0aa732178c68c5b047cad9be60b1dd3f to your computer and use it in GitHub Desktop.
Save ebeloded/0aa732178c68c5b047cad9be60b1dd3f to your computer and use it in GitHub Desktop.
createPath
type ProxyType<T> = {
[P in keyof T]: Record<string, ProxyType<T[P]> & Callable> & Callable
}
type Callable = {
(arg?: string): string
}
export function createPath<T extends {}>(_input: T): ProxyType<T> {
const proxy: any = (path: string[]) =>
new Proxy(() => {}, {
get: (_target, prop: string) =>
typeof path === 'symbol' ? undefined : proxy([...path, prop]),
apply: (_, _this, args) => {
const lastIndex = path.length - 1
const last = path[lastIndex] /*?*/
if (last === 'call') {
path = path.slice(0, lastIndex)
} else if (last === 'apply') {
path = path.slice(0, lastIndex)
args = args[1]
}
if (typeof path[path.length - 1] === 'symbol') return undefined
return [...path, ...args].join('/')
},
})
return proxy([])
}
export const dbPath = createPath({
workspaces: { accounts: {}, transactions: {} },
})
dbPath.workspaces('asdf') /*?*/
dbPath.workspaces['asdf']() /*?*/
dbPath.workspaces['asdf'].accounts('asdf') /*?*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment