Betterez HTTP Service Utilities

1.47.0 · active · verified Wed Apr 22

btrz-http-service is a JavaScript utility library designed to streamline API development within the Betterez ecosystem. Currently at version 1.47.0, it offers a suite of tools including a Swagger request handler formatter for defining API endpoints, specialized success and error response handlers for consistent API feedback, a collection of common Swagger schemas, and robust Swagger schema validation. It also introduces a custom `ValidationError` type to standardize error reporting within the application. The library appears to be actively maintained with a steady release cadence, evidenced by its significant minor version increments. Its key differentiators include its tight integration with Swagger for API definition and validation, a structured approach to middleware and error handling, and its focus on providing consistent API behavior for Betterez applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an API endpoint using a `RequestHandler` class, integrate it with `swaggerRequestHandler` and optional middleware, and handle responses using `ResponseHandlers.success` and `ResponseHandlers.error`.

const { swaggerRequestHandler, ResponseHandlers } = require('btrz-http-service');

// A mock request object for demonstration
const mockReq = { body: { items: ['item1', 'item2'] } };
// A mock response object with methods expected by ResponseHandlers
const mockRes = {
  statusCode: 200,
  data: null,
  status(code) { this.statusCode = code; return this; },
  send(data) { this.data = data; console.log(`Response Status: ${this.statusCode}, Data:`, this.data); },
  json(data) { this.data = data; console.log(`Response Status: ${this.statusCode}, JSON:`, this.data); },
};

class RequestHandler {
  constructor(swagger) {
    this.swagger = swagger; // In a real app, this might be injected or provided
  }
  getSpec() {
    return {
      "description": "endpoint description",
      "path": "/endpoint",
      "summary": "endpoint summary",
      "method": "POST",
      "parameters": [
        {
          "name": "items",
          "in": "body",
          "description": "the items",
          "schema": { "type": "array", "items": { "type": "string" } },
          "required": true
        }
      ],
      "produces": ["application/json"],
      "type": "Schema",
      "errorResponses": [],
      "nickname": "nick"
    };
  }
  async handler(req, res) {
    console.log('Handler received request body:', req.body);
    try {
      // Simulate an async operation
      await new Promise(resolve => setTimeout(resolve, 100));
      if (!req.body || !Array.isArray(req.body.items) || req.body.items.length === 0) {
        throw new Error('No items provided');
      }
      const processedData = req.body.items.map(item => item.toUpperCase());
      console.log('Processed data:', processedData);
      // Use success handler
      ResponseHandlers.success(res)(processedData);
    } catch (error) {
      console.error('Handler error:', error.message);
      // Use error handler
      ResponseHandlers.error(res)(error);
    }
  }
}

// Mock middleware for demonstration
function passportAuthenticate(req, res, next) {
  console.log('Running passportAuthenticate middleware');
  // Simulate authentication success
  next();
}

function otherMiddleware(req, res, next) {
  console.log('Running otherMiddleware');
  // Simulate some other processing
  next();
}

// Create a handler instance (mocking swagger object as it's not provided in context)
const handlerInstance = new RequestHandler({}); 

// Generate the swagger handler with middleware
const swaggerHandler = swaggerRequestHandler(passportAuthenticate, otherMiddleware, handlerInstance);

// Simulate calling the generated swaggerHandler
console.log('--- Simulating API Call ---');
swaggerHandler(mockReq, mockRes);

view raw JSON →