0

I'm building an app in JavaScript (ES6). I'm more familiar with C#, so if my lingo is a bit off, I apologize.

Anyways, in my app, I want to create a service that supports other services. Basically, when my service is created, I want to dynamically load some services that implement my "interface". That "interface" has a single function named "sendMessage". Then, when I call MyService.sendMessage('someMessage'), that message will automatically get sent out via the registered services. I'm trying to accomplish something like this:

const MyService {
  initialize: function() {
    this.services = [];

    // Somehow load services here

    // This function will send the message to the plugins
    this.sendMessage = function(msg) {
      for (let service in services) {
        service.sendMessage(msg);
      }
    };
  }
};

The above doesn't work because, the services aren't getting populated in anyway. I know that JavaScript doesn't have an interface keyword like C#. For that reason, I know that I need a way to "register" services. My question But, I'm not sure how to do this.

How do I create a service such that a third-party developer can plugin to my service?

user70192
  • 13,786
  • 51
  • 160
  • 240

3 Answers3

2

JavaScript doesn't have interface per se, but it sure has classes. (ES6)

So, what you can do is create a base-class such as this:

class BaseService {
    constructor(options) {
        // Handle options here
    }

    // Methods

    sendMessage(msg) {
        throw new Error(`sendMessage is not implemented in the base class. 
                         Please override this method in your extended class.`);
    }

    // Other Methods

    get name() {
        // 
    }
}

Next, if anyone wants to build a service for your app, like an SMS gateway provider, they can simply extend your BaseService class and implement their own sendMessage method.

Of course, you cannot stop them from not implementing that method. However, if they don't, an error will be thrown. Which I guess, provides a somewhat Interface like abstraction in JavaScript.

code
  • 2,115
  • 1
  • 22
  • 46
0

You can use http://www.typescriptlang.org/ for interfaces. ES6 'class' doesn't support interfaces, so typescript is your best way, unless you want to develop OOP infra by yourself.

bgauryy
  • 416
  • 3
  • 7
0

There is no Implementation of Interfaces in Javascript as it is a Dynamic language and not strongly typed as c#. You can check this answer which explains a work around for your question.

Hope this helps.