UNPKG

@noony-serverless/core

Version:

A Middy base framework compatible with Firebase and GCP Cloud Functions with TypeScript

106 lines 3.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpMethod = void 0; exports.generateRequestId = generateRequestId; exports.adaptGCPRequest = adaptGCPRequest; exports.adaptGCPResponse = adaptGCPResponse; exports.createContext = createContext; const typedi_1 = require("typedi"); /** * Framework-agnostic HTTP method enum */ var HttpMethod; (function (HttpMethod) { HttpMethod["GET"] = "GET"; HttpMethod["POST"] = "POST"; HttpMethod["PUT"] = "PUT"; HttpMethod["DELETE"] = "DELETE"; HttpMethod["PATCH"] = "PATCH"; HttpMethod["OPTIONS"] = "OPTIONS"; HttpMethod["HEAD"] = "HEAD"; })(HttpMethod || (exports.HttpMethod = HttpMethod = {})); /** * Utility function to generate unique request IDs */ function generateRequestId() { return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; } /** * Adapter to convert GCP Functions Request to GenericRequest */ function adaptGCPRequest(gcpRequest) { return { method: gcpRequest.method || HttpMethod.GET, url: gcpRequest.url || '/', path: gcpRequest.path, headers: gcpRequest.headers || {}, query: gcpRequest.query || {}, params: gcpRequest.params || {}, body: gcpRequest.body, rawBody: gcpRequest.rawBody, ip: gcpRequest.ip, userAgent: gcpRequest.get?.('user-agent'), }; } /** * Adapter to convert GCP Functions Response to GenericResponse */ function adaptGCPResponse(gcpResponse) { let currentStatusCode = 200; let isHeadersSent = false; return { status: (code) => { currentStatusCode = code; gcpResponse.status(code); return adaptGCPResponse(gcpResponse); }, json: (data) => { isHeadersSent = true; gcpResponse.json(data); }, send: (data) => { isHeadersSent = true; gcpResponse.send(data); }, header: (name, value) => { gcpResponse.header(name, value); return adaptGCPResponse(gcpResponse); }, headers: (headers) => { Object.entries(headers).forEach(([key, value]) => { gcpResponse.header(key, value); }); return adaptGCPResponse(gcpResponse); }, end: () => { isHeadersSent = true; gcpResponse.end(); }, get statusCode() { return gcpResponse.statusCode || currentStatusCode; }, get headersSent() { return gcpResponse.headersSent || isHeadersSent; }, }; } /** * Creates a context object for framework-agnostic handlers * @template TBody The type of the request body * @template TUser The type of the authenticated user */ function createContext(req, res, options = {}) { return { req, res, container: options.container || typedi_1.Container.of(), error: options.error || null, businessData: options.businessData || new Map(), user: options.user, startTime: options.startTime || Date.now(), requestId: options.requestId || generateRequestId(), timeoutSignal: options.timeoutSignal, responseData: options.responseData, }; } //# sourceMappingURL=core.js.map