Skip to content
Merged
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
32 changes: 21 additions & 11 deletions src/app/core/validators/pokemon.validator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Observable } from 'rxjs';
import { catchError, map, of } from 'rxjs';
import { catchError, finalize, map, of, switchMap, tap, timer } from 'rxjs';
import { inject, Injectable, signal } from '@angular/core';
import type { AbstractControl, AsyncValidator, ValidationErrors } from '@angular/forms';
import { PokemonService } from '~features/pokemon/services/pokemon.service';
Expand All @@ -8,30 +8,40 @@ import { PokemonService } from '~features/pokemon/services/pokemon.service';
export class PokemonValidator implements AsyncValidator {
private readonly pokemonService = inject(PokemonService);
private readonly pokemonName = signal('');
private readonly debounceMs = 500;

readonly pokemonId = signal(-1);
readonly isPokemonValidating = signal(false);

validate(control: AbstractControl): Observable<ValidationErrors | null> {
validate(control: AbstractControl<string | null>): Observable<ValidationErrors | null> {
const pokemonName = (control.value ?? '').toLowerCase().trim();

if (!pokemonName) {
this.isPokemonValidating.set(false);
this.pokemonId.set(-1);
return of(null);
}

this.pokemonName.set(pokemonName.toLowerCase());
this.pokemonName.set(pokemonName);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the extra .toLowerCase() call here because the value was already being normalized earlier in validate().

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

this.isPokemonValidating.set(true);
return this.pokemonService.getPokemon(pokemonName.toLowerCase()).pipe(
map((pokemon) => {
return this.validatePokemonName(pokemonName).pipe(
finalize(() => {
this.isPokemonValidating.set(false);
this.pokemonId.set(pokemon.id);
return null;
}),
catchError(() => {
this.isPokemonValidating.set(false);
return of({ pokemonName: true });
}),
);
}

private validatePokemonName(pokemonName: string): Observable<ValidationErrors | null> {
return timer(this.debounceMs).pipe(
switchMap(() =>
this.pokemonService.getPokemon(pokemonName).pipe(
tap((pokemon) => {
this.pokemonId.set(pokemon.id);
}),
map(() => null),
catchError(() => of({ pokemonName: true })),
),
),
);
}
}