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
muslnode 18–226 runs
build_error
glibcnode 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);
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.
fixEnsure 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.
fixCheck 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.
fixReview 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.
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.