@@ -4,25 +4,43 @@ const { metarhia } = require('./deps.js');
44
55const prepare = ( unit , application ) => {
66 const namespaces = application . schemas ? [ application . schemas . model ] : [ ] ;
7- const { parameters, returns } = unit ;
7+ const { parameters, query = { } , returns } = unit ;
88 const { Schema } = metarhia . metaschema ;
99 const validation = {
1010 parameters : parameters ? Schema . from ( parameters , namespaces ) : null ,
11+ query : query . params ? Schema . from ( query . params , namespaces ) : null ,
1112 returns : returns ? Schema . from ( returns , namespaces ) : null ,
1213 } ;
13- const method = async ( args ) => {
14- const { parameters, returns } = validation ;
14+ const method = async ( args = { } ) => {
15+ const { parameters, query , returns } = validation ;
1516 if ( parameters ) {
1617 const { valid, errors } = parameters . check ( args ) ;
1718 const problems = errors . join ( '; ' ) ;
1819 if ( ! valid ) return new Error ( 'Invalid parameters type: ' + problems ) ;
1920 }
21+ if ( unit . query . params ) {
22+ const { valid, errors } = query . check ( args ) ;
23+ const problems = errors . join ( '; ' ) ;
24+ if ( ! valid ) return new Error ( 'Invalid query type: ' + problems ) ;
25+ }
2026 const service = method . parent [ '.service' ] ;
2127 const verb = unit . method . get ? 'get' : 'post' ;
2228 const target = [ service . url , unit . method [ verb ] ] ;
2329 if ( unit . method . path ) {
2430 target . push ( ...unit . method . path . map ( ( arg ) => args [ arg ] ) ) ;
2531 }
32+ let url = target . join ( '/' ) ;
33+ if ( unit . query ) {
34+ const params = [ ] ;
35+ const { prefix = '' , suffix = '' } = unit . query ;
36+ for ( const param of Object . keys ( unit . query . params ) ) {
37+ if ( ! args [ param ] ) continue ;
38+ params . push ( [ prefix + param + suffix , args [ param ] ] ) ;
39+ }
40+ const parsedParams = Object . fromEntries ( params ) ;
41+ const stringParams = new URLSearchParams ( parsedParams ) . toString ( ) ;
42+ url = params . length ? url + '?' + stringParams : url ;
43+ }
2644 const body = metarhia . metautil . serializeArguments ( unit . method . body , args ) ;
2745 const url = target . join ( '/' ) ;
2846 const options = { method : verb . toUpperCase ( ) , headers : unit . headers , body } ;
0 commit comments