Skip to content

Answer:5 #1314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
33 changes: 33 additions & 0 deletions apps/angular/5-crud-application/src/app/_services/todos.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { Todo } from '../_interfaces/todo.interface';
import { handleError } from '../_utils';

@Injectable({ providedIn: 'root' })
export class TodosService {
private readonly http = inject(HttpClient);
private readonly url = environment.config.API_URL;
private readonly headers = environment.config.API_HEADERS;

getTodos(): Observable<Todo[]> {
return this.http
.get<Todo[]>(this.url, { headers: this.headers })
.pipe(catchError(handleError));
}

updateTodo(id: number, changes: Partial<Todo>): Observable<Todo> {
return this.http
.put<Todo>(`${this.url}/${id}`, JSON.stringify(changes), {
headers: this.headers,
})
.pipe(catchError(handleError));
}

deleteTodo(id: number): Observable<Todo> {
return this.http
.delete<Todo>(`${this.url}/${id}`)
.pipe(catchError(handleError));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './todos.actions';
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Todo } from '../../_interfaces/todo.interface';
import {
deleteTodoActions,
loadTodosActions,
updateTodoActions,
} from '../actions';
describe('Todos Actions', () => {
describe('loadTodosActions', () => {
it('should create a load action', () => {
const action = loadTodosActions.load();
expect(action).toEqual({ type: '[Todos/Load] Load' });
});

it('should create a success action', () => {
const todos: Todo[] = [
{ userId: 1, id: 1, title: 'Test Todo', completed: false },
];
const action = loadTodosActions.success({ todos });
expect(action).toEqual({
type: '[Todos/Load] Success',
todos: [{ userId: 1, id: 1, title: 'Test Todo', completed: false }],
});
});

it('should create a failure action', () => {
const error = 'Error loading todos';
const action = loadTodosActions.failure({ error });
expect(action).toEqual({
type: '[Todos/Load] Failure',
error: 'Error loading todos',
});
});
});

describe('updateTodoActions', () => {
it('should create an update action', () => {
const update = { id: 1, changes: { title: 'Updated Todo' } };
const action = updateTodoActions.update({ update });
expect(action).toEqual({
type: '[Todos/Update] Update',
update: { id: 1, changes: { title: 'Updated Todo' } },
});
});

it('should create a success action', () => {
const update = { id: 1, changes: { title: 'Updated Todo' } };
const action = updateTodoActions.success({ update });
expect(action).toEqual({
type: '[Todos/Update] Success',
update: { id: 1, changes: { title: 'Updated Todo' } },
});
});

it('should create a failure action', () => {
const error = 'Error updating todo';
const action = updateTodoActions.failure({ error });
expect(action).toEqual({
type: '[Todos/Update] Failure',
error: 'Error updating todo',
});
});
});

describe('deleteTodoActions', () => {
it('should create a delete action', () => {
const todo: Todo = {
userId: 1,
id: 1,
title: 'Test Todo',
completed: false,
};
const action = deleteTodoActions.delete({ todo });
expect(action).toEqual({
type: '[Todos/Delete] Delete',
todo: { userId: 1, id: 1, title: 'Test Todo', completed: false },
});
});

it('should create a success action', () => {
const todo: Todo = {
userId: 1,
id: 1,
title: 'Test Todo',
completed: false,
};
const action = deleteTodoActions.success({ todo });
expect(action).toEqual({
type: '[Todos/Delete] Success',
todo: { userId: 1, id: 1, title: 'Test Todo', completed: false },
});
});

it('should create a failure action', () => {
const error = 'Error deleting todo';
const action = deleteTodoActions.failure({ error });
expect(action).toEqual({
type: '[Todos/Delete] Failure',
error: 'Error deleting todo',
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Update } from '@ngrx/entity';
import { createActionGroup, emptyProps, props } from '@ngrx/store';

import { Todo } from '../../_interfaces/todo.interface';

export const loadTodosActions = createActionGroup({
source: 'Todos/Load',
events: {
Load: emptyProps(),
Success: props<{ todos: Todo[] }>(),
Failure: props<{ error: string }>(),
},
});

export const updateTodoActions = createActionGroup({
source: 'Todos/Update',
events: {
Update: props<{ update: Update<Todo> }>(),
Success: props<{ update: Update<Todo> }>(),
Failure: props<{ error: string }>(),
},
});

export const deleteTodoActions = createActionGroup({
source: 'Todos/Delete',
events: {
Delete: props<{ todo: Todo }>(),
Success: props<{ todo: Todo }>(),
Failure: props<{ error: string }>(),
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './todos.effects';
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { inject } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, map, mergeMap, of, switchMap } from 'rxjs';
import { Todo } from '../../_interfaces/todo.interface';
import { TodosService } from '../../_services/todos.service';
import {
deleteTodoActions,
loadTodosActions,
updateTodoActions,
} from '../actions';

export const loadTodosEffect = createEffect(
(
actions$: Actions = inject(Actions),
todosService = inject(TodosService),
) => {
return actions$.pipe(
ofType(loadTodosActions.load),
switchMap(() =>
todosService.getTodos().pipe(
map((todos) => loadTodosActions.success({ todos })),
catchError((error) => of(loadTodosActions.failure({ error }))),
),
),
);
},
{ functional: true },
);

export const updateTodoEffect = createEffect(
(
actions$: Actions = inject(Actions),
todosService = inject(TodosService),
) => {
return actions$.pipe(
ofType(updateTodoActions.update),
mergeMap(({ update }) =>
todosService
.updateTodo(
typeof update.id === 'string' ? parseInt(update.id, 10) : update.id,
update.changes,
)
.pipe(
map((updatedTodo: Todo) =>
updateTodoActions.success({
update: {
id: updatedTodo.id,
changes: updatedTodo,
},
}),
),
catchError((error) => of(updateTodoActions.failure({ error }))),
),
),
);
},
{ functional: true },
);

export const deleteTodoEffect = createEffect(
(
actions$: Actions = inject(Actions),
todosService = inject(TodosService),
) => {
return actions$.pipe(
ofType(deleteTodoActions.delete),
mergeMap(({ todo }) =>
todosService.deleteTodo(todo.id).pipe(
map((deletedTodo: Todo) =>
deleteTodoActions.success({ todo: deletedTodo }),
),
catchError((error) => of(updateTodoActions.failure({ error }))),
),
),
);
},
{ functional: true },
);
3 changes: 3 additions & 0 deletions apps/angular/5-crud-application/src/app/_store/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './actions';
export * from './effects';
export * from './reducers';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './todos.reducers';
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { createFeature, createReducer, on } from '@ngrx/store';
import { Todo } from '../../_interfaces/todo.interface';
import {
deleteTodoActions,
loadTodosActions,
updateTodoActions,
} from '../actions';

export interface TodoState extends EntityState<Todo> {
loadingTodos: boolean;
loadingTodoIds: number[];
error: string | null;
}

export const todoAdapter = createEntityAdapter<Todo>();

export const initialState: TodoState = todoAdapter.getInitialState({
loadingTodos: false,
loadingTodoIds: [],
error: null,
});

export const todosFeature = createFeature({
name: 'todos',
reducer: createReducer(
initialState,

// common - failure actions
on(
loadTodosActions.failure,
updateTodoActions.failure,
deleteTodoActions.failure,
(state, { error }) => ({
...state,
loadingTodos: false,
loadingTodoIds: [],
error: error,
}),
),

// load actions
on(loadTodosActions.load, (state) => ({
...state,
loadingTodos: true,
})),
on(loadTodosActions.success, (state, { todos }) =>
todoAdapter.setAll(todos, {
...state,
loadingTodos: false,
}),
),

// update actions
on(updateTodoActions.update, (state, { update }) => ({
...state,
loadingTodoIds: [...state.loadingTodoIds, update.id as number],
})),
on(updateTodoActions.success, (state, { update }) =>
todoAdapter.updateOne(update, {
...state,
loadingTodoIds: state.loadingTodoIds.filter((id) => id !== update.id),
}),
),

// delete actions
on(deleteTodoActions.delete, (state, { todo }) => ({
...state,
loadingTodoIds: [...state.loadingTodoIds, todo.id],
})),
on(deleteTodoActions.success, (state, { todo }) =>
todoAdapter.removeOne(todo.id, {
...state,
loadingTodoIds: state.loadingTodoIds.filter((id) => id !== todo.id),
}),
),
),

extraSelectors: ({ selectTodosState }) => ({
...todoAdapter.getSelectors(selectTodosState),
}),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { HttpErrorResponse } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';

export function handleError(err: HttpErrorResponse): Observable<never> {
const errorMsg =
err.error instanceof ErrorEvent
? `Client-side error: ${err.error.message}`
: `Server-side error (${err.status}): ${err.message}`;

console.warn(errorMsg);
return throwError(() => new Error(errorMsg));
}
1 change: 1 addition & 0 deletions apps/angular/5-crud-application/src/app/_utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './http-error-handler';
Loading