base_nodejs_library
v1.0.26
Published
Base node.js library for all common features
Downloads
728
Readme
base_nodejs_library
This npm package provides a set of utilities for Node.js applications, including date formatting, random number generation, simplified HTTP status responses, AWS S3 bucket operations, and input validation. This package is ideal for developers looking to streamline common backend functionalities.
Features
- Date Formatting: Convert current date and time to a database-friendly format.
- Random Number Generation: Generate a random number within a given range.
- HTTP Status Responses: Easily send HTTP responses with predefined messages.
- AWS S3 Operations: Handle file uploads, downloads, and deletions on AWS S3.
- Input Validation: Validate required fields and check password confirmations.
Installation
Install the package via npm:
npm i base_nodejs_library
Detailed Function Descriptions
# dBDateFormatModule
dBDateFormatModule
Description: Converts the current date and time into a string formatted for database storage.
Usage:
import { dBDateFormatModule } from 'base_nodejs_library'
# randomNumberModule
randomNumberModule
import { randomNumberModule } from 'base_nodejs_library';
const randomNumber = randomNumberModule(1, 100);
Parameters:
Parameter | Description | Required
Min | Minimum value | Yes
Max | Maximum value | Yes
Description:
The randomNumberModule function is a utility designed to generate a random integer within a specified range. This function is useful in various scenarios within a Node.js application where randomization is required, such as generating random IDs, selecting random elements from a list, or for use in simulations and games.
Usage:
import { randomNumberModule } from 'base_nodejs_library';
const randomNumber = randomNumberModule(1, 100);
# HTTP Response Functions
Each HTTP response function formats a response object according to the HTTP status code it represents.
Common Parameters:
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message or data to send. | Yes
Example Usage:
# generateBadRequestResponse
import { generateBadRequestResponse } from 'base_nodejs_library';
Description:
The generateBadRequestResponse function is a utility designed for Node.js applications to uniformly handle scenarios where an incoming request is improperly formed. This function facilitates sending standardized HTTP 400 (Bad Request) responses, which notify the client that the server cannot process the request due to client-side errors, such as malformed request syntax, invalid request message parameters, or deceptive request routing.
Example Usage:
generateBadRequestResponse(res, data);
# generateUnauthorizedResponse
import { generateUnauthorizedResponse } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message. | Yes
Description :
The generateUnauthorizedResponse function is designed to facilitate the generation of HTTP responses specifically for unauthorized access scenarios in Node.js applications. It uses the HTTP status code 401 to indicate that the request has not been fulfilled because it lacks valid authentication credentials for the target resource.
Example Usage:
generateUnauthorizedResponse(res, data);
# generateBadGatewayResponse
import { generateBadGatewayResponse } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message. | Yes
Description:
The generateBadGatewayResponse function is a utility crafted for Node.js applications to standardize the process of responding with HTTP 502 (Bad Gateway) errors. This response is typically used to indicate issues with an upstream server or service that a gateway or proxy server, through which the request was routed, uses to handle the request.
Example Usage:
generateBadGatewayResponse(res, data);
# generateForbiddenErrorResponse
import { generateForbiddenErrorResponse } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message. | Yes
Description:
The generateForbiddenErrorResponse function is designed for use in Node.js applications to efficiently handle and respond with HTTP 403 (Forbidden) status codes. This status is used when the server understands the request but refuses to authorize it. If authentication credentials are provided, a 403 response indicates that authorization has been refused for those credentials.
Example Usage:
generateForbiddenErrorResponse(res, data);
# generateErrorResponse
import { generateErrorResponse } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message. | Yes
Description:
The generateErrorResponse function is tailored for Node.js applications to standardize the generation of HTTP 500 (Internal Server Error) responses. This response code is typically used when an unexpected condition was encountered and no more specific message is suitable, indicating an issue on the server side that prevents it from fulfilling the request.
Example Usage:
generateErrorResponse(res, data);
# generateSuccessResponse
import { generateSuccessResponse } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The message. | Yes
Description:
The generateSuccessResponse function is specifically designed for Node.js applications to uniformly handle and communicate successful operations via HTTP 200 (OK) responses. This function facilitates sending back a positive response with a customizable message, indicating that the request has been successfully processed.
Example Usage:
generateSuccessResponse(res, data);
# generateSuccessResponseWithData
import { generateSuccessResponseWithData } from 'base_nodejs_library';
Parameter | Description | Required
response | The response object from Express. | Yes
data | The data. | Yes
Description:
The generateSuccessResponseWithData function in Node.js applications standardizes the way successful operations are communicated back to clients. It uses the HTTP 200 (OK) status code to signify that the request has been successfully executed and also includes additional data that may be pertinent to the operation.
Example Usage:
generateSuccessResponseWithData(res, data);
############ End HTTP Response Functions
# capitalizeFirstLetter
import { capitalizeFirstLetter } from 'base_nodejs_library';
Parameter | Description | Required
sentence | The string | Yes
Description:
The capitalizeFirstLetter function is a straightforward utility designed to modify a given string by capitalizing the first letter. This function is particularly useful in scenarios where text formatting is important, such as formatting user input for names, places, or any other data that requires a standardized appearance.
Example Usage:
capitalizeFirstLetter(sentence)
# checkRequiredValidation
import { checkRequiredValidation } from 'base_nodejs_library';
Parameter | Description | Required
data | The object. | Yes
Description:
"The `checkRequiredValidation` function is an essential part of the utility library, designed to validate various API input parameters based on predefined rules. It supports validation for required fields, specific length requirements, and password confirmation checks, ensuring that input data meets your application's requirements before processing."
Example Usage:
checkRequiredValidation(dataToValidate).then().catch()
# extractKeyFromObjectUrl
import { extractKeyFromObjectUrl } from 'base_nodejs_library';
Parameter | Description | Required
objectUrl | The string | Yes
Description:
"The extractKeyFromObjectUrl function is designed to extract a key or identifier from a URL's pathname, primarily used when working with URLs that point to objects in a storage service like AWS S3. This utility is especially useful in scenarios where applications interact with cloud storage services and need to parse object keys from provided URLs."
Example Usage:
extractKeyFromObjectUrl(objectUrl)
# uploadFiles3Bucket
import { uploadFiles3Bucket } from 'base_nodejs_library';
Parameter | Description | Required
Region | AWS region | Yes
AccessKey | AWS access key | Yes
SecretKey | AWS secret key | Yes
BucketName | Name of the S3 bucket | Yes
LocalStorageFilesPath | Local storage path | Yes
FileObjectPath | Path of the file object | Yes
Description:
The uploadFiles3Bucket function is an asynchronous utility designed for uploading files to an AWS S3 bucket. It is a comprehensive function capable of handling single or multiple file uploads, managing local and remote file storage paths, and providing feedback on the upload process.
Example Usage:
await uploadFiles3Bucket(region, accessKey, secretKey, bucketName, localStoragePath, fileObjectPath);
# deleteFileFroms3Bucket
import { deleteFileFroms3Bucket } from 'base_nodejs_library';
Parameter | Description | Required
Region | AWS region | Yes
AccessKey | AWS access key | Yes
SecretKey | AWS secret key | Yes
BucketName | Name of the S3 bucket | Yes
FilePath | Path of the file object | Yes
Description:
The `deleteFileFroms3Bucket` function is an essential utility for managing AWS S3 storage within Node.js applications. It allows developers to delete files from an S3 bucket programmatically, using simple and secure access methods.
Example Usage:
deleteFileFroms3Bucket(awsConfig.Region, awsConfig.AccessKey, awsConfig.SecretKey, awsConfig.BucketName, filePath)
.then().catch()
# twilioSendOTP
import { twilioSendOTP } from 'base_nodejs_library';
Parameter | Description | Required
to | String | Yes
mode | Twilio Channel | Yes
config | TwilioConfig The object. | Yes
| {
| accountSid : ""
| template : ""
| authToken : ""
| }
Description:
The twilioSendOTP function is used to send a One-Time Password (OTP) via Twilio's communication channels. This function is part of the base_nodejs_library package and requires several parameters to configure and send the OTP correctly.
Parameters
to (String): The recipient's phone number or email address to which the OTP will be sent. This parameter is mandatory.
mode (String): The Twilio channel through which the OTP will be sent. It can be set to options like SMS, Email, etc. This parameter is mandatory.
config (Object): The configuration object that includes Twilio credentials and the OTP template. This object is mandatory and should include the following properties:
accountSid (String): Your Twilio Account SID.
authToken (String): Your Twilio Auth Token.
template (String): The template for the OTP message.
Example Usage:
twilioSendOTP({
to: recipient,
mode: channel,
config: twilioConfig
})
.then(response => {
})
.catch(error => {
});
# twilioVerifyOTP
import { twilioVerifyOTP } from 'base_nodejs_library';
Parameter | Description | Required
to | String | Yes
mode | Twilio Channel | Yes
config | TwilioConfig The object. | Yes
| {
| accountSid : ""
| template : ""
| authToken : ""
| }
Description:
The twilioVerifyOTP function is used to verify a One-Time Password (OTP) sent via Twilio's communication channels. This function is part of the base_nodejs_library package and requires several parameters to verify the OTP correctly.
Parameters
to (String): The recipient's phone number or email address to which the OTP was sent. This parameter is mandatory.
mode (String): The Twilio channel through which the OTP was sent. It can be set to options like SMS, Email, etc. This parameter is mandatory.
config (Object): The configuration object that includes Twilio credentials and the OTP template. This object is mandatory and should include the following properties:
accountSid (String): Your Twilio Account SID.
authToken (String): Your Twilio Auth Token.
template (String): The template for the OTP message.
Example Usage:
twilioVerifyOTP({
to: recipient,
mode: channel,
otp: otpCode,
config: twilioConfig})
.then(response => {})
.catch(error => {});
# getContextFromEnvironment
import { getContextFromEnvironment } from 'base_nodejs_library';
Description:
The `getContextFromEnvironment` function is designed to determine the current operating environment of an application based on the provided `environment` string. This function is useful for configuring different behaviors or settings depending on whether the application is running in a production, beta, or development environment.
Parameters:
| Parameter | Description | Required |
|--------------|----------------------------------------------------------|----------|
| environment | A string representing the environment (e.g., 'prod', 'beta', 'dev'). | Yes |
Example Usage:
const environment = process.env.ENVIRONMENT || '';
// Pass the environment variable to the function
const context = getContextFromEnvironment(environment);
# getContextFromEnvironment
# applyPagination
import { applyPagination } from 'base_nodejs_library';
Description:
The `applyPagination` function is a utility designed to paginate an array of data. It returns a subset of the data based on the specified page number and limit of items per page. This function is useful for implementing pagination in applications where large datasets need to be displayed in manageable chunks.
Parameters:
Parameter | Description | Required
----------|-------------|---------
data | Array of data to paginate. | Yes
page | The page number to retrieve. | Yes
limit | The maximum number of items per page. | Yes
Example Usage:
const paginatedData = applyPagination(data, page, limit);
# applyPagination
# // removeKeysFromJoinData - Start
import { removeKeysFromJoinData } from 'base_nodejs_library';
Description:
The removeKeysFromJoinData function is designed to transform an object by removing its keys and returning an array of its values. This function is useful for scenarios where you need to work with a list of values extracted from an object, such as processing joined data in a relational context.
Parameter | Description | Required
data | The object to transform. | Yes
Example Usage:
const joinedData = {
key1: { id: 1, name: 'Alice' },
key2: { id: 2, name: 'Bob' },
key3: { id: 3, name: 'Charlie' }
};
const valuesArray = removeKeysFromJoinData(joinedData);
# checkEmptyString
import { checkEmptyString } from 'base_nodejs_library';
Description:
The checkEmptyString function is designed to determine if a given input is an empty string, null, or undefined. This utility function is useful for validating input data and ensuring that the provided data is not empty or invalid.
Parameters:
Parameter | Description | Required
data | The input data to be checked. | Yes
Example Usage:
const emptyString = "";
const nullValue = null;
const undefinedValue = undefined;
const nonEmptyString = "Hello, World!";
console.log(checkEmptyString(emptyString)); // Output: true
console.log(checkEmptyString(nullValue)); // Output: true
console.log(checkEmptyString(undefinedValue)); // Output: true
console.log(checkEmptyString(nonEmptyString)); // Output: false
# checkEmptyString -END
# getYearAndWeekNumber - Start
import { getYearAndWeekNumber } from 'base_nodejs_library';
Description:
The getYearAndWeekNumber function is designed to retrieve the current year and the ISO week number for the current date. This function is useful for applications that require date-based operations, scheduling, or time tracking.
Parameters:
Parameter | Description | Required
None | N/A | N/A
Example Usage:
const { year, weekNumber } = getYearAndWeekNumber();
# getYearAndWeekNumber - End
# removeSpecialCharactersFromNormalString - Start
import { removeSpecialCharactersFromNormalString } from 'base_nodejs_library';
Description:
Removes specific special characters from a string.
Parameters:
Parameter | Description | Required
str | The input string | yes
Example Usage:
removeSpecialCharactersFromNormalString(exampleString)
# removeSpecialCharactersFromNormalString - End
# removeSpecialCharactersFromURL - Start
import { removeSpecialCharactersFromURL } from 'base_nodejs_library';
Description:
Removes specific special characters from a URL string.
Parameters:
Parameter | Description | Required
str | The input string | yes
Example Usage:
removeSpecialCharactersFromURL(exampleString)
# removeSpecialCharactersFromURL - End
# removeAccents - Start
import { removeAccents } from 'base_nodejs_library';
Description:
Removes accents from a string.
Parameters:
Parameter | Description | Required
str | The input string | yes
Example Usage:
console.log(removeAccents(exampleString));
# removeAccents - End
# normalizeDataNFD - Start
import { normalizeDataNFD } from 'base_nodejs_library';
Description:
Normalizes a string by removing accents using the NFD normalization form.
Parameters:
Parameter | Description | Required
str | The input string | yes
Example Usage:
console.log(normalizeDataNFD(exampleString));
# removeAccents - End
# normalizeString - Start
import { normalizeString } from 'base_nodejs_library';
Description:
Normalizes a string by removing accents and special characters using the NFD normalization form.
Parameters:
Parameter | Description | Required
str | The input string | yes
Example Usage:
console.log(normalizeString(exampleString));
# removeAccents - End
# runAnyQuery - Start
import { runAnyQuery } from 'base_nodejs_library';
Description:
This Database Query Utility provides a convenient way to run SQL queries using MySQL in a Node.js environment with TypeScript. The core function runAnyQuery allows you to execute any SQL query while ensuring type safety and error handling through promises.
Parameters:
Parameter | Description | Required
dbCon | MySQL connection object | yes
sql | SQL query string | yes
values | Array of values to be injected into the query | yes
Example Usage:
runAnyQuery(dbCon, sql, values).then(()=>{}).catch(()=>{})
# selectQueryModule - Start
import { selectQueryModule } from 'base_nodejs_library';
Description:
The selectQueryModule function allows you to run a SELECT SQL query with dynamic clauses such as WHERE, GROUP BY, ORDER BY, and LIMIT. It returns a promise that resolves with the query results or an error message.
Parameters:
Parameter | Description | Required
dbCon | MySQL connection object | yes
table | Table name to perform the query on | yes
columns | Comma-separated list of columns to retrieve | yes
where | WHERE clause to filter results (optional) | No
groupBy | GROUP BY clause to group results (optional) | No
orderBy | ORDER BY clause to sort results (optional) | No
limit | LIMIT clause to restrict the number of results | No
values | Array of values to be injected into the query | yes
Example Usage:
selectQueryModule(dbCon, table, columns, where, groupBy, orderBy, limit, values).then((result)=>{}).catch((error) => {});
# generateServerErrorResponse - Start
import { generateServerErrorResponse } from 'base_nodejs_library';
Description:
The generateServerErrorResponse function is a utility used in Express.js to generate consistent server error responses in JSON format. It accepts the response object, an error message, and an HTTP status code, and returns a structured error response in the JSON format.
Parameters:
Parameter | Description | Required
response | The Express response object used to send the error response | yes
data | The error message or description to send | yes
statusCode | HTTP status code to send along with the response | yes
Example Usage:
generateServerErrorResponse(res, data, statusCode);
# generateServerErrorResponse - Start
import { generateServerErrorResponse } from 'base_nodejs_library';
Description:
The generateServerErrorResponse function is a utility used in Express.js to generate consistent server error responses in JSON format. It accepts the response object, an error message, and an HTTP status code, and returns a structured error response in JSON format.
Parameters:
Parameter | Description | Required
response | The Express response object used to send the error response | yes
data | The error message or description to send | yes
statusCode | HTTP status code to send along with the response | yes
Example Usage:
generateServerErrorResponse(res, 'Internal server error', 500);
# isValidTime - Start
import { isValidTime } from 'base_nodejs_library';
Description:
The isValidTime function checks whether a given string is a valid time in HH:MM format.
Parameters:
Parameter | Description | Required
time | The time string in HH:MM format | yes
Example Usage:
const isValid = isValidTime(time);
# isValidEndTime - Start
import { isValidEndTime } from 'base_nodejs_library';
Description:
The isValidEndTime function checks if the endTime is valid and comes after the startTime.
Parameters:
Parameter | Description | Required
startTime | The time string in HH:MM format | yes
endTime | The time string in HH:MM format | yes
Example Usage:
const isValid = isValidEndTime(startTime,endTime);
# isPastDate - Start
import { isPastDate } from 'base_nodejs_library';
Description:
The isPastDate function checks if a given date is in the past.
Parameters:
Parameter | Description | Required
date | The date object or date string to be checked | yes
Example Usage:
const isInPast = isPastDate(date);
# validateAndConvertDate - Start
import { validateAndConvertDate } from 'base_nodejs_library';
Description:
The validateAndConvertDate function validates and converts a date string to a Date object.
Parameters:
Parameter | Description | Required
dateStr | The string representing a date | yes
Example Usage:
const date = validateAndConvertDate(dateStr);
# convertDateTimeFormat - Start
import { convertDateTimeFormat } from 'base_nodejs_library';
Description:
The convertDateTimeFormat function converts a Date object to a string in the format YYYY-MM-DD HH:MM:SS.
Parameters:
Parameter | Description | Required
date | The Date object | yes
Example Usage:
const formattedDate = convertDateTimeFormat(date);
# isValidS3Url - Start
import { isValidS3Url } from 'base_nodejs_library';
Description:
The isValidS3Url function checks if a given URL is a valid Amazon S3 URL.
Parameters:
Parameter | Description | Required
url | The S3 URL to validate | yes
Example Usage:
const isValidUrl = isValidS3Url(url);
# generateSuccessFullResponse - Start
import { generateSuccessFullResponse } from 'base_nodejs_library';
Description:
The generateSuccessFullResponse function generates a standard successful response with a message and optional data.
Parameters:
Parameter | Description | Required
data | Optional data to be returned with response | no
message | A success message | yes
Example Usage:
const response = generateSuccessFullResponse(message, data);