Skip to content

Instantly share code, notes, and snippets.

@WoLfulus
Last active June 5, 2024 10:36
Show Gist options
  • Save WoLfulus/b424e613762a2ebcc2d52ada679fa425 to your computer and use it in GitHub Desktop.
Save WoLfulus/b424e613762a2ebcc2d52ada679fa425 to your computer and use it in GitHub Desktop.
Keeps the client instance the same when adding extensions.
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;
};
};
const sdk = createDirectus(...).with(bindings());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment