Skip to content

Instantly share code, notes, and snippets.

@colinhacks
Last active September 11, 2020 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinhacks/4c846b9b07325c600fe4c1cc38ddd5d7 to your computer and use it in GitHub Desktop.
Save colinhacks/4c846b9b07325c600fe4c1cc38ddd5d7 to your computer and use it in GitHub Desktop.
optional_ctx_resolver.ts
type GlobalCtx = {
session: {
authorize(): void;
};
};
type LoginInputType = {
email: string;
};
export type Fn = (...args: any) => Promise<any>;
export type ResolverDef<T extends Fn> = (
input: Parameters<T>[0],
ctx: GlobalCtx
) => ReturnType<T>;
export type CombinedResolver<T extends Fn> = (
input: Parameters<T>[0],
ctx?: GlobalCtx
) => ReturnType<T>;
function wrap<T extends ResolverDef<Fn>>(resolverDef: T): CombinedResolver<T>;
function wrap<T extends ResolverDef<Fn>>(resolverDef: T) {
return (input: Parameters<T>[0], ctx: GlobalCtx) => {
return resolverDef(input, ctx);
};
}
const login = wrap(async function login(input: LoginInputType, ctx) {
ctx.session.authorize();
return true;
});
// I want both of these to be valid
login({ email: '' }, { session: { authorize: () => {} } });
login({ email: '' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment