@simpleapps-com/augur-api
Version:
TypeScript client library for Augur microservices API endpoints
123 lines • 4.78 kB
JavaScript
import axios from 'axios';
import { DEFAULT_CONFIG } from './config';
import { AugurError, AuthenticationError, NotFoundError, RateLimitError } from './errors';
export class HTTPClient {
constructor(serviceName, config) {
this.serviceName = serviceName;
this.config = { ...DEFAULT_CONFIG, ...config };
this.axios = axios.create({
timeout: this.config.timeout,
});
this.setupInterceptors();
}
setupInterceptors() {
// Request interceptor
this.axios.interceptors.request.use(async (config) => {
// Always add x-site-id header
config.headers['x-site-id'] = this.config.siteId;
// Add bearer token for non-health-check endpoints
const isHealthCheck = config.url?.includes('/health-check');
if (!isHealthCheck && this.config.bearerToken) {
config.headers['Authorization'] = `Bearer ${this.config.bearerToken}`;
}
// User-defined request interceptor
if (this.config.onRequest) {
const modifiedConfig = await this.config.onRequest(config);
// Ensure we return the internal config format
return modifiedConfig;
}
return config;
}, error => Promise.reject(error));
// Response interceptor
this.axios.interceptors.response.use(async (response) => {
if (this.config.onResponse) {
return this.config.onResponse(response);
}
return response;
}, async (error) => {
const originalRequest = error.config;
const endpoint = originalRequest?.url || 'unknown';
if (error.response) {
this.handleHttpError(error.response, endpoint);
}
this.handleNetworkError(error, endpoint);
});
}
handleHttpError(response, endpoint) {
const { status, data } = response;
switch (status) {
case 401:
throw new AuthenticationError({
message: data?.message || 'Authentication failed',
service: this.serviceName,
endpoint,
});
case 404:
throw new NotFoundError({
message: data?.message || 'Resource not found',
service: this.serviceName,
endpoint,
});
case 429:
throw new RateLimitError({
message: data?.message || 'Rate limit exceeded',
service: this.serviceName,
endpoint,
});
default:
throw new AugurError({
message: data?.message || `Request failed with status ${status}`,
code: data?.code || 'API_ERROR',
statusCode: status,
service: this.serviceName,
endpoint,
requestId: data?.requestId,
});
}
}
handleNetworkError(error, endpoint) {
throw new AugurError({
message: error.message || 'Network error',
code: 'NETWORK_ERROR',
statusCode: 0,
service: this.serviceName,
endpoint,
});
}
async get(url, params, config) {
const baseParams = params && typeof params === 'object' ? params : {};
// Auto-inject cacheSiteId parameter based on edgeCache value
const enhancedParams = { ...baseParams };
// If edgeCache is specified, map it to the correct cacheSiteId parameter
if (baseParams.edgeCache && typeof baseParams.edgeCache === 'number') {
const cacheHours = baseParams.edgeCache;
enhancedParams[`cacheSiteId${cacheHours}`] = this.config.siteId;
// Remove the edgeCache parameter as it's only used for mapping
delete enhancedParams.edgeCache;
}
const response = await this.axios.get(url, {
params: enhancedParams,
...config,
});
return response.data;
}
async post(url, data, config) {
const response = await this.axios.post(url, data, config);
return response.data;
}
async put(url, data, config) {
const response = await this.axios.put(url, data, config);
return response.data;
}
async delete(url, config) {
const response = await this.axios.delete(url, config);
return response.data;
}
setBearerToken(token) {
this.config.bearerToken = token;
}
setSiteId(siteId) {
this.config.siteId = siteId;
}
}
//# sourceMappingURL=client.js.map