Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

validation-queries.service.ts

89 lines2.2 KB

1import { Injectable } from '@angular/core'
2import { mutationOptions, queryOptions } from '@tanstack/angular-query'
3​
4export type UsernameValidation = {
5 available: boolean
6}
7​
8export type InviteCodeValidation = {
9 valid: boolean
11​
12export type RegistrationData = {
13 username: string
14 inviteCodes: Array<string>
16​
17export type RegistrationMutationResult =
18 | { ok: true }
19 | {
20 ok: false
21 errors: Array<{
22 fieldPath: ['username'] | ['inviteCodes', number]
23 error: string
24 }>
25 }
26​
27@Injectable({ providedIn: 'root' })
28export class ValidationQueriesService {
29 usernameAvailability(username: string) {
30 return queryOptions({
31 queryKey: ['username-availability', username],
32 gcTime: 15_000,
33 queryFn: async (): Promise<UsernameValidation> => {
34 await this.delay()
35 return { available: username.toLowerCase() !== 'taken' }
36 },
37 })
38 }
39​
40 inviteCodeValidation(code: string) {
41 return queryOptions({
42 queryKey: ['invite-code-validation', code],
43 gcTime: 15_000,
44 staleTime: 30_000,
45 queryFn: async (): Promise<InviteCodeValidation> => {
46 await this.delay()
47 return { valid: code.toUpperCase().startsWith('TEAM-') }
48 },
49 })
50 }
51​
52 submitRegistration() {
53 return mutationOptions({
54 gcTime: 20_000,
55 mutationFn: async (
56 variables: RegistrationData,
57 ): Promise<RegistrationMutationResult> => {
58 await this.delay()
59​
60 const errors: Array<{
61 fieldPath: ['username'] | ['inviteCodes', number]
62 error: string
63 }> = []
64​
65 if (variables.username.toLowerCase().includes('error')) {
66 errors.push({
67 fieldPath: ['username'],
68 error: 'This username cannot be registered',
69 })
70 }
71​
72 variables.inviteCodes.forEach((inviteCode, index) => {
73 if (inviteCode.toLowerCase().includes('error')) {
74 errors.push({
75 fieldPath: ['inviteCodes', index],
76 error: 'This invite code cannot be registered',
77 })
78 }
79 })
80​
81 return errors.length > 0 ? { ok: false, errors } : { ok: true }
82 },
83 })
84 }
85​
86 private delay() {
87 return new Promise((resolve) => setTimeout(resolve, 450))
88 }