Registry / web-framework / btrz-http-service

btrz-http-service

JSON →
library1.47.0jsnpmunverified

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.

npm install btrz-http-service
INSTALL
IMPORT
SIG · BTRZ-HTTP-SERVICE
B
btrz-http-service
web-frameworkjavascriptv1.47.0
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

swaggerRequestHandler
✓ const swaggerRequestHandler = require('btrz-http-service').swaggerRequestHandler;
✗ import { swaggerRequestHandler } from 'btrz-http-service';
The documentation explicitly uses CommonJS `require`. Direct ESM import syntax might not be supported without a transpilation step or if the package is purely CJS.
ResponseHandlers
✓ const ResponseHandlers = require('btrz-http-service').ResponseHandlers;
✗ import { ResponseHandlers } from 'btrz-http-service';
Provides `success` and `error` methods for standardizing API responses. Intended for use at the end of promise chains.
validateSwaggerSchema
✓ const validateSwaggerSchema = require('btrz-http-service').validateSwaggerSchema;
✗ import { validateSwaggerSchema } from 'btrz-http-service';
This function is used for runtime validation of request bodies against defined Swagger schemas.
ValidationError
✓ const ValidationError = require('btrz-http-service').ValidationError;
✗ import { ValidationError } from 'btrz-http-service';
A custom error type subclassing native `Error`, allowing for specific error codes, messages, and HTTP status overrides for API responses.

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);
Debug
Known issues
gotchaOlder versions (v1.6.5 and earlier) of `btrz-http-service` used `swagger-validation` in a way that could mutate the original Swagger `models` object passed for validation. This could lead to unexpected side effects in applications that reuse the models.
fix
Upgrade to `btrz-http-service` v1.6.6 or newer, which includes a workaround to clone the `models` object before validation. Ensure your application does not rely on mutable `models` objects if using older versions.
affects: <1.6.6
gotchaThe `ResponseHandlers.success` and `ResponseHandlers.error` utilities are designed to be used only once at the very end of a promise chain. Calling them multiple times or at intermediate steps in a chain can lead to unexpected behavior or errors in API responses.
fix
Always place `ResponseHandlers.success(res)` or `ResponseHandlers.error(res)` as the final `.then()` or `.catch()` callback in your promise chains to ensure a single, consistent response.
affects: >=1.0.0
gotchaWhen defining `getSpec()` in a `RequestHandler` class, ensure that `this.swagger.paramTypes` or other `this.swagger` properties are correctly initialized and available. Improper setup of the `swagger` object passed to the `RequestHandler` constructor can lead to `TypeError: Cannot read properties of undefined (reading 'paramTypes')`.
fix
Ensure that the `RequestHandler` instance is correctly initialized with a `swagger` object that contains the necessary properties, such as `paramTypes`, as expected by the `getSpec` method. This object is typically provided by the framework integrating `btrz-http-service`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'paramTypes')
`this.swagger` or `this.swagger.paramTypes` is undefined within a `RequestHandler`'s `getSpec` method.
fix
Ensure that the `RequestHandler` class is properly constructed with a `swagger` object that provides the `paramTypes` utility, or mock it during testing. In typical usage, an integrating framework provides this context.
ValidationError: WRONG_DATA - The 'field_name' field is required.
A request body failed validation against its defined Swagger schema, indicating missing or invalid data.
fix
Check the API documentation for the endpoint's schema requirements. Adjust the request payload to include all required fields and ensure data types and formats match the schema definition. The `WRONG_DATA` log entry should specify the model path and field value.
ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client
Multiple attempts were made to send a response (e.g., using `res.send`, `res.json`, or a response handler) within a single request-response cycle, likely due to incorrect promise chaining or conditional logic.
fix
Review the code to ensure that only one response is sent per request. Pay close attention to asynchronous operations and promise chains, especially when using `ResponseHandlers.success` and `ResponseHandlers.error`, which should be terminal operations.
Upgrade
Version history
1.47.0latest on npm
Audit
Dependencies
swagger-validationrequiredUsed for validating request bodies against Swagger schemas, as indicated by release notes and `validateSwaggerSchema` utility.
expressoptionalThe README describes middleware functions with a `(req, res, next)` signature and mentions 'Just like in Express with Connect,' implying an Express.js-like environment.
btrz-auth-api-keyoptionalMentioned in code examples (`passportAuthenticate`) and related Betterez package documentation, suggesting common integration for authentication.
Agent activity
14 hits · last 30 days
node
12
Amazon
1
OpenAI (training)
1
Resources
btrz-http-service — npm install btrz-http-service · libregistry