Setting up a service URL with parameters using a versatile approach

I am faced with a situation where I have over 200 service URLs that follow a specific format:

serviceURL = DomainName + MethodName + Path;

The DomainName and MethodNames can be configured, while the path may consist of elements such as Param1, Param2, and Param3 like this:

Path = 'A' + '/' + Param1 + '/' + 'B' + '/' + Param2 + '/' + 'C'  + '/'+ Param3;

My goal is to develop a versatile method that allows me to input a single URL with parameters, and then automatically sets the serviceURL based on that input. For example:

Var URL = 'domain1/method1/A/{0}/B/{1}/C/{2}';

GenericMethod(URL, Param1, Param2, Param3){

//Replace domain1 with DomainName
//Replace method1 with MethodName
//Replace {0}, {1}, {2} in the URL with the corresponding params

}

Has anyone encountered a similar need before?

Any suggestions are welcome.

Thank you

Answer №1

It seems like there might be a bit of confusion in understanding your query, but if I have grasped it correctly, you can achieve the desired outcome by implementing the following solution.

function generateURL(URL, parameter1, parameter2, parameter3){
    return URL.replace('{0}', parameter1).replace('{1}', parameter2).replace('{2}', parameter3);
}

$http.get(generateURL(URL, parameter1, parameter2, parameter3));

The most optimal approach would be to develop a service that encapsulates this functionality.

Answer №2

To achieve this functionality, utilize the arguments variable present in every JavaScript function and incorporate a bit of Regular Expression:

function generateServiceRequestURL(serviceEndpoint) {

    var requestURL = serviceEndpoint;

    for(var i = 1; i <= arguments.length; i++) {
        requestURL = requestURL.replace(new RegExp('\\{' + (i-1) + '\\}', 'gi'), arguments[i]);
    }

    return requestURL;

}

This code snippet retrieves all arguments after the serviceEndpoint and substitutes the {0} token with the respective parameter supplied to the function. It is designed to handle service URLs of any length, regardless of the number of parameters provided.

Answer №3

An efficient approach involves utilizing regular expressions:

let urlScheme = '{domain}/{method}/A/{param1}/B/{param2}/C/{param3}';

let URL = generateURL(urlScheme, 'myDomain', 'doSomething', 'a', 'b', 'c');

function generateURL(scheme, domain, method, param1, param2, param3){    
    return url
        .replace(/\{domain\}/g, domain)
        .replace(/\{method\}/g, method)
        .replace(/\{param1\}/g, param1)
        .replace(/\{param2\}/g, param2)
        .replace(/\{param3\}/g, param3);
}

For a more dynamic solution, consider passing a hash of arguments to generateURL ({ domain: 'myDomain', param1: 'myParam1'}) and then iterating through the keys.

Nevertheless, this approach introduces an implicit connection between unrelated services, potentially causing issues if a new service requires a different URL structure in the future. Therefore, in complex applications, it is common practice to adhere to conventional URL schemes to avoid unnecessary dependencies.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transformation of data in Ext JS

Shop: Ext.define('onlineStore.store.market', { model: 'Market', root: 'products', proxy: { type: 'ajax', url: 'http://localhost/onlineStore/data/market.json', reader: { type: ' ...

"Switching from vertical to horizontal time line in @devexpress/dx-react-scheduler-material-ui: A step-by-step guide

Is there a way to switch the Time to a horizontal line using @devexpress/dx-react-scheduler-material-ui? <WeekView startDayHour={7} endDayHour={20} timeTableCellComponent={TimeTableCell} dayScaleCellComponent={DayScaleCell} /> Click ...

Displaying a blank column in a table using JavaScript

I am trying to write a JavaScript function that will add a new column to a table. I want this new column to be displayed at the index where it is added, and then hidden once the addition is complete. Here is the code for my method: function addColumnToTa ...

Tips for distinguishing between local and remote variables (PHPStorm, Webstorm)

Is there a way to create a dynamic variable within my project that can be accessed in both JavaScript and PHP, which will automatically populate based on settings in WebStorm before deployment (locally or remotely)? For instance, let's say I define th ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...

Leveraging depends alongside max for jQuery validation

Trying to implement a conditional max value on a field using jQuery validation, but encountering issues. Even though I've utilized the depends function, it seems like the validate function is not functioning as expected. The code block appears correc ...

Change the Bootstrap components according to the size of the screen

Is there a built-in Bootstrap feature to change an element's class based on screen size? I'm working on a webpage with scrollable card elements. On desktop, the cards are arranged horizontally, but on mobile they are stacked vertically, requirin ...

Implementing dynamic webpage updates based on dropdown list selections

In my webpage, I am displaying a list of movies fetched from an API. The issue I am facing is related to sorting the movies based on user selection. When I uncomment one of the sort methods in my code, it works as intended. What I want to achieve is that ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

What is the best way to remove jest from your system completely?

I've been trying to set up jest for testing react applications However, after installing it with yarn, I am encountering issues starting my react app in any way This error message keeps popping up, but the suggested solution didn't resolve it: ...

Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here I inserted the code provided in the link into an Angular directive like this: app.directive('stackBar', function() { return { restrict: 'A', ...

What could be preventing $routeChangeSuccess from being called?

I have been working on a similar feature for my app, but I'm struggling to capture the routeChangeSuccess event. var myapp = angular.module('myapp', ["ui.router", "ngRoute"]); myapp.controller("home.RootController", function($rootScope, ...

Error Handling in ReactJS

Every time I try to execute my ReactJS code, an error pops up saying: Unhandled Rejection (Error): Material-UI: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e2f5f1f3e4d0a1a6bea3bea0">[email protected]</a> ve ...

Selenium WebDriverJs has difficulty in setting up a new client for iOS devices

Struggling to make Selenium WebDriverJS work with the iOS browser, but unfortunately facing some issues. I followed the instructions on setting up the "iWebDriver" project as mentioned on the iPhoneDriver wiki page. The Python script worked fine, and even ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

The update function now saves only the name property in the database, while the url property is stored as undefined

I utilized nodejs, mongoose, and angular to create a RestAPI with mean stack, focusing on updating provider records in my database. Below is the implementation of the put method: Object {_id: "553d27a24c47696420c6ee39", name: "nn", url: undefined, __v: 0, ...

Encountering an issue with the file:/// error message while trying to locate the hostname in Ionic and

Utilizing Ionic and Oauth.io for authentication has been a smooth process when running ionic serve with the outh.js file included in the index. However, issues arise when switching to ionic run ios or installing the app on an Android device. Upon clicking ...

What are some ways I can showcase the outcomes of my multiple choice quiz?

I need help with my multiple choice quiz. I want to display the answers under each question and highlight the correct one in bold. Here is the current code: function check() { var question1 = document.quiz.question1.value; var question2 = document.q ...

AngularJS ng-repeat along with jQuery Mobile

I am attempting to utilize ng-repeat in combination with jQuery mobile checkboxes. While the checkboxes appear correctly, they do not become checked when clicked. Could someone provide guidance on how to effectively use ng-repeat with jQuery mobile checkb ...

Complete and send HTML forms with changing IDs

I am facing an issue with storing data from two HTML forms with dynamic ID attributes using AJAX calls. Currently, the AJAX call only works for one HTML form with a static ID name "surveyImage". I am unsure how to individually call the submit() method for ...