mercredi 26 février 2020

How to implement CRUD service in JS (Singleton?)

after reading that Singletons are evil over and over again, i'm not sure how to implement a class that handles "crud" operations of a dataset, that contains some settings on a server.

The dataset does not really exists on the client side. The client only see its name and can initiate the server to load, save or delete its datasets.

To be indipendent on the server, the server instance will be "injected". The user can pass the name of the concerned Dataset.

class DataSet {
  constructor(name, server) {
    this.server = server;
    this.name = name;
  }

  async load() {
    this.server.sendLoadCommand(this.name);
  }

  async delete() {
    this.server.sendDeeleteCommand(this.name);
  }

  // ...
}

In most cases only one method is needed at a time. Then the object is no longer required.

new Dataset("foo").delete();

Since theoretically the same object can be used every time, a global manager (singleton) could be used.

const window.dataSetManager = {

  async load(name) {
    this.server.sendLoadCommand(this.name);
  }

  async delete(name) {
    this.server.sendDeeleteCommand(this.name);
  }

  // ...
}

window.itemManager.server = server;

Can anyone tell me the advantages of one or both ways?

Many thanks, Meisenmann

Aucun commentaire:

Enregistrer un commentaire