Utils bundle


Installation

Follow these steps to install and configure the Utils bundle :
Ref : Utils bundle documentation

Available functions

Base link : from "@phpcreation/frontend-utils-react-nextjs-bundle/utils

From /

import {
    errorHandler
} 

errorHandler

Logs and send error to sentry
Signature
errorHandler = (
  error: Error,
  message = "An error occurred : ",
)

Usage
try {
    await axios
        .get(informations)
        .then((res) => console.log(res));
} catch (err: any) {
      errorHandler(err, "Error getting status");
}


From /utils/functions

import {
  cn, 
  generateCsrfToken,
  generateJWT, 
  getFQCN,
  getNestedProperty,
  validateCsrfToken,
  verifyCsrfJwt
} 

cn

Concatenate strings. Generally used for tailwind classes
Signature
cn = (...args: string[])

Usage
classname={cn(
  "flex justify-center bg-phpc-blue",
  classNameFromProps
)}


generateCsrfToken

Generate a csrf token when the user logs in
Signature
function generateCsrfToken(response: Response | NextResponse, url: string): string

Usage
const token = generateCsrfToken(response, request.headers.get("referer") || "");


generateJWT

Generate a jwt token with the csrf token and the url as audience. It creates a jwt token with the csrf token and the url (https://example.com/page/3) as audience to confirm the token is used on the right page.
Signature
function generateJWT(csrfToken: string, url: string): string

Usage
const newJWT = generateJWT("galiuewbfliuewa" , "https://demo.inventory.phpreaction.phpr.link/fr/products");


getFQCN

Get the Fully Qualified Class Name
Signature
const getFQCN = (
  bui: IFQCN_BUI,
  Part: string | null,
  Element: string | null = ""
): string

Usage
const fqcn = {
  Bundle: "sidebarMenuBundle",
  Unit: "menu",
  Interface: "Listing",
};
const fqcnString = getFQCN(fqcn, "menu", "home-icon");


getNestedProperty

Get a nested property from an object
Signature
function getNestedProperty(obj: any, path: string): any

Usage
const object = {
  a: {
    b: "Get B", 
    c: "Get C"
  }
};
const nested = getNestedProperty({a: obj, "a.b");
// Get B


From /utils/helpers

import { 
  CallAPI,
  GetEnvironment,
  convertDateToFormat,
  encodeSpecialChar,
  formatNumbersSeparateThousands,
  limitSpecialChars,
  rateLimitByKey,
  sanitizeNumber,
  updateQuerystrings
} 

CallAPI

Structure to call the API
Signature
async function CallAPI(
  method: "GET" | "POST" | "PUT" | "DELETE",
  tenant: string,
  resource: string,
  parameters?: any,
  payload?: any,
  logRequest: boolean = false
): Promise<any>

Usage
const { data } = await CallAPI(
        "GET",
        "demo",
        CallAPIURL.products.get, 
        JSON.stringify({
          _locale: "fr_CA",
          sku: "123456"
        })
  );

const products123456 = data.response["hydra:member"][0];

const { data } = await CallAPI(
        "POST",
        "demo",
        CallAPIURL.products.get,
        "",
        JSON.stringify({
          name,
          quantity,
          sku
        })
      );

const product = data.response["hydra:member"];


GetEnvironment

Get the environment : dev | staging | prod
Signature
const GetEnvironment = (href: string): string

Usage
const environment = GetEnvironment("demo.dev.punch.phpr.link");
// dev


convertDateToFormat

Convert a date to our specific format (YYYY-MM-DD)
Signature
export function convertDateToFormat( date?: number, onlyDate?: boolean ): string

Usage
const date = convertDateToFormat(1741635184); // 2025-03-10


encodeSpecialChar

Encode special characters for security to avoid XSS attacks
Signature
function encodeSpecialChar(value: string): string

Usage
const encoded = encodeSpecialChar("<script>alert('XSS')</script>");
// &lt;script&gt;alert('XSS')&lt;/script&gt;


formatNumbersSeparateThousands

Format numbers to separate thousands
Signature
function formatNumbersSeparateThousands(value: number): string

Usage
const formatted = formatNumbersSeparateThousands(1234567890);
// 1,234,567,890


limitSpecialChars

Limit the special characters that can be used, for security purpose. Default accepeted special charaters are : +&-
Signature
limitSpecialChars(
  value: string,
  additionalSpecialChars?: string
): string | { validSpecialChars: string }

Usage
const limited = limitSpecialChars("Hello + - World!@#$%^&*()")
// Hello + - World


rateLimitByKey

Rate limit by key to avoid multiple requests. The key should be unique for each request and can be an id or an Ip adress for example.
Signature

function rateLimitByKey(
  key: string,
  limit: number = 3,
  duration: number = 10000 // 10 seconds
): {
    status: number;
    error: string;
}

Usage
const rateLimit = rateLimitByKey('1234567890');
// {status: 429, error: 'Too many requests'}
// or
// {status: 200, error: 'OK'}" 


sanitizeNumber

Sanitize a number to avoid SQL injection
Signature
function sanitizeNumber(
  value: string,
  min?: number | null,
  max?: number | null
): number | null

Usage
const sanitized = sanitizeNumber(1234567890);
// 1234567890


updateQuerystrings

Update the query strings variable to include or exclude a filter
Signature
function updateQuerystrings(
  includeAll: boolean,
  filters?: { key: string; value?: string | string[] }[]
): string

Usage
const updatedQuery = updateQuerystrings(false, { key: "status", value: "active" });
// ?status=active