Examples
In this example, we'll explore the basic usage of the ApiUtils library by creating a simple API server that handles user authentication and message encryption. We'll demonstrate how to generate tokens, encrypt passwords, and manage internationalized response messages.
Let's dive into the code and see how to set up the server and utilize the various functionalities provided by the ApiUtils library.
Encrypt Password
The following code shows the process of rapid password encryption along with rule validation
// app.js
const { encrypt } = require('apiutils.js');
const hashPassword = encrypt('Test01*', {uppercase: true, lowercase: true,
specialCharacters: true, numbers: true, containsPersonalInfo: false});
console.log('password hashing -->', hashPassword); // password hashing --> asd8f7qn09sadu98asdhqn93u
The following code shows the process of fast password encryption along with rule validation and validation of personal data within the rules
// app.js
const { encrypt } = require('apiutils.js');
const hashPassword = encrypt('Test01*', {uppercase: true, lowercase: true,
specialCharacters: true, numbers: true, containsPersonalInfo: true,
personalInfo: { name: "John", last_name: "Smith", born_date: "01/01/2000" }});
console.log('password hashing -->', hashPassword); // password hashing --> asd8f7qn09sadu98asdhqn93u
Decrypt Password
The following code shows the process of comparing the password supplied by the user with a quick validation of the password in plain text against the hash
// app.js
const { decrypt } = require('apiutils.js');
const comparePassword = decrypt('Test01*', 'asd8f7qn09sadu98asdhqn93u');
console.log('password compare -->', comparePassword); // password compare --> true
Generate Token
The following code shows the generation process for an authentication token, which allows loading an internal payload and expiration time
// app.js
const { generateToken } = require('apiutils.js');
const payload = {
fullName: "John Smith",
userId: "00202031"
};
const expireIn = "4H";
const token = generateToken(payload, expireIn);
console.log('token -->', token); // token --> eyawdfasdf97a8sdf90qa9f87d9f8a7sdf...
VerifyToken
The following code shows the validation process of an authentication token, which allows validating if it has expired or if it has been signed with the certificate generated by the system
// app.js
const { verifyToken } = require('apiutils.js');
const token = "eyawdfasdf97a8sdf90qa9f87d9f8a7sdf...";
const isValidToken = verifyToken(token);
console.log('token -->', isValidToken); // token --> { isValid: true }
MiddlewareToken Auth
The following code shows how to validate an authentication token in a Node.js application using middleware. This middleware checks if the provided token is valid, that is, if it is not expired and if it has been signed with the correct certificate generated by the system.
// app.js
const express = require('express');
const { middlewareToken } = require('apiutils.js');
const app = express();
app.use('/users', middlewareToken);
// Route with middleware
app.get('/users', (req, res) => {
res.send('Obteniendo lista de usuarios');
});
// Route without middleware
app.get('/', (req, res) => {
res.send('¡Hola, mundo!');
});
app.listen(3000, () => {
console.log('Server running in port 3000');
});
i18n for api response
The following code shows how to handle response messages from your API in multiple languages in a totally easy way in your code
// en.json
{
"NOT_FOUND": "Not found",
"SUCCESS_LOGIN": "Success Login"
}
// es.json
{
"NOT_FOUND": "No hemos podido encontrarlo",
"SUCCESS_LOGIN": "Inicio de Sesión satisfactorio"
}
// app.js
const express = require('express');
const { i18n_msg_manage } = require('apiutils.js');
const app = express();
app.use((req, res, next) => {
req.headers.lng = req.headers['accept-language'] || 'en';
next();
});
app.get('/users', (req, res) => {
res.status(404).json({
msg: i18n_msg_manage(req.headers.lng, 'NOT_FOUND')
});
});
app.listen(3000, () => {
console.log('Server running in port 3000');
});
Proccess Monitoring
The following code shows how to implement monitoring of your API processes.
// app.js
const express = require('express');
const { processMonitoring } = require('apiutils.js');
const app = express();
app.use(processMonitoring);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
[2024-04-12T10:30:15.123Z] Process started: GET /api/users
[2024-04-12T10:30:15.124Z] Total requests: 1
[2024-04-12T10:30:20.125Z] CPU usage: 12000μs user, 5000μs system
[2024-04-12T10:30:20.125Z] Memory usage: 200 MB used, 800 MB free
[2024-04-12T10:30:20.126Z] Process finished: GET /api/users
[2024-04-12T10:30:20.126Z] Elapsed time: 3.432ms
[2024-04-12T10:30:20.126Z] Total requests: 1
Compress Response
The following code shows the process of implementing API response compression for faster transactions from server to client.
// app.js
const express = require('express');
const {compressResponse} = require('apiutils.js');
const app = express();
app.use(compressResponse);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Generate JSON Schema for Validate Body's and Query's
The following code shows the implementation process for the validation of body's and query's in your API requests
Generate Schemas
userSchema:
type: object
properties:
username:
type: string
email:
type: string
format: email
age:
type: number
minimum: 0
required:
- username
- email
npx create-schema
Implement corresponding Middleware in the routes
// app.js
const express = require('express');
const { validateBodyReq, validateQuerysReq } = require('apiutils.js');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extends: true }))
app.get('/query', validateQuerysReq('querySchema'), (req, res) => {
res.status(200).json({
ok: true
});
});
app.post('/body', validateBodyReq('userSchema'), (req, res) => {
console.log(req.body);
res.status(200).json({
ok: true
});
});
app.listen(3000, () => {
console.log('api running');
});
Encrypt API Responses and Requests
The following code presents how to encrypt the API responses and decrypt the information received in the API
Generate apiKey
npx generate-key
Implement corresponding Middleware in app
const express = require('express');
const cors = require('cors');
const { encryptResponse, decryptRequest } = require('apiutils.js');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extends: true }));
app.use(cors());
app.use(encryptResponse);
app.use(decryptRequest);
app.get('/test', (req, res) => {
res.status(200).json({
ok: true,
msg: "Test",
personalInfo: {
name: "John",
lastName: "Smith",
age: 23
}
})
});
app.post('/test', (req, res) => {
res.status(200).json({
ok: true,
data: "MSG"
})
})
app.listen(4000, () => {
return console.log('api running');
});
Generate JSON Mocks from JSON Schema
This module will help you generate mocks through AI based on your JSON Schema which you can generate using our module for this task that you will see above.
Create file for mock generation
Create a file anywhere in your project where you will invoke the _generateMocks function
JSON Schema
{
"type": "object",
"properties": {
"username": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "number",
"minimum": 0
}
},
"required": [
"username",
"email"
]
}
JavaScript File
// mock.js
const { _generateMocks } = require('apiutils.js');
_generateMocks('userSchema', 5);
Response
[
{
"username": "JohnDoe",
"email": "johndoe@example.com",
"age": 30
},
{
"username": "JaneDoe",
"email": "janedoe@example.com",
"age": 25
},
{
"username": "BobSmith",
"email": "bobsmith@example.com",
"age": 40
},
{
"username": "AliceJohnson",
"email": "alicejohnson@example.com",
"age": 35
},
{
"username": "TomJackson",
"email": "tomjackson@example.com",
"age": 28
}
]
This mock will automatically be saved in your schema-validators folder, then you can move it to any other directory
Cron-Utils
The cron-utils module within apiutils.js provides utilities for scheduling tasks to run at specific intervals. It allows you to easily schedule tasks to run every few seconds, minutes, or hours.
Usage
To use cron-utils, import the library into your project:
const { every, everyHour, ... } = require('apiutils.js');
const {
everyMinute,
everyHour,
everyDay,
everyDayAt,
everyDayWeek,
everyWeekend,
every
} = require('apiutils.js');
function printHelloWorld() {
console.log('Hello World!');
}
// Run every minute
everyMinute(printHelloWorld);
// Run every hour
everyHour(printHelloWorld);
// Run every day
everyDay(printHelloWorld);
// Run every day at
everyDayAt(printHelloWorld, { hours: 15, minutes: 30 });
// Run every day at
everyDayWeek(printHelloWorld, { hours: 15, minutes: 30 });
// Run every day week
everyDayWeek(printHelloWorld, 'sunday'); // 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'
// Run every weekend
everyDayWeek(printHelloWorld, { hours: 15, minutes: 30 });
// Run every X number of minutes
every(5).minutes(printHelloWorld);
// Run every X number of seconds
every(40).seconds(printHelloWorld);
// Run every X number of hours
every(3).hours(printHelloWorld);