Skip to content

Instantly share code, notes, and snippets.

@otonielguajardo
Last active August 3, 2021 16:16
Show Gist options
  • Save otonielguajardo/dd57a5f580489ca1a16d363f6726e889 to your computer and use it in GitHub Desktop.
Save otonielguajardo/dd57a5f580489ca1a16d363f6726e889 to your computer and use it in GitHub Desktop.
Directus Angular register/login NGXS action flow
...
@Action(Login)
login({ patchState, dispatch, getState }: StateContext<AppStateModel>, { payload }: Login) {
let body = {};
let endpoint = '';
if (payload != null) {
patchState({ currentUserLoading: true });
body = payload;
endpoint = 'auth/login';
} else if (this.apiService.refresh_token != undefined) {
patchState({ screenLoading: true });
body = { refresh_token: this.apiService.refresh_token };
endpoint = 'auth/refresh';
} else {
patchState({ currentUser: null });
return false;
}
return this.apiService.request('POST', endpoint, body).pipe(
tap((responseA: any) => {
this.apiService.access_token = responseA.data.access_token;
this.apiService.refresh_token = responseA.data.refresh_token;
}),
concatMap((responseA: any) =>
this.apiService.request('GET', `users/me`).pipe(
map((responseB: any) => {
console.log('@Action(Login)', responseB.data);
patchState({ currentUser: responseB.data });
})
)
),
catchError((err) => {
if (err.error != undefined) {
if (err.error.errors != undefined) {
if (err.error.errors[0].extensions.code == 'INVALID_PAYLOAD') {
console.log('Cmbinación incorrecta, revisar correo y contraseña');
} else if (err.error.errors[0].extensions.code == 'INVALID_CREDENTIALS') {
console.log('credenciales inválidas, intenta nuevamente y si el error persiste comunicate a soporte');
dispatch(new Logout());
}
}
}else{
console.log(err);
}
return throwError(err);
}),
finalize(() => {
patchState({ currentUserLoading: false });
})
);
}
@Action(Register)
register({ patchState, dispatch, getState }: StateContext<AppStateModel>, { payload }: Register) {
patchState({ currentUserLoading: true });
return this.apiService
.request('POST', `users`, payload)
.pipe(
tap((response: any) => {
console.log('@Action(Register)', response.data);
dispatch(new Login({ email: payload.email, password: payload.password }));
console.log('Registro exitoso');
// window.location.replace('/');
}),
catchError((err) => {
if (err.error.errors[0].extensions.code == 'RECORD_NOT_UNIQUE') {
console.log('El correo ingresado ya esta siendo usado por otro usuario');
} else {
console.log(err);
}
return throwError(error);
}),
finalize(() => {
patchState({ currentUserLoading: false });
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment