Created
August 7, 2019 16:03
-
-
Save koblas/20e3246cbeccc3ef3fbea10ea0c5af33 to your computer and use it in GitHub Desktop.
Login Typescript
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
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