Ad

JavaScript - Add To Class Assignment After Class Initiation

I am trying to manipulate an already initialised JavaScript class. The class is a http request library and I am trying to create a "base" initiation that will meet all my HTTP request needs, then be able to extend the initialised JavaScript class at the individual request layer. An example would be:

const Request = require('my-library');

const requestBaseConnection = new Request(
  {
    httpsProxy: (process.env.HTTPS_PROXY ? process.env.HTTPS_PROXY : ''),
    retryOptions: {
      retries: 0,
      retryableMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],
      statusShouldRetry: (status) => (status >= 500) && (status <= 599),
    },
    timeout: 100000,
  }
);

const jenkinsServicesDevAxway = () => {

  const token = 'abc';
  const url = 'https://url.com';

  let requestSpecifics = { headers: {'X-API-Key': `${token}`}, baseURL: `${url}` };

  const connection = { ... requestBaseConnection, ...requestSpecifics };

  return connection
};


module.exports = {
  jenkinsServicesDevAxway
};

As you can see I thought this is whee the JavaScript Spread operator would maybe help me? As I thought it would concatenate the two objects together. It doesn't seem to be working thought as when I console.log(connection) I get Connection: [object Object].

What I would hope for would be it would add the:

{ headers: {'X-API-Key': `${token}`}, baseURL: `${url}` }

to the initiated class, so the class Request would now look like this:

  {
    httpsProxy: (process.env.HTTPS_PROXY ? process.env.HTTPS_PROXY : ''),
    retryOptions: {
      retries: 0,
      retryableMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],
      statusShouldRetry: (status) => (status >= 500) && (status <= 599),
    },
    timeout: 100000,
    baseURL: 'https://url.com',
    headers: {'X-API-Key': abc }
  }

Is there a good/better way of doing what I am trying to achieve?

Ad

Answer

I think you're looking for something like

const Request = require('my-library');

const baseRequestOptions = {
  httpsProxy: (process.env.HTTPS_PROXY ? process.env.HTTPS_PROXY : ''),
  retryOptions: {
    retries: 0,
    retryableMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],
    statusShouldRetry: (status) => (status >= 500) && (status <= 599),
  },
  timeout: 100000,
};

function jenkinsServicesDevAxway(token, url) {
  return new Request({
    ...baseRequestOptions,
    headers: {
      'X-API-Key': token
    },
    baseURL: url,
  });
}

module.exports = {
  jenkinsServicesDevAxway
};

// …
jenkinsServicesDevAxway('abc', 'https://url.com');
Ad
source: stackoverflow.com
Ad