Last active
June 5, 2024 10:36
-
-
Save WoLfulus/b424e613762a2ebcc2d52ada679fa425 to your computer and use it in GitHub Desktop.
Keeps the client instance the same when adding extensions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DirectusClient } from "@directus/sdk"; | |
export interface BindableClient { | |
with: < | |
Client extends DirectusClient<any>, | |
Extension extends object, | |
>( | |
createExtension: (client: Client) => Extension, | |
) => this & Extension; | |
} | |
export const bindings = () => { | |
return <Schema, Client extends DirectusClient<Schema>>( | |
client: Client, | |
): BindableClient => { | |
return { | |
with(createExtension: any) { | |
const extension = createExtension(this); | |
const extensions = Object.entries( | |
extension, | |
).reduce<PropertyDescriptorMap>((properties, [name, value]) => { | |
return { | |
...properties, | |
[name]: { | |
value, | |
configurable: true, | |
writable: true, | |
enumerable: true, | |
}, | |
}; | |
}, {}); | |
Object.defineProperties(this, extensions); | |
return this; | |
}, | |
} as any; | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sdk = createDirectus(...).with(bindings()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment