UNPKG

@sudowealth/schwab-api

Version:

TypeScript client for Charles Schwab API with OAuth support, market data, trading functionality, and complete type safety

46 lines (45 loc) 1.59 kB
import { createLogger } from '../utils/secure-logger'; const logger = createLogger('MiddlewareMetadata'); /** * Symbol used to store middleware metadata on Request and Response objects */ const MIDDLEWARE_METADATA = Symbol('MIDDLEWARE_METADATA'); /** * Gets middleware metadata from a Request or Response * Creates an empty object if no metadata exists yet */ export function getMetadata(obj) { // Check if the object is extensible and has the symbol property already if (Object.getOwnPropertySymbols(obj).includes(MIDDLEWARE_METADATA)) { return obj[MIDDLEWARE_METADATA]; } // Create new metadata object const metadata = {}; try { // Try to set the symbol property on the object Object.defineProperty(obj, MIDDLEWARE_METADATA, { value: metadata, enumerable: false, writable: true, }); } catch (e) { // If we can't modify the object (e.g., frozen objects), log a warning logger.warn('Could not attach metadata to object, some middleware coordination might not work properly. Error:', e?.message || e); } return metadata; } /** * Creates a new Request with the metadata from the original * Useful when you need to clone a request but maintain its metadata */ export function cloneRequestWithMetadata(req) { const newReq = new Request(req.url, req); const metadata = getMetadata(req); Object.defineProperty(newReq, MIDDLEWARE_METADATA, { value: { ...metadata }, enumerable: false, writable: true, }); return newReq; }