@dbs-portal/core-api
Version:
HTTP client and API utilities for DBS Portal
188 lines • 5.17 kB
JavaScript
/**
* Request utility functions
*/
/**
* Serializes data for request body
*/
export function serializeRequestData(data, contentType) {
if (!data) {
return null;
}
if (typeof data === 'string') {
return data;
}
if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) {
return data;
}
if (contentType?.includes('application/x-www-form-urlencoded')) {
return new URLSearchParams(data).toString();
}
// Default to JSON
return JSON.stringify(data);
}
/**
* Creates FormData from object
*/
export function createFormData(data) {
const formData = new FormData();
for (const [key, value] of Object.entries(data)) {
if (value instanceof File || value instanceof Blob) {
formData.append(key, value);
}
else {
formData.append(key, String(value));
}
}
return formData;
}
/**
* Merges request configurations
*/
export function mergeConfigs(defaultConfig, requestConfig) {
return {
...defaultConfig,
...requestConfig,
headers: {
...defaultConfig.headers,
...requestConfig.headers,
},
params: {
...defaultConfig.params,
...requestConfig.params,
},
};
}
/**
* Validates request configuration
*/
export function validateRequestConfig(config) {
if (!config.url) {
throw new Error('URL is required');
}
if (config.timeout && config.timeout < 0) {
throw new Error('Timeout must be positive');
}
if (config.method &&
!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(config.method)) {
throw new Error(`Invalid HTTP method: ${config.method}`);
}
}
/**
* Creates abort controller with timeout
*/
export function createAbortController(timeout) {
const controller = new AbortController();
if (timeout && timeout > 0) {
const timeoutId = setTimeout(() => {
controller.abort();
}, timeout);
return { controller, timeoutId };
}
return { controller };
}
/**
* Determines content type from data
*/
export function getContentType(data) {
if (typeof data === 'string') {
return 'text/plain';
}
if (data instanceof FormData) {
return 'multipart/form-data';
}
if (data instanceof URLSearchParams) {
return 'application/x-www-form-urlencoded';
}
if (data instanceof Blob) {
return data.type || 'application/octet-stream';
}
if (data instanceof ArrayBuffer) {
return 'application/octet-stream';
}
// Default to JSON for objects
return 'application/json';
}
/**
* Checks if request should have body
*/
export function shouldHaveBody(method) {
return ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase());
}
/**
* Sanitizes headers by removing undefined values
*/
export function sanitizeHeaders(headers) {
const sanitized = {};
for (const [key, value] of Object.entries(headers)) {
if (value !== undefined && value !== null) {
sanitized[key] = String(value);
}
}
return sanitized;
}
/**
* Creates request signature for caching/deduplication
*/
export function createRequestSignature(config) {
const method = config.method || 'GET';
const url = config.url;
const params = config.params ? JSON.stringify(config.params) : '';
const data = config.data ? JSON.stringify(config.data) : '';
return `${method}:${url}:${params}:${data}`;
}
/**
* Checks if request is cacheable
*/
export function isCacheableRequest(config) {
const method = config.method || 'GET';
// Only cache safe methods
if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return false;
}
// Don't cache requests with authorization headers (unless explicitly allowed)
if (config.headers?.['Authorization'] || config.headers?.['authorization']) {
return false;
}
return true;
}
/**
* Estimates request size for monitoring
*/
export function estimateRequestSize(config) {
let size = 0;
// URL size
size += config.url.length;
// Headers size
if (config.headers) {
for (const [key, value] of Object.entries(config.headers)) {
size += key.length + String(value).length;
}
}
// Body size
if (config.data) {
if (typeof config.data === 'string') {
size += config.data.length;
}
else if (config.data instanceof Blob) {
size += config.data.size;
}
else {
size += JSON.stringify(config.data).length;
}
}
return size;
}
/**
* Creates request metadata for logging/monitoring
*/
export function createRequestMetadata(config) {
return {
method: config.method || 'GET',
url: config.url,
hasAuth: !!(config.headers?.['Authorization'] || config.headers?.['authorization']),
hasBody: !!config.data,
estimatedSize: estimateRequestSize(config),
timestamp: Date.now(),
};
}
//# sourceMappingURL=request-utils.js.map