Implementing the JavaScript API Shell

Can anyone suggest a template that can be used to write the JavaScript API where there is no common code between multiple implementations? The idea is to provide a customer consumer with one wrapping API for one of the many possible APIs defined at runtime. An API call can be associated with objects / libraries already in the application environment or web service calls.

The following bits of pseudo code are the two approaches that I have examined:

Monolithic solution

var apiWrapper = {
      init: function() {
          // *runtime* context of which API to call
          this.context = App.getContext(); 
      },
      getName: function() {
           switch(context) {
             case a:
               return a.getDeviceName() // real api call
             case b:
               return b.deviceName // real api call
             etc...
           }
      // More methods ...
    }
}

Pros . May support consistent API for library users.

Cons : will lead to the creation of a huge monolithic library that is difficult to maintain.

Solution for modules

init.js

// set apiWrapper to the correct implementation determined at runtime
require([App.getContext()], function(api) {
  var apiWrapper = api;
});

module_a.js

// Implementation for API A
define(function() {
  var module = {
      getName: function() {
         return deviceA.getDeviceName();
       }
  };
  return module;
});

module_b.js

// Implementation for API B
define(function() {
  var module = {
      getName: function() {
         // could also potentially be a web service call
         return deviceB.getName;
       }
  };
  return module;
});

: .

. , API . DRY.

, - , , Js.

?

+5
3

, , , . "API, " , .

, , say getName C, module_c.js .

IMO , .

+3

, - , ! JS, .

i , , JS.

:

  • , -.
  • , " ".
  • , , .
  • , ,
  • (jQuery, dojo, mootools ..), ( API)
  • , / API ( ), "" API, API, , .

, ( ), , :

+4

I would choose a modular solution. Although there is no built-in way to execute contracts, you can still decide one, and then switch to TDD and create a test package that checks the conformance of the module interfaces.

Then your test suite basically fulfills the role that compilation will be in a language with explicit interfaces: if the interface is not properly implemented, it will complain.

+2
source

All Articles