LocalStorage.js
2 years ago
LocationManager.js
2 years ago
RenderCurrentPage.js
2 years ago
resolveRestUrl.js
2 years ago
resolveRestUrl.js
45 lines
| 1 | const { |
| 2 | __, |
| 3 | } = wp.i18n; |
| 4 | |
| 5 | /** |
| 6 | * @param restUrl {String} |
| 7 | * @param props {Object} |
| 8 | * @returns {String} |
| 9 | * |
| 10 | * @throws {Error} |
| 11 | */ |
| 12 | function resolveRestUrl( restUrl, props ) { |
| 13 | if ( 'object' !== typeof props || !Object.keys( props )?.length ) { |
| 14 | return restUrl; |
| 15 | } |
| 16 | |
| 17 | for ( let [ name, value ] of Object.entries( props ) ) { |
| 18 | const regexp = new RegExp( `\\(\\?P<${name}>(.*?)\\)` ); |
| 19 | const parts = restUrl.match( regexp ); |
| 20 | |
| 21 | if ( !Array.isArray( parts ) ) { |
| 22 | continue; |
| 23 | } |
| 24 | |
| 25 | // to string |
| 26 | value = '' + value; |
| 27 | const partRegexp = new RegExp( parts[ 1 ] ); |
| 28 | |
| 29 | if ( !partRegexp.test( value ) ) { |
| 30 | throw new Error( |
| 31 | __( |
| 32 | `Invalid parameter for rest url. RegExp: ${ parts[ 1 ] }, |
| 33 | Value: ${ value }`, |
| 34 | 'jet-form-builder', |
| 35 | ), |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | restUrl = restUrl.replace( regexp, value ); |
| 40 | } |
| 41 | |
| 42 | return restUrl; |
| 43 | } |
| 44 | |
| 45 | export default resolveRestUrl; |