1.0.0 • Published 7 months ago

api-helper-toolkit v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

API Helper Toolkit

A utility toolkit for building APIs in Node.js, providing reusable helpers and middleware to streamline development. It offers functionalities for standardized responses, pagination, error handling, rate limiting, and more, making it easier to implement these common features across your projects.

Features

  • Standardized API Responses:

    • Use Case: When building APIs, it's essential to maintain consistency in the way responses are sent to clients. This package provides utility functions to standardize success and error responses in a uniform format.
    • How It Works: It provides two methods: success for successful responses and error for error responses. These methods include default message handling and the ability to pass custom messages or error details.
  • Pagination Utilities:

    • Use Case: Pagination is a common requirement when working with large sets of data. This utility simplifies the process of paginating through lists of data.
    • How It Works: The paginate function takes an array of data and breaks it into pages based on the page and limit parameters provided. This helps control the amount of data sent to the client at once and reduces load on your server.
  • Error Handling:

    • Use Case: Consistent error handling ensures that errors are managed in a way that's predictable and informative for the end user or developer. This package provides a custom error class and global error handling middleware.
    • How It Works: The AppError class allows you to create custom error messages with status codes. The errorMiddleware function catches these errors and formats them uniformly before sending them in the API response.
  • Rate Limiter:

    • Use Case: APIs are often subject to abuse through excessive requests, which can overload the server. This middleware helps limit the number of requests from a single client to prevent this.
    • How It Works: The package uses the express-rate-limit package to set a limit on how many requests an individual client (based on their IP) can make within a given time window (e.g., 100 requests per 15 minutes). If the limit is exceeded, a predefined error message is returned.
  • HTTP Client:

    • Use Case: When interacting with external APIs or services, it’s useful to have a pre-configured HTTP client to streamline making requests. This package includes a basic Axios client to handle HTTP calls to external resources.
    • How It Works: The httpClient is an instance of axios, pre-configured with a base URL and timeout setting. You can use this client to make HTTP requests to external APIs and handle responses more easily.

Installation

To use this package, you can install it via NPM:

npm install api-helper-toolkit

Usage

1. Standardized API Responses

Import the responseHelper module to use the success and error functions:

const { success, error } = require('api-helper-toolkit').responseHelper;

Then, in your route handlers:

app.get('/items', (req, res) => {
   const data = { id: 1, name: 'Item 1' };
   success(res, data, 'Items fetched successfully');
});

2. Pagination Utilities

Import the paginationHelper module:

const { paginate } = require('api-helper-toolkit').paginationHelper;

Use it to paginate through your data:

app.get('/items', (req, res) => {
   const items = [...Array(100).keys()];  // Example data
   const page = parseInt(req.query.page) || 1;
   const limit = parseInt(req.query.limit) || 10;
   const paginatedItems = paginate(items, page, limit);
   success(res, paginatedItems, 'Paginated items fetched');
});

3. Error Handling

To use the error handling utilities, you can create a custom error with AppError:

const { AppError, errorMiddleware } = require('api-helper-toolkit').errorHandler;

app.get('/error', (req, res, next) => {
   next(new AppError('Something went wrong!', 400));
});

app.use(errorMiddleware);  // Global error handler

4. Rate Limiting

You can apply rate limiting globally or to specific routes:

const apiRateLimiter = require('api-helper-toolkit').apiRateLimiter;

app.use('/api', apiRateLimiter);  // Apply to all API routes

app.get('/api/some-endpoint', (req, res) => {
   res.json({ message: 'This is rate-limited' });
});

5. HTTP Client for External APIs

To use the pre-configured Axios client for making requests to external services:

const httpClient = require('api-helper-toolkit').httpClient;

app.get('/external-data', async (req, res) => {
   try {
      const response = await httpClient.get('/data');
      success(res, response.data, 'External data fetched');
   } catch (err) {
      error(res, 'Failed to fetch external data');
   }
});

Conclusion

The API Helper Toolkit simplifies and streamlines API development by providing ready-to-use solutions for common tasks. You can focus on building your application while relying on this toolkit for standardized error handling, responses, rate limiting, and more.

1.0.0

7 months ago