22 FunctionalFilter ,
33 InternalError ,
44 createFilterExtension ,
5+ getLogger ,
56} from '@vulcan-sql/core' ;
67
78import axios from 'axios' ;
@@ -12,23 +13,49 @@ export const RestApiCallerFilter: FunctionalFilter = async ({
1213} ) => {
1314 if ( ! args [ 'url' ] ) throw new InternalError ( 'url is required' ) ;
1415
15- const url = args [ 'arg' ] && args [ 'arg' ] === ':id' ? `${ args [ 'url' ] } /${ value } ` : args [ 'url' ] ;
16+ const logger = getLogger ( {
17+ scopeName : 'CORE' ,
18+ } ) ;
19+ let url = args [ 'url' ] ;
1620 const httpMethod = args [ 'method' ] || 'get' ;
21+
1722 let options : any = {
18- url : url ,
1923 method : httpMethod ,
20- params : args [ 'arg' ] && args [ 'arg' ] !== ':id' ? { [ args [ 'arg' ] ] : value } : { } ,
24+ url ,
2125 }
22- if ( args [ 'body' ] ) {
23- options = { ...options , body : JSON . parse ( args [ 'body' ] ) }
26+
27+ if ( 'path' in value ) {
28+ for ( const key in value [ 'path' ] ) {
29+ url = url . replace ( `:${ key } ` , value [ 'path' ] [ key ] ) ;
30+ }
31+ options = { ...options , url}
2432 }
25- if ( args [ 'headers' ] ) {
26- options = { ...options , headers : JSON . parse ( args [ 'headers' ] ) }
33+
34+ if ( 'query' in value ) {
35+ options = { ...options , params : value [ 'query' ] }
2736 }
2837
29- const results = await axios ( options ) ;
38+ if ( 'body' in value ) {
39+ options = { ...options , data : value [ 'body' ] }
40+ }
3041
31- return JSON . stringify ( results . data ) ;
42+ if ( 'headers' in value ) {
43+ options = { ...options , headers : value [ 'headers' ] }
44+ }
45+
46+ try {
47+ logger . info ( 'API request:' , options ) ;
48+ const results = await axios ( options ) ;
49+ logger . info ( 'API response:' , results . data ) ;
50+ return JSON . stringify ( results . data ) ;
51+ } catch ( error : any ) {
52+ const message = error . response
53+ ? `response status: ${ error . response . status } , response data: ${ JSON . stringify ( error . response . data ) } `
54+ : `remote server does not response. request ${ error . toJSON ( ) } }` ;
55+ throw new InternalError (
56+ `Failed to execute API request "${ url } " data, ${ message } `
57+ ) ;
58+ }
3259} ;
3360
3461export const [ Builder , Runner ] = createFilterExtension (
0 commit comments