1- import * as v from 'valibot'
1+ import * as v from 'valibot' ;
22
3- const Client = v . object ( {
4- id : v . number ( ) ,
5- name : v . string ( ) ,
6- email : v . string ( )
7- } )
8- export type Client = v . InferOutput < typeof Client >
3+ const Client = v . object ( { id : v . number ( ) , name : v . string ( ) , email : v . string ( ) } ) ;
4+ export type Client = v . InferOutput < typeof Client > ;
5+ const Clients = v . array ( Client ) ;
96
10- const Clients = v . array ( Client )
7+ // Write DTO (what your form sends)
8+ const ClientUpsert = v . object ( {
9+ name : v . string ( ) ,
10+ email : v . string ( )
11+ } ) ;
12+ export type ClientUpsert = v . InferOutput < typeof ClientUpsert > ;
13+
14+ const API = '/api' ;
1115
1216export async function getClients ( ) {
13- const response = await fetch ( '/api/clients' , { credentials : 'include' } )
14- if ( ! response . ok ) {
15- throw new Error ( 'Failed to fetch Clients' )
16- }
17- return v . parse ( Clients , await response . json ( ) )
17+ const r = await fetch ( `${ API } /clients` , { credentials : 'include' } ) ;
18+ if ( ! r . ok ) throw new Error ( 'Failed to fetch clients' ) ;
19+ return v . parse ( Clients , await r . json ( ) ) ;
20+ }
21+
22+ export async function getClient ( id : number ) {
23+ const r = await fetch ( `${ API } /clients/${ id } ` , { credentials : 'include' } ) ;
24+ if ( ! r . ok ) throw new Error ( `Client ${ id } not found` ) ;
25+ return v . parse ( Client , await r . json ( ) ) ;
26+ }
27+
28+ export async function createClient ( input : ClientUpsert ) {
29+ // optional client-side shape check
30+ v . parse ( ClientUpsert , input ) ;
31+
32+ const r = await fetch ( `${ API } /clients` , {
33+ method : 'POST' ,
34+ credentials : 'include' ,
35+ headers : { 'Content-Type' : 'application/json' } ,
36+ body : JSON . stringify ( input )
37+ } ) ;
38+ if ( r . status === 409 ) throw new Error ( 'Email already exists' ) ;
39+ if ( ! r . ok ) throw new Error ( 'Create failed' ) ;
40+ return v . parse ( Client , await r . json ( ) ) ;
1841}
42+
43+ export async function updateClient ( id : number , input : ClientUpsert ) {
44+ v . parse ( ClientUpsert , input ) ;
45+
46+ const r = await fetch ( `${ API } /clients/${ id } ` , {
47+ method : 'PUT' ,
48+ credentials : 'include' ,
49+ headers : { 'Content-Type' : 'application/json' } ,
50+ body : JSON . stringify ( input )
51+ } ) ;
52+ if ( r . status === 409 ) throw new Error ( 'Email already exists' ) ;
53+ if ( ! r . ok ) throw new Error ( 'Update failed' ) ;
54+ return v . parse ( Client , await r . json ( ) ) ;
55+ }
56+
57+ export async function deleteClient ( id : number ) {
58+ const r = await fetch ( `${ API } /clients/${ id } ` , {
59+ method : 'DELETE' ,
60+ credentials : 'include'
61+ } ) ;
62+ if ( ! ( r . ok || r . status === 204 ) ) throw new Error ( 'Delete failed' ) ;
63+ }
0 commit comments