Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { Actions, createEffect, ofType } from '@ngrx/effects';
- import {
- catchError,
- concatMap,
- map,
- switchMap,
- tap,
- toArray,
- withLatestFrom,
- } from 'rxjs/operators';
- import { Action, select, Store } from '@ngrx/store';
- import { UsersService } from '../../services/users.service';
- import { concat, forkJoin, merge, Observable, of } from 'rxjs';
- import { HttpErrorResponse } from '@angular/common/http';
- import { UserSkillState } from '../user-skill.state';
- import {
- loadUserSkills,
- setUserSkillSaveLoading,
- setUserSkillsLoadError,
- updateUserSkillById,
- userSkillActionTypes,
- } from '../actions/user-skill.action';
- import { selectUserSkills } from '../selectors/user-skill.selector';
- import { IUserSkill } from '../../classes/IUserSkill';
- import { SkillService } from '../../../skills/services/skill.service';
- import { Skill } from '../../../skills/classes/Skill';
- import { loadSkills } from '../../../skills/ngrx/actions/skill.action';
- import { selectProfile } from '../../../../ngrx/selectors/app.selector';
- import { IProfile } from '../../../profile/classes/IProfile';
- import { MainConstants } from '../../../../constant';
- import { showGenericError, showToast } from '../../../../ngrx/actions/app.action';
- import { ToastType } from '../../../../classes/ToastType';
- interface RequestUserSkillsAction extends Action {
- userId: number;
- }
- interface RequestSaveUserSkillManyAction extends Action {
- deletedSkillIds: number[];
- userId: number;
- }
- @Injectable()
- export class UserSkillEffect {
- constructor(
- private actions$: Actions,
- private usersService: UsersService,
- private skillService: SkillService,
- private store: Store<UserSkillState>
- ) {}
- requestUserSkills$ = createEffect(() =>
- this.actions$.pipe(
- ofType(userSkillActionTypes.requestUserSkills),
- withLatestFrom(this.store.pipe(select(selectProfile))),
- switchMap(([{ userId }, { id: profileId }]: [RequestUserSkillsAction, IProfile]) => {
- userId = userId || profileId;
- return this.usersService.getUserSkills(userId);
- }),
- map((userSkills: IUserSkill[]) =>
- loadUserSkills({
- userSkills,
- })
- ),
- catchError((err: HttpErrorResponse) => of(setUserSkillsLoadError({ error: err.message })))
- )
- );
- addUserSkillMany$ = createEffect(() =>
- this.actions$
- .pipe(
- ofType(userSkillActionTypes.requestSaveUserSkillMany),
- withLatestFrom(this.store.pipe(select(selectUserSkills))),
- concatMap((action: [RequestSaveUserSkillManyAction, IUserSkill[]]) => {
- this.store.dispatch(setUserSkillSaveLoading({ isSaveLoading: true }));
- const deletedSkillIds = action[0].deletedSkillIds;
- const userId = action[0].userId;
- if (Array.isArray(deletedSkillIds) && deletedSkillIds.length > 0) {
- return this.deleteUserSkills(deletedSkillIds, userId).pipe(map(() => action));
- }
- return of(null).pipe(map(() => action));
- }),
- concatMap((action: [RequestSaveUserSkillManyAction, IUserSkill[]]) =>
- this.handleNewSkillSave(action[1], action[0].userId)
- ),
- concatMap(
- ({ oldIds, newIds, userId }: { oldIds: number[]; newIds: number[]; userId: number }) => {
- oldIds.forEach((oldId: number, index: number) =>
- this.store.dispatch(
- updateUserSkillById({ userSkill: { id: oldId, changes: { id: newIds[index] } } })
- )
- );
- return of(userId);
- }
- ),
- withLatestFrom(this.store.pipe(select(selectUserSkills))),
- concatMap(([userId, userSkills]: [number, IUserSkill[]]) =>
- this.postUserSkills(userSkills, userId).pipe(map(() => userId))
- ),
- concatMap((userId: number) => {
- const userSkills$ = this.usersService.getUserSkills(userId);
- const skills$ = this.skillService.getAllSkills();
- return forkJoin(userSkills$, skills$);
- }),
- switchMap(([userSkills, skills]: [IUserSkill[], Skill[]]) => {
- return merge([
- loadSkills({ skills }),
- loadUserSkills({ userSkills }),
- setUserSkillSaveLoading({ isSaveLoading: false }),
- showToast({
- translationKey: 'COMMON.SUCCESS',
- toastType: ToastType.Success,
- params: null,
- }),
- ]);
- })
- )
- .pipe(
- catchError(() =>
- merge([showGenericError(), setUserSkillSaveLoading({ isSaveLoading: false })])
- )
- )
- );
- private deleteUserSkills(skillIds: number[], userId: number): Observable<unknown> {
- return this.usersService.deleteUserSkills({
- userId: userId,
- skillIds,
- });
- }
- private postUserSkills(skills: IUserSkill[], userId: number): Observable<IUserSkill[]> {
- return this.usersService.postUserSkills({
- userId: userId,
- skills: skills.map((skill) => ({
- skillId: skill.id,
- level: skill.level || MainConstants.NEW_SKILL_TO_USER_DEF_LEVEL,
- })),
- });
- }
- private handleNewSkillSave(
- userSkills: IUserSkill[],
- userId: number
- ): Observable<{ oldIds: number[]; newIds: number[]; userId: number }> {
- const newSkills = userSkills.filter((userSkill: IUserSkill) => userSkill.id <= 0);
- const postNewSkills$: Observable<Skill>[] = newSkills.map((newSkill) =>
- this.skillService.createSkill({
- name: newSkill.name,
- description: newSkill.description,
- isApproved: 0,
- })
- );
- let index = 0;
- const oldIds = [];
- const newIds = [];
- return concat(...postNewSkills$).pipe(
- tap((skill: Skill) => {
- oldIds.push(newSkills[index].id);
- newIds.push(skill.id);
- index++;
- }),
- toArray(),
- map(() => ({ oldIds, newIds, userId })) // return new skills with created ids
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement