1- import { superValidate , message , setError } from '$lib/index.js' ;
1+ import { superValidate , message , setError , type SuperValidated , type Infer } from '$lib/index.js' ;
22import { zod } from '$lib/adapters/zod.js' ;
33import { fail } from '@sveltejs/kit' ;
44import { schema } from './schema.js' ;
@@ -12,32 +12,34 @@ export const load = async () => {
1212 return { form } ;
1313} ;
1414
15+ function checkUsername ( form : SuperValidated < Infer < typeof schema > > ) {
16+ if ( takenUsernames . includes ( form . data . username ) ) {
17+ setError ( form , 'username' , 'Username is already taken.' ) ;
18+ return false ;
19+ }
20+ return true ;
21+ }
22+
1523export const actions : Actions = {
1624 post : async ( { request } ) => {
1725 const form = await superValidate ( request , zod ( schema ) ) ;
26+
27+ if ( ! form . valid || ! checkUsername ( form ) ) return fail ( 400 , { form } ) ;
28+
1829 console . log ( form ) ;
1930
20- if ( ! form . valid ) return fail ( 400 , { form } ) ;
31+ // TODO: Create user
2132
2233 return message ( form , 'Form posted successfully!' ) ;
2334 } ,
2435
2536 check : async ( { request } ) => {
26- // Introduce a little delay
37+ // Introduce a little delay (large DB check)
2738 await new Promise ( ( res ) => setTimeout ( res , Math . random ( ) * 500 ) ) ;
2839
29- const formData = await request . formData ( ) ;
30- console . log ( formData ) ;
31-
32- const form = await superValidate ( formData , zod ( usernameSchema ) ) ;
33- console . log ( form ) ;
34-
35- if ( ! form . valid ) return { form } ;
36-
37- if ( takenUsernames . includes ( form . data . username ) ) {
38- return setError ( form , 'username' , 'Username is already taken.' ) ;
39- }
40+ const form = await superValidate ( request , zod ( usernameSchema ) ) ;
4041
41- return { form } ;
42+ if ( ! form . valid || ! checkUsername ( form ) ) return fail ( 400 , { form } ) ;
43+ else return { form } ;
4244 }
4345} ;
0 commit comments