qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
56 lines (46 loc) • 1.5 kB
JavaScript
/**
* Cookie Extractor
* Single Responsibility: Extract values from HTTP cookies ONLY
*/
/**
* Extracts API key from request cookies
* @param {object} req - Express request object
* @param {string} [cookieName='apiKey'] - Name of the cookie containing the API key
* @returns {string|null} API key from cookie or null if not found
*/
function extractApiKeyFromCookie(req, cookieName = 'apiKey') {
if (!req || typeof req !== 'object') {
return null;
}
// Check if cookies exist on request
if (!req.cookies || typeof req.cookies !== 'object') {
return null;
}
// Extract the specific cookie value
const cookieValue = req.cookies[cookieName];
// Return null if cookie doesn't exist or is empty
if (!cookieValue || typeof cookieValue !== 'string' || cookieValue.trim() === '') {
return null;
}
return cookieValue.trim();
}
/**
* Extracts multiple values from cookies
* @param {object} req - Express request object
* @param {string[]} cookieNames - Array of cookie names to extract
* @returns {object} Object with cookie names as keys and values as extracted data
*/
function extractMultipleCookies(req, cookieNames) {
if (!Array.isArray(cookieNames)) {
throw new Error('Cookie names must be an array');
}
const result = {};
for (const cookieName of cookieNames) {
result[cookieName] = extractApiKeyFromCookie(req, cookieName);
}
return result;
}
module.exports = {
extractApiKeyFromCookie,
extractMultipleCookies
};