@bgroup/helpers
v1.0.7
Published
The Helpers package is a set of utilities and functions designed to improve the efficiency and quality of application development application development This package is focused on simplifying common and repetitive tasks by providing predefined solutions
Downloads
2
Keywords
Readme
Helper Package
💌
The Helpers
package is a set of utilities and functions designed to improve the efficiency and quality of application
development. This package focuses on simplifying common and repetitive tasks by providing predefined solutions in key
development areas. Some of the highlights of this package's functionality include. include:
md5
function 💡
The md5
function is a method that takes care of calculating the MD5 hash of a given text string and returns the hash
in lowercase hexadecimal format.
Import
import { MD5 } from '@bgroup/helpers/md5';
This function uses the MD5 implementation to generate the corresponding hash of the provided string. The MD5 hash MD5 is a widely used algorithm for creating cryptographic representations of text strings, which makes it useful for encrypting passwords. useful for encrypting passwords and other sensitive data.
Parameters
str
(string): The input string to be hashed.
Returns
- (string): The MD5 hash of the input string in lowercase hexadecimal format.
Usage Example
const hash = md5('mySecretString');
console.log(hash); // Your output: ``5f4dcccc3b5aa765d61d8327deb882cf99```; // Your output: ``5f4dcc3b5aa765d61d8327deb882cf99```.
The md5 function is useful when you need to store passwords or sensitive data securely, since the resulting hash resulting hash is difficult to revert to get the original string.
Object Utils
🎯
The Utils
object provides utility methods for data manipulation and processing.
Import
import { Utils } from '@bgroup/helpers/utils';
Its functionality focuses on the following areas:
Token Generation.
The generateToken(length?: any, onlyNumbers?: any): string
method generates random tokens of the specified length. You
can choose whether you want the token to consist only of numbers by setting the onlyNumbers
parameter to true
.
MD5 hashing
The md5(str: string): string
method allows you to calculate the MD5 hash of a text string. This is useful for
encrypting and verifying passwords or any other data that requires a hash representation.
String Transformations
toCamelCase(key: string): string
: Converts a string in snake_case or kebab-case format to camelCase. This is useful for useful for processing object property names in JavaScript or TypeScript.toUnderscore(key: string): string
: Converts a string in camelCase format to snake_case.
Object Transformations
underscoreToCamelCase(data: object): object
: Recursively converts an object's keys from snake_case or kebab-case to camelCase.- camelCaseToUnderscore(data: object): object`: Recursively converts the keys of an object from camelCase to snake_case.
Relational Data Processing
objectProcessor(data: object, fn: any): object
: A generic method that allows processing the keys of an object using a custom transformation function. using a custom transformation function. This is useful for working with data in complex structures. structures.
Database Data Processing
processAdditional(item: Record, model: BDModel): object
: Extracts and processes attributes of a data object belonging to a database model. belong to a specific database model. This is useful for working with data from relational databases. relational databases.processQueryItem(item?: any, model?: any, additionalAttributes?: any, additionalModels?: any): object
: Processes a data object, extracting attributes from it. data object, extracting attributes belonging to the main model and additional models, if specified. This is useful to obtain relational data from databases.processQueryArray(data, model, additionalAttributes?, additionalModel?)
: Processes an array of data objects using theprocessQueryArray(data, model, additionalAttributes?, additionalModel?)
method. using theprocessQueryItem
method. This is useful for transforming database query data into a more manageable format. easier to handle format.
Transformation of Objects in CamelCase
The processItems(data: data: object[]): object[]
method converts an array of objects with keys in snake_case or
kebab-case to camelCase.
In summary, the Model
class provides a wide range of functionality for processing data, transforming strings and
facilitate object manipulation in web and database applications. You can use these methods in your project to simplify
working with data and perform necessary transformations.
Usage
const token = Utils.generateToken(10, true); // Generate a token of length 10 with only numbers.
const camelCaseKey = Utils.toCamelCase('example_key_name'); // Convert 'example_key_name' to 'exampleKeyName'.
const underscoreKey = Utils.toUnderscore('exampleKeyName'); // Convert 'exampleKeyName' to 'example_key_name'.
Object JWT :
The JWT
object is used to generate and verify JWT
tokens.
The JWT
object is used for the generation and verification of JWT
tokens (JSON Web Tokens) in applications that
require token-based authentication and authorization. require token-based authentication and authorization. This class
encapsulates methods for signing and verifying JWT
tokens based on the JWT` tokens based on a secret key, facilitating
secure authentication management in web applications.
Importation
import { jwt } from '@bgroup/helpers/jwt';
Methods :
``constructor(secretKey: string)`: Initializes an instance of the JWT class with a secret key obtained from the process.env.SECRET_KEY environment variable. If no secret key is provided, the default string 'defaultSecretKey: string' is used. defaultSecretKey'... is used.
init(secretKey: string)
: Allows to change the secret key of the JWT instance once initialized. It receives as parameter a new secret key (secretKey) and assigns it to this.secretKey.generate(payload, expiresIn: string = '1h'): string
: Generates a JWT token from a provided
payload. Optionally, an expiration time can be specified (
expiresIn`). Returns the generated token as a string. string.authenticateToken(token: string)
: Private method that verifies and decodes a given JWT token. If the token is not valid, expired or incorrect, it throws an error with the corresponding message.verify(req: Request, res: Response, next: NextFunction)
: Method that acts as middleware to verify the token provided in the request. provided in the request. It extracts the token from the
Authorizationheader and uses the
authenticateTokenmethod.
authenticateTokenmethod to verify its validity. If the token is valid, it decodes the token and assigns it to
req.user` for later use in protected routes. In case of error, it returns a response with the corresponding status and an error message. and an error message.
Use :
The JWT
class is instantiated with a unique secret key, which will be used to sign and verify JWT tokens. Then, its
generateToken and verifyToken methods are used in the generation and validation of tokens in the application's
protected paths. protected paths of the application.
This class is essential for the security of routes that require authentication, since it provides a layer of layer of security by using valid and secure JWT tokens.
consider this example of use in an ExpressJS application to generate and verify a token: 👇
Generate Token
import express, { Request, Response } from 'express';
import { JWT } from '@bgroup/helpers/jwt';
const app = express();
// Path to generate a token
app.post('/generate-token', (req: Request, res: Response) => {
const { appId, userId, profileId } = req.body;
// Check if the data is valid (further validation can be done here)
if (
typeof appId !== 'string' ||
typeof userId !== 'string' ||
typeof profileId !== 'string'
) {
return res
.status(400)
.json({ message: 'Invalid data types in request' });
}
const payload = { appId, userId, profileId };
const token = jwt.generate(payload);
res.json({ token });
});
This example creates a /generate-token route to generate a token and a /protected route that requires a valid token for access. valid token for access.
Verify Token
// Protected path that verifies the token
import { JWT } from '@bgroup/helpers/jwt';
app.get('/protected-path', jwt.verify, (req, res) => {
// The token has been successfully verified and you can access req.user
res.json({ message: 'Access authorized', user: req.user });
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
Change the secret key :
import { JWT } from '@bgroup/helpers/jwt';
// Change the secret key using the init method
const newSecretKey = 'newSecretKey';
jwt.init(newSecretKey); // Change secret key
In this path, jwt.verify is used as middleware. This middleware verifies the token provided in the Authorization header of the incoming request. Authorization header of the incoming request. If the token is valid, decoded and verified correctly, the decoded object is assigned (decoded). the decoded object (req.user) is allocated and access to the route is allowed, responding with a JSON message indicating authorized access. authorized access.
Class Response :
The `Response`` class is a utility for structuring and handling endpoint responses in web applications. It provides methods to generate responses with success or error status, following a predefined format to maintain consistency in server responses. consistency in server responses.
Import
import { Response } from '@bgroup/helpers/response';
Methods
.
success({ data })
: Creates a success response with the data provided.error({ code, message })
: Creates an error response with specific error details, such as error type, code and a descriptive message. error, the code and a descriptive message.errors({ errors })
: Creates an error response for multiple errors, where errors is an array of objects containing details about different errors, each containing details about different errors, each containing details about different errors, each containing details about different errors. containing details about different errors, each with a code and a message.Examples
Endpoint to get all resources :
app.get('/resource', (req, res) => {
try {
// Logic to get all resources (e.g., from a database)
const resources = getResourcesFromDatabase(); // This function is hypothetical, replace it with your real logic.
// If resources are found, return a successful response
if (resources.length > 0) {
res.status(200).json(Response.success({ data: resources }));
} else {
// If there are no resources, returns an error response
res.status(404).json(
Response.error({
code: 404,
message: 'Resource not found',
})
);
}
} catch (error) {
// In case of an internal error, return an error response
res.status(500).json(
response.error({
error: 'Internal Server Error',
code: 500,
message: 'Internal error getting resources',
})
);
}
});
Endpoint to create a new resource :
app.post('/resource', (req, res) => {
try {
// Logic to create a new resource (e.g., from a POST request)
const newResource = req.body; // Assuming the new resource data is in the body of the request.
// Validate and create the resource
const created = createResource(newResource); // This function is hypothetical, replace it with your real logic
if (created) {
// If successfully created, return a successful response.
res.status(201).json(Response.success({ data: created }));
} else {
// If the resource cannot be created, it returns an error response
res.status(400).json(
Response.error({
error: 'Bad Request',
code: 400,
message: 'Could not create resource',
})
);
}
} catch (error) {
// In case of an internal error, return an error response.
res.status(500).json(
Response.error({
error: 'Internal Server Error',
code: 500,
message: 'Internal error creating resource',
})
);
}
});