@@ -20,45 +20,32 @@ const getClient = (item: ItemService): Client => {
20
20
}
21
21
}
22
22
23
- const createServiceRequests = ( { api, _id, item } : any ) => {
24
- return ( requestItem : ItemServiceRequest , index : number ) => {
25
- // TODO: reuse existing client (of service) if possible
26
- // or at least $fetch/useFetch/unfetch client which supports
27
- // entire service request options (for example hooks, etc.)
28
- const createInvoke = ( item : ItemServiceRequest ) => {
29
- const { url, method, headers, body } = item
30
- return async ( ) => {
31
- const response = await fetch ( url , {
32
- method,
33
- headers,
34
- // IMPORTANT: Request with GET/HEAD method cannot have body
35
- ...( ! [ 'GET' , 'HEAD' ] . includes ( method ) && { body } ) ,
36
- } )
37
- return response . json ( )
38
- }
39
- }
40
- const proxy = new Proxy ( ( ( ) => { } ) , {
41
- /** Select existing by name: "service.requests('getAllTodos')" */
42
- get : ( _target , _id ) : ServiceRequest => {
43
- return { invoke : createInvoke ( item ) , item }
44
- } ,
45
- /** Creating a new service by passing in options */
46
- apply : ( _target , _thisArg , args ) : ServiceRequest => {
47
- return { invoke : createInvoke ( item ) , item }
48
- }
23
+ const createServiceRequest = ( item : ItemServiceRequest ) : ServiceRequest => {
24
+ // TODO: reuse existing client (of service) if possible
25
+ // or at least $fetch/useFetch/unfetch client which supports
26
+ // entire service request options (for example hooks, etc.)
27
+ const invoke = async ( overrides ?: Partial < ItemServiceRequest > ) => {
28
+ const { url, method, headers, body } = { ...item , ...overrides }
29
+ const response = await fetch ( url , {
30
+ method,
31
+ headers,
32
+ // IMPORTANT: Request with GET/HEAD method cannot have body
33
+ ...( ! [ 'GET' , 'HEAD' ] . includes ( method ) && { body } ) ,
49
34
} )
50
- return [ item . name , proxy ]
35
+ return response . json ( )
51
36
}
37
+ return { invoke, item }
52
38
}
53
39
54
40
export const createService = ( api : ClientBuilder ) => {
55
41
return async ( _id : string ) => {
56
- const item = await api . services [ _id ] . get ( )
42
+ const item = await api . services [ _id ] . get < ItemService > ( )
57
43
const client = getClient ( item )
58
44
59
- const requests = Object . fromEntries (
60
- item . requests . map ( createServiceRequests ( { api, _id, item } ) )
61
- )
45
+ const requests = item . requests . reduce ( ( previousValue , currentValue ) => ( {
46
+ ...previousValue ,
47
+ [ currentValue . name ] : createServiceRequest ( currentValue )
48
+ } ) , { } as Record < string , ServiceRequest > )
62
49
63
50
return { client, requests, item } // see NOTE bellow
64
51
}
0 commit comments