Skip to content

Instantly share code, notes, and snippets.

@nickdbush
Last active June 28, 2024 17:59
Show Gist options
  • Select an option

  • Save nickdbush/7e1f2b6dcd6add2556b871badf53c18b to your computer and use it in GitHub Desktop.

Select an option

Save nickdbush/7e1f2b6dcd6add2556b871badf53c18b to your computer and use it in GitHub Desktop.
Better generated client
export type Response<Tag, Data = never> = {
tag: Tag;
data: Data;
};
const parseEmpty = <T>(tag: T) => (_: any): Response<T> => ({
tag,
data: null as never,
});
const endpoint = <R>({}: {
parsers: {[key: number]: (data: any) => R};
}): (() => Promise<R>) => {
return async (): Promise<R> => {
// TODO
}
}
export type UserResponse = Response<"user", User>;
export type User = {
shippingPort: string | null;
preferences: string[];
id: string;
email: string;
}
const parseUser = (data: any): UserResponse => ({
tag: "user",
data: {
shippingPort: data.shipping_port,
preferences: data.preferences ?? [],
id: data.id,
email: data.email,
}
});
export type NotFoundResponse = Response<"not_found">;
export type GetUserResponse = UserResponse | NotFoundResponse;
export const getUser = endpoint<GetUserResponse>({
parsers: {
200: parseUser,
404: parseEmpty("not_found"),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment