Skip to content

Instantly share code, notes, and snippets.

@koblas
Created August 7, 2019 16:03
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 koblas/20e3246cbeccc3ef3fbea10ea0c5af33 to your computer and use it in GitHub Desktop.
Save koblas/20e3246cbeccc3ef3fbea10ea0c5af33 to your computer and use it in GitHub Desktop.
Login Typescript
export interface AuthTokenResponse {
token?: string;
created?: boolean;
user?: UserType;
errors?: ValidationError[];
}
// tslint:disable:no-multiline-string
const LOGIN_MUTATION = gql`
mutation($email: Email!, $password: String!) {
authLogin(email: $email, password: $password) {
... on ValidationErrors {
errors {
field
message
}
}
... on AuthToken {
token
}
}
}
`;
export type LoginResponse = ApolloQueryResult<{
authLogin: AuthTokenResponse;
}>;
interface LoginInput {
email: string;
password: string;
}
export function useLoginUser(
next: string,
extra?: MutationHookOptions<AuthTokenResponse>,
): (input: LoginInput) => Promise<void> {
const saveAuth = useSaveAuth();
const addSnack = useAddSnack();
const { history } = useReactRouter();
type VErrors = Record<keyof LoginInput, string[]>;
const [mutFunc] = useMutation<AuthTokenResponse>(LOGIN_MUTATION, extra);
return async (input: LoginInput) => {
const { data } = (await mutFunc({ variables: input })) as LoginResponse;
const result = data.authLogin;
if (result.errors && result.errors.length !== 0) {
throw validationErrors<VErrors>(result.errors);
} else if (!result.token) {
addSnack("Something failed");
} else {
await saveAuth(result.token);
history.push(next);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment