Skip to content

Instantly share code, notes, and snippets.

@oof2win2
Last active April 14, 2024 12:01
Show Gist options
  • Save oof2win2/8eb92c1d33cf75263f4f68ab296794d5 to your computer and use it in GitHub Desktop.
Save oof2win2/8eb92c1d33cf75263f4f68ab296794d5 to your computer and use it in GitHub Desktop.
Typings for a "class-based" API approach with workers
class Users {
constructor(private env: Env) {}
async getUser(userId: string) {
// ...
}
// ...
}
type PickMatching<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
// biome-ignore lint/complexity/noBannedTypes: it's okay here as it is only a picker
type ExtractMethods<T> = PickMatching<T, Function>;
export class Backend extends WorkerEntrypoint<Env> {
#users: Users;
constructor(ctx: ExecutionContext, env: Env) {
super(ctx, env);
this.#users = new Users(env);
}
get users() {
// biome-ignore format: its nicer in one line
return {
getUser: this.#users.getUser.bind(this.#users),
getUsers: this.#users.getUsers.bind(this.#users),
createUser: this.#users.createUser.bind(this.#users),
deleteUser: this.#users.deleteUser.bind(this.#users)
} satisfies ExtractMethods<Users>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment