jeudi 25 février 2021

Should I opt for code repetition or consolidation with api service - JS

I'm working on a large CMS system where a particular module and its submodules take advantage of the same backend API. The endpoint is exactly the same for each submodule aside from its "document type".

So a pattern like this is followed:

api/path/v1/{document-type}

api/path/v1/{document-type}/{id}

api/path/v1/{document-type}/{id}/versions

As time goes on the number of modules that use this API grows and I am left with many, many redundant api services that implement 7 CRUD methods:

getAllDocType1s() {...}
getDocType1(id) {...}
getDocTypeVersion(id, versionId) {...}

etc...

I came to a point where I decided to make a single service and do something like this:

const BASE_URL = window.config.baseUrl + Const.API_ENDPOINT;
const ENDPOINTS = {
  "DOCTYPE1": "/v1/DOCTYPE1/",
  "DOCTYPE1": "/v1/DOCTYPE1/",
  "DOCTYPE3": "/v1/DOCTYPE3/",
  "DOCTYPE4": "/v1/DOCTYPE4/",
}

getAllDocuments(docType, headers = {}, params = {}, timeout = Const.TIMEOUTS.NETWORK_STANDARD) {
  let endpoint = BASE_URL + ENDPOINTS[docType.toUpperCase()];
  return http.get(endpoint, {headers, params, timeout})
      .then(response => {
        if (Array.isArray(response.data)) return response.data;
      })
      .catch(error => {
        console.error("FAILED TO LOAD CMS DOCUMENT LIST");
        throw error;
      });
}
...other methods

Where a type is specified and a mapped endpoint is used to build the path.

This reduces all of the document api services down to one. Now this is more concise code wise, but obviously now requires an extra parameter and the terminology is more generic:

getAllDocType1s --> getAllDocType

and it's a bit less 'idiot-proof'. What makes me insecure about the current way it is written is that there are 6 modules that use this API and the same 7 methods in each service.

The questions I keep asking myself are:

  • Am I bordering anti-pattern with the dynamic functions?

  • What if I had 10+ modules using the same API?

  • Is this a backend design problem? As in, should docType be a parameter?

Aucun commentaire:

Enregistrer un commentaire