npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

apiutils.js

v0.1.1

Published

A versatile tool to streamline API development in Node.js

Downloads

24

Readme

ApiUtils

A comprehensive utility library for building and enhancing APIs in Node.js.

Installation

This is a Node.js module available through the npm registry. Before installing, download and install Node.js. Node.js 14 or higher is required.

If this is a new project, make sure to create a package.json first with the npm init command.

Installation is done using the npm install command:

$ npm install apiutils.js

Features

  • Token Generation & Manage: Easy, fast and secure creation of tokens with high security standards for your API.
  • Password Manage: Password generation, password comparison and rule validation when registering a hash.
  • Internationalization (i18n) Management: Managing your response messages in multiple languages ​​more effectively
  • Process Monitoring: Real-time visualization of the processes executed by your API, number of requests executed, execution times and more...
  • Response Compression: Compression of the responses sent by your API to the client to make faster transactions
  • Schemas Validators: Generate schemas for your requests and validate the validity of the body's and query's

Documentation

For detailed usage and examples, check out the documentation.

Quick Start

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": "[email protected]",
    "age": 30
  },
  {
    "username": "JaneDoe",
    "email": "[email protected]",
    "age": 25
  },
  {
    "username": "BobSmith",
    "email": "[email protected]",
    "age": 40
  },
  {
    "username": "AliceJohnson",
    "email": "[email protected]",
    "age": 35
  },
  {
    "username": "TomJackson",
    "email": "[email protected]",
    "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);

Contributing

We welcome contributions from the community! Whether it's bug fixes, new features, or improvements to the documentation, feel free to submit a pull request. Check out our contributing guidelines for more information.

Security

If you discover any security vulnerabilities, please report them via email. We take security seriously and appreciate your help in keeping our library safe.

License

This project is licensed under the MIT License - see the LICENSE file for details.