Should I separate client-side API calls into a separate .js file and class, and reference that?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/406300

  •  08-03-2021
  •  | 
  •  

سؤال

Summary

Instead of calling WebApi straight from a Web Forms User Control, I have created JS class which contains functions returning jQuery AJAX requests. The control would instantiate the class and call these functions, which would allow me to separate the code that calls the API from my control.

Is this the best approach? What down-falls could there be later?

Implementation

MyService.js

Assume my WebApi controller is called MyServiceController. The client-side JS class would be:

class MyService
{
    //  Example method to call
    start = function(userId) {
        return $.ajax({
            url: '/api/myService/start',
            type: 'POST',
            data: {
                id: userId
            });
    }

    // Another example method
    stop = function() {
        return $.ajax({
            url: '/api/myService/stop',
            type: 'POST'
        });
    }
}

MyCode.ascx

This will then be consumed from the web forms control as so:

// Instantiate the class
var let api = new MyService();

// Assume document has loaded and add click-handler
var someId = 1;

// Call Start
$('.myService-start').click(function(){
    api.start(someId)
        .done(function(){
            console.log('start completed');
        })
        .fail(function(){
            console.log('start failed');
        });
});

// Call Stop
$('.myService-stop').click(function(){
    api.stop()
        .done(function(){
            console.log('stop completed');
        })
        .fail(function(){
            console.log('stop failed');
        });;
});
<span class"myService-start">Start</span>
<span class"myService-stop">Stop</span>

Question

Am I following a bad pattern? Will this lead to a code-smell later on?

Please let me know if there's a better way to implement this

هل كانت مفيدة؟

المحلول

Yes, its good practice.

You presumably will want to use the api in several different places through your app and this will save you code and make things cleaner.

I would go further and put the javascript client in its own project so you can use it across multiple projects, distribute it via npn, add typescript types, change from $.ajax to the native fetch(), upgrade from webforms?!?!!!?!!! etc

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top