Javascript

Easy steps to create source endpoints with base url’s in react or any spa applications using ES6 tagged templates as a project utility and maintainbilty

Hello,

Here I would like to share with you a very handy and new innovative approach using ES6 Tag Literals template to ease of creating the base URL’s for use a single source of truth defined as library constants or utility code to refer as the single page application grows.

Let’s get hand dirty and mind free from hassle of maintaining and forming lines cluttered code and creating mess in many files as web application grows.

Hope you understand what I mean, developers get frustrated to follow the best practice as in tight project deadlines,

Heads up on I am currently using 2Factor.in endpoints in this post as I were using part of the project implementation, we will head in list out numbers as steps needs to follow for the quick implementation:

  1. We will save API key and API base URL in env file, (hope you are aware were it will lies in your project code, basically it lies at the core level of project director with named and with extension exactly, .env
SITE_2FACTORIN_API_BASE_URL=https://2factor.in/API/V1/
SITE_2FACTORIN_API_KEY=XXXXXX-dde0-23ec-XXXXXXXXXX

2. As I were using Nextjs, so I need to configure these env variables in next.config.js file to export it to the FE side contants(.js) file:

//next.config.js
module.exports = {
  publicRuntimeConfig: {
    SITE_2FACTORIN_API_BASE_URL: process.env.SITE_2FACTORIN_API_BASE_URL,
    SITE_2FACTORIN_API_KEY: process.env.SITE_2FACTORIN_API_KEY,
  },
};

3. Next we need to import publicRuntimeConfig object in our constants(.js) file

import { publicRuntimeConfig } from "./env.settings";

I am importing from .env.settings files which is actually using nextjs getConfig method to export publicRuntimeConfig variable, I am skipping that step to show here, once you search for docs on next/config you will get an idea what we are doing here.

4. Main part here it comes in contants.js file:

export const f2param1 = (param) => param || 1234657890;
export const f2param2 = (param) => param || "myTemplateName-OTP";

export function tagTemplate2FactorAPI(strings, param1, param2) {

  const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
  const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';

  let str0 = strings[0] || ""; // "That "
  let str1 = strings[1] || ""; // " is a "
  let str2 = strings[2] || ""; // "."

  // We can even return a string built using a template literal
  return `${prefixBaseUrl}${str0}${param1 || ''}${str1}${param2 || ''}${str2}`;
}

export const factor2API_Endpoint = {
  CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
  SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN`,
  SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN/${f2param2()}`,
  SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${f2param1()}/${f2param2()}`,
  CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
  SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
  SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};

console.log(factor2API_Endpoint.SEND_OTP_SMS);
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE);
console.log(factor2API_Endpoint.SEND_VERIFY_SMS);

This is how the final code looks, but there is a catch in this code, just need to handle of passing the params dynamically to the constants property of the object, otherwise with the fixed 2 params in same file would do the trick.

Will share once I got the way of passing dynamic params values to object property in template literal invocation line.

—— Here I found it the other approach —- Edited: 00:44 (after few mins of publishing this post after above approach shared 🙂 )

export function tagTemplate2FactorAPI(strings, ...keys) {

  const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
  const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';

  return (function (...values) {
    let dict = values[values.length - 1] || {};
    let result = [strings[0]];
    keys.forEach(function (key, i) {
      let value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });

    result.unshift(prefixBaseUrl); //added this line to prefix with base url path
    return result.join('');
  });
}

export const factor2API_Endpoint = {
  CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
  SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN`,
  SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN/${1}`,
  SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${0}/${1}`,
  CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
  SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
  SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};

 console.log(factor2API_Endpoint.SEND_OTP_SMS(12311312, 'newTemplate-newOTP'));
 console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE(5656565, 'newTemplate-newOTP'));
 console.log(factor2API_Endpoint.SEND_VERIFY_SMS(456646545, 'newTemplate-newOTP'));

Output log of the above code:

Solution, I found right after reading the basic guide on Tagged template on Mozilla documentation on Tagged Templates

Thanks for reading.

Happy Learning.

admin

Recent Posts

The Ultimate Guide to Effective Meetings

In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…

1 week ago

From Mine to Market: How Gold Is Mined, Refined, and Sold in Shops

Gold is one of the most coveted precious metals in the world, adored for its…

1 week ago

The Historical Journey of Gold: From Ancient Civilizations to Modern Times

Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…

1 week ago

How to Onboard an Intern in Small, Individual-Based Company

How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…

2 months ago