@beta3000/serverless-library
v1.0.3
Published
Helpers de respuesta y utilidades para AWS Lambda (SAM)
Maintainers
Readme
serverless-library
TypeScript utility library for AWS Lambda + API Gateway (SAM) projects. Provides a unified response envelope, error handling, request parsing and Cognito identity helpers.
Installation
npm install @beta3000/serverless-libraryUnified Response Envelope
Every response produced by buildResponse and buildErrorResponse follows the
same JSON envelope:
{
"success": true,
"code": "OK",
"httpCode": 200,
"messages": [],
"data": { "id": 1, "name": "Ada" }
}Error responses use the same shape with success: false and data: null:
{
"success": false,
"code": "REQUEST_BODY",
"httpCode": 400,
"messages": ["Invalid JSON body"],
"data": null
}Configuration
CORS origin
Set the ORIGIN environment variable for CORS headers. When ORIGIN is an
explicit origin, Access-Control-Allow-Credentials: true is included. When
ORIGIN is not set, the fallback * is used without credentials (the
combination is invalid per the CORS spec). In production, always set an explicit
origin.
export ORIGIN=https://app.example.comUsage
End-to-end Lambda handler
import {
buildErrorResponse,
buildResponse,
getRequest,
getPathParamsByKey,
getUsername,
LambdaEvent,
} from '@beta3000/serverless-library';
interface CreateItemBody {
name: string;
price: number;
}
export const handler = async (event: LambdaEvent) => {
try {
const body = getRequest<CreateItemBody>(event);
const user = getUsername(event);
// Business logic
const item = { id: '123', ...body, createdBy: user };
return buildResponse({
data: item,
code: 'CREATED',
httpCode: 201,
messages: ['Item created successfully'],
});
} catch (error) {
return buildErrorResponse(error);
}
};Request body parsing — getRequest
import { getRequest } from '@beta3000/serverless-library';
const body = getRequest(event);- Returns
{}whenevent.bodyisnull. - Returns the parsed object when
bodyis valid JSON. - Throws
BusinessErrorwith codeREQUEST_BODY(HTTP 400) on invalid JSON. - Returns the event itself when
bodyproperty is absent (fallback). - Base64-encoded bodies are not supported in v1.
Query and path parameters
import { getQueryParamsByKey, getPathParamsByKey } from '@beta3000/serverless-library';
const page = getQueryParamsByKey(event, 'page'); // string | undefined
const id = getPathParamsByKey(event, 'id'); // string | undefinedBoth return undefined when the key is missing, the parameters object is
null, or the value is an empty string.
Cognito identity — getUsername / getClaims
import { getUsername, getClaims } from '@beta3000/serverless-library';
const username = getUsername(event); // cognito:username or 'SYSTEM'
const claims = getClaims(event); // Record<string, string> | undefinedSafe to call on non-Cognito events — never throws. Falls back to 'SYSTEM'
when claims are unavailable.
Building responses
import { buildResponse } from '@beta3000/serverless-library';
return buildResponse({
data: { id: 1, name: 'Ada' },
code: 'OK',
httpCode: 200,
});Error handling
import { buildErrorResponse, BusinessError, HTTP_CONSTANT } from '@beta3000/serverless-library';
// BusinessError → uses its code/httpCode/messages
// Generic Error → 500 INTERNAL_ERROR (internal message never exposed)
// Non-Error value → 500 INTERNAL_ERROR
return buildErrorResponse(error);Security headers
import { buildSecurityHeaders } from '@beta3000/serverless-library';
const headers = buildSecurityHeaders();
// X-Content-Type-Options: nosniff
// X-XSS-Protection: 1; mode=block
// X-Frame-Options: SAMEORIGIN
// Referrer-Policy: strict-origin-when-cross-origin
// Strict-Transport-Security: max-age=31536000; includeSubDomains
// Access-Control-Allow-Origin: <ORIGIN>Extending the error catalog
import { Errors, HTTP_CONSTANT, BusinessError } from '@beta3000/serverless-library';
const MyErrors = {
...Errors,
DUPLICATE_EMAIL: { code: 'DUPLICATE_EMAIL', message: 'Email already in use' },
};
throw new BusinessError({
code: MyErrors.DUPLICATE_EMAIL.code,
httpCode: HTTP_CONSTANT.BAD_REQUEST.httpCode,
messages: [MyErrors.DUPLICATE_EMAIL.message],
});API Reference
Generate full API docs locally:
npm run docsOutput is written to docs-api/.
License
MIT
