Last active
April 14, 2024 12:01
-
-
Save oof2win2/8eb92c1d33cf75263f4f68ab296794d5 to your computer and use it in GitHub Desktop.
Typings for a "class-based" API approach with workers
This file contains 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
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