A set of general utilities for Cybearl projects.
This package includes multiple centralized utilities for the Cybearl application and API service. It is designed to be a single package that can be used in both the client and server side of the application. It is also designed to be well-optimized and well-documented for easy use.
// With npm
$ npm install @cybearl/cypack
// With yarn
$ yarn add @cybearl/cypackAnd that's it! You can now use our utilities in your project.
Note that the package is divided into three modules:
backend(@cybearl/cypack/backend): Contains utilities that are meant to be used in the backend.frontend(@cybearl/cypack/frontend): Contains utilities that are meant to be used in the frontend.main(@cybearl/cypack): Contains utilities that can be used in both the client and server side of the application.
Bench: A class that provides a simple way to benchmark functions.
Note that these are stored inside a crypto object that is exported from the package.
aes256Gcm(AES-256-GCM symmetric encryption):encrypt: Encrypts data using AES-256-GCM symmetric encryption.decrypt: Decrypts data using AES-256-GCM symmetric encryption.decryptPayload: Decrypts a payload that contains the initialization vector, ciphertext, and authentication tag.
CyBuffer: A class that extends the Uint8Array class with additional methods to read and write data.
generateCGASStatus: Generates a Cybearl General API System (CGAS) status object.
Contains utilities to get the hostname and other host-related information.
getHostname: Get the name of the host on which the application is running.
Contains a simple multi-level logger that logs to the console based on Winston.
logger: A simple multi-level logger that logs to the console based onWinston.
Contains utilities to get the Next.js server and other Next.js-related information.
NextApiWrapper: A class that wraps the Next.js API route handler (specifically for page router):function read({ req, wrapper }: NextApiMethodInput) { if (!req.query.blabla) return wrapper.errorResponse(AppErrors.UNAUTHORIZED) return wrapper.successResponse(200, status) } export default async function handler(req: NextApiRequest, res: NextApiResponse) { const wrapper = new NextApiWrapper(req, res, { read }) await wrapper.run() }
nextAuthApiWrapper: Similar toNextApiWrapper, but with built-in NextAuth support (specifically for page router).
getCGASStatus: Returns the current status of the application, or the application marker only if specified, in the Cybearl General API System (CGAS) format.fallbackCGASStatus: The fallback CGAS status, used when the CGAS API is not available.
Contains utilities to manipulate URLs.
addParamsToUrl: Allows to add query parameters to a URL.currentUrlOrigin: Get the current URL origin or null if it's not available.
arrayEqual: Compares two arrays for equality.isClient: Check if the code is running on the client.isServer: Check if the code is running on the server.
CyCONSTANTS: Multiple constants used throughout the application:- Security:
HASH_SALT_ROUNDS. - User-related fields such as
(MIN / MAX)_PASSWORD_LENGTHetc.. - Image and video sizes specifically for image optimization.
- Security:
Country: An object containing all countries with their respective details (name, code, continent, etc.), based on the ISO 3166-1 standard (alpha-2).formatCountryName: Formats a country name from camel case to a spaced name.COUNTRIES_SELECT_FIELD: An array of countries formatted for use in select fields.getCountryNameFromCode: Get the country name from its ISO 3166-1 alpha-2 code.
Contains a set of base error that follows the Cybearl error format, and other error-related utilities.
formatErrorResponse: Formats an error response object.stringifyError: Stringifies an error object.parseCRUDError: Parse the error of a CRUD call and return a standardized error.formatMessageAsStringifiedError: Formats a message and an error object into a JSON string that follows theFailedRequeststandard.BaseError: The base error class that all Cybearl errors inherit from, don't forget to do:To be sure that you respect the error format.export const AppErrors = { ...BaseErrors, // Add your custom errors here } as const satisfies Record<string, ErrorObj>
Contains a set of utilities to format numbers, time, and other values.
isValidIntId: Validate a direct ID parameter (as integer for SQL DBs etc..).isValidSlug: Validates a slug.formatUnit: Format a number with an attached unit + an optional time unit.formatHRTime: Format a high-resolution time, into a responsive string with the en-US locale format.formatTime: Format a time in milliseconds into a responsive string with the en-US locale format.formatPercentage: Formats a number as a percentage.truncateString: Truncate a string to a specified length.parseQueryNumberArray: Parse a query containing either a number or numbers separated by commas and returns an array of numbers.parseQueryStringArray: Parse a query containing either a string or strings separated by commas and returns an array of strings.slugifyName: Slugify a given name with support for automatic number incrementing.formatBytes: Formats a number of bytes into a human-readable string with appropriate units.
Contains utilities to parse and stringify JSON objects.
formatJson: Format a JSON object with indentation.stringify: Stringify a JSON object with support for BigInt and functions.
Contains utilities to perform mathematical operations.
mapRange: Maps a number from one range to another.safeAverage: Safely creates an average value based on a total and count coming from a Lucid ORM / SQL query result.safePercentage: Safely creates a percentage based on a numerator and denominator coming from a Lucid ORM / SQL query result.
Contains utilities to create middleware functions (for Next.js, etc.).
fullyPermissiveCspHeader: A Content Security Policy (CSP) header that allows everything, used for development.
Contains utilities to manipulate strings.
convertErrorToString: Safely converts any error into a string for parsing/searching.decodeObjectURIComponents: Decodes all components of an object as URI components (e.g., for decoding Next.jsreq.query).
Contains utilities to manipulate CSS styles.
shadeColor: Shades a color by a percentage.
Bit: A single bit value used by CyBuffer.BenchmarkResult: The type of the benchmark function result.BenchmarkResults: An object containing multiple benchmark results, ordered by functions.CGASStatusString: The type for the CGAS status string (enabled,disabled,in-maintenance,in-development).CGASStatus: The Cybearl General API System (CGAS) status response.Endianness: The endianness (LEorBE).ErrorObj: The type definition for an error object.StringEncoding: The available string encoding instruction for theCyBufferstring methods.SuccessfulRequest: The type for a successful request, containing the data of type T.FailedRequest: The type for a failed request, containing the error message and the error object.RequestResult: Returns a failed request in case thesuccessfield is set tofalse, otherwise returns a successful request with a data object of type T.
N/A
