ng-http-spring
Version:
A Spring Boot-like HTTP library for Angular with decorators, caching, request queuing, file upload, WebSocket, and GraphQL support
458 lines (436 loc) • 14.8 kB
TypeScript
import * as i1 from '@angular/common/http';
import { HttpErrorResponse, HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpInterceptorFn } from '@angular/common/http';
import * as rxjs from 'rxjs';
import { Observable } from 'rxjs';
import * as i0 from '@angular/core';
import { Provider } from '@angular/core';
interface HttpConfig {
url: string;
method?: string;
headers?: {
[key: string]: string;
};
params?: {
[key: string]: string;
};
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
retryConfig?: {
maxRetries: number;
delayMs: number;
retryCondition?: (error: any) => boolean;
};
withCredentials?: boolean;
observe?: 'body' | 'response' | 'events';
body?: any;
}
interface CacheConfig {
key?: string;
ttl?: number;
group?: string;
condition?: (response: any) => boolean;
}
interface CacheEntry<T = any> {
data: T;
expiry: number;
group?: string;
}
interface CacheStorage {
get<T>(key: string): CacheEntry<T> | undefined;
set<T>(key: string, entry: CacheEntry<T>): void;
delete(key: string): void;
clear(group?: string): void;
}
declare class HttpError extends Error {
status: number;
message: string;
error: any;
path: string;
constructor(status: number, message: string, error: any, path: string);
static from(error: HttpErrorResponse): HttpError;
}
interface ErrorHandler {
handleError(error: HttpError): void;
}
interface ErrorConfig {
handler?: ErrorHandler;
retryable?: boolean;
transform?: (error: HttpError) => any;
}
declare function PathVariable(paramName: string): (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare function RequestParam(paramName: string): (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare function RequestBody(): (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
declare function Header(headerName: string): (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
interface RequestMetadata {
path: string;
method: string;
cache?: CacheConfig;
error?: ErrorConfig;
config?: HttpConfig;
}
declare const Get: (path: string, config?: HttpConfig & {
cache?: CacheConfig;
error?: ErrorConfig;
}) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
declare const Post: (path: string, config?: HttpConfig & {
cache?: CacheConfig;
error?: ErrorConfig;
}) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
declare const Put: (path: string, config?: HttpConfig & {
cache?: CacheConfig;
error?: ErrorConfig;
}) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
declare const Delete: (path: string, config?: HttpConfig & {
cache?: CacheConfig;
error?: ErrorConfig;
}) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
declare const Patch: (path: string, config?: HttpConfig & {
cache?: CacheConfig;
error?: ErrorConfig;
}) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
declare class HttpService {
private readonly http;
constructor(http: HttpClient);
executeRequest(config: HttpConfig): Observable<any>;
private createRequest;
static ɵfac: i0.ɵɵFactoryDeclaration<HttpService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<HttpService>;
}
declare enum LogLevel {
DEBUG = "DEBUG",
INFO = "INFO",
WARN = "WARN",
ERROR = "ERROR"
}
interface LogConfig {
level: LogLevel;
maxBodySize?: number;
includeHeaders?: boolean;
includeTiming?: boolean;
includeMetrics?: boolean;
formatter?: (message: string, level: LogLevel, data?: any) => string;
}
declare class LoggingInterceptor implements HttpInterceptor {
private config;
private metrics;
setConfig(config: Partial<LogConfig>): void;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
private calculateRequestSize;
private calculateResponseSize;
private truncateBody;
private updateMetrics;
private logMetrics;
private log;
private isLevelEnabled;
static ɵfac: i0.ɵɵFactoryDeclaration<LoggingInterceptor, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<LoggingInterceptor>;
}
declare class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
static ɵfac: i0.ɵɵFactoryDeclaration<ErrorInterceptor, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<ErrorInterceptor>;
}
interface AuthConfig {
tokenProvider: () => string | Promise<string>;
headerName?: string;
scheme?: string;
refreshToken?: () => Promise<string>;
onAuthError?: (error: any) => void;
}
interface TokenResponse {
accessToken: string;
refreshToken?: string;
expiresIn?: number;
}
declare class AuthInterceptor implements HttpInterceptor {
private isRefreshing;
private authConfig;
constructor();
setConfig(config: AuthConfig): void;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
private handleRequest;
private handleAuthError;
private addAuthHeader;
static ɵfac: i0.ɵɵFactoryDeclaration<AuthInterceptor, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<AuthInterceptor>;
}
declare const loggingInterceptor: HttpInterceptorFn;
declare const errorInterceptor: HttpInterceptorFn;
declare const authInterceptor: HttpInterceptorFn;
declare class MemoryCacheService implements CacheStorage {
private cache;
get<T>(key: string): CacheEntry<T> | undefined;
set<T>(key: string, entry: CacheEntry<T>): void;
delete(key: string): void;
clear(group?: string): void;
static ɵfac: i0.ɵɵFactoryDeclaration<MemoryCacheService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<MemoryCacheService>;
}
interface UploadConfig {
url: string;
file: File;
chunkSize?: number;
headers?: {
[key: string]: string;
};
allowedTypes?: string[];
maxSize?: number;
withCredentials?: boolean;
metadata?: {
[key: string]: any;
};
}
interface UploadProgress {
loaded: number;
total: number;
percentage: number;
status: 'pending' | 'uploading' | 'completed' | 'failed' | 'paused';
chunk?: number;
totalChunks?: number;
}
interface ChunkMetadata {
chunkIndex: number;
totalChunks: number;
fileId: string;
fileName: string;
fileSize: number;
mimeType: string;
}
declare class FileUploadService {
private http;
private readonly DEFAULT_CHUNK_SIZE;
private activeUploads;
constructor(http: HttpClient);
upload(config: UploadConfig): Observable<UploadProgress>;
pauseUpload(uploadId: string): void;
resumeUpload(uploadId: string): void;
cancelUpload(uploadId: string): void;
private validateFile;
private uploadFile;
private uploadInChunks;
private getProgress;
static ɵfac: i0.ɵɵFactoryDeclaration<FileUploadService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<FileUploadService>;
}
interface QueueConfig {
maxConcurrent?: number;
priorityLevels?: number;
defaultPriority?: number;
throttleMs?: number;
retryDelayMs?: number;
}
interface QueuedRequest<T = any> {
id: string;
request: HttpRequest<T>;
priority: number;
timestamp: number;
execute: () => Observable<any>;
}
declare class RequestQueueService {
private config;
private queues;
private activeRequests;
private queueSubject;
private requestComplete;
constructor();
setConfig(config: Partial<QueueConfig>): void;
enqueue<T>(request: HttpRequest<T>, execute: () => Observable<any>, priority?: number): Observable<any>;
private processNextRequest;
private processRequest;
private getNextRequest;
private removeFromQueue;
getQueueStatus(): {
activeRequests: number;
queueLengths: number[];
config: {
maxConcurrent?: number;
priorityLevels?: number;
defaultPriority?: number;
throttleMs?: number;
retryDelayMs?: number;
};
};
static ɵfac: i0.ɵɵFactoryDeclaration<RequestQueueService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<RequestQueueService>;
}
interface TransformConfig {
dateFields?: string[];
caseStyle?: 'camelCase' | 'snakeCase' | 'kebabCase';
transforms?: {
[key: string]: (value: any) => any;
};
removeFields?: string[];
addFields?: {
[key: string]: any | ((data: any) => any);
};
xmlToJson?: boolean;
}
declare class ResponseTransformerService {
transform(data: any, config: TransformConfig): any;
private clone;
private transformDates;
private transformCase;
private transformKey;
private applyCustomTransforms;
private removeFields;
private addFields;
private xmlToJson;
private xmlNodeToJson;
static ɵfac: i0.ɵɵFactoryDeclaration<ResponseTransformerService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<ResponseTransformerService>;
}
interface OfflineRequestStore {
id?: number;
url: string;
method: string;
body?: any;
headers?: {
[key: string]: string;
};
timestamp: number;
retryCount: number;
priority: number;
}
interface OfflineConfig {
dbName?: string;
maxRetries?: number;
retryDelay?: number;
maxCacheAge?: number;
syncStrategy?: 'immediate' | 'periodic' | 'manual';
syncInterval?: number;
priorityLevels?: number;
}
declare class OfflineService {
private db;
private online$;
private config;
private syncInProgress;
private syncSubject;
readonly sync$: Observable<void>;
constructor();
setConfig(config: Partial<OfflineConfig>): void;
private initializeDB;
private setupSync;
queueRequest(request: Omit<OfflineRequestStore, 'timestamp' | 'retryCount'>): Promise<void>;
cacheResponse(url: string, response: any): Promise<void>;
getCachedResponse(url: string): Promise<any | null>;
sync(): Promise<void>;
getPendingRequests(): Promise<OfflineRequestStore[]>;
clearCache(): Promise<void>;
clearPendingRequests(): Promise<void>;
isOnline(): Observable<boolean>;
static ɵfac: i0.ɵɵFactoryDeclaration<OfflineService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<OfflineService>;
}
interface WebSocketConfig {
url: string;
protocols?: string | string[];
reconnectAttempts?: number;
reconnectInterval?: number;
heartbeatInterval?: number;
heartbeatMessage?: any;
serializer?: (data: any) => string;
deserializer?: (e: MessageEvent) => any;
}
interface WebSocketMessage<T = any> {
type: string;
data: T;
timestamp?: number;
}
interface WebSocketStatus {
connected: boolean;
attempting: boolean;
attemptCount: number;
}
declare class WebSocketService {
private config;
private wsSubject?;
private messagesSubject;
private statusSubject;
private heartbeatTimer?;
private reconnectCount;
readonly messages$: rxjs.Observable<WebSocketMessage<any>>;
readonly status$: rxjs.Observable<WebSocketStatus>;
connect(config: Partial<WebSocketConfig>): void;
send(message: WebSocketMessage): void;
close(): void;
private initializeWebSocket;
private startHeartbeat;
private stopHeartbeat;
private updateStatus;
private defaultSerializer;
private defaultDeserializer;
static ɵfac: i0.ɵɵFactoryDeclaration<WebSocketService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<WebSocketService>;
}
interface GraphQLConfig {
url: string;
headers?: {
[key: string]: string;
};
fragments?: {
[key: string]: string;
};
batchInterval?: number;
batchMax?: number;
}
interface GraphQLRequest {
query: string;
variables?: {
[key: string]: any;
};
operationName?: string;
}
interface GraphQLResponse<T = any> {
data?: T;
errors?: Array<{
message: string;
locations?: Array<{
line: number;
column: number;
}>;
path?: string[];
extensions?: any;
}>;
}
interface BatchedGraphQLRequest extends GraphQLRequest {
id: string;
}
declare class GraphQLService {
private http;
private config;
private batchQueue;
private batchTimeout?;
constructor(http: HttpClient);
setConfig(config: Partial<GraphQLConfig>): void;
query<T = any>(query: string, variables?: {
[key: string]: any;
}): Observable<T>;
mutation<T = any>(mutation: string, variables?: {
[key: string]: any;
}): Observable<T>;
batchQuery<T = any>(query: string, variables?: {
[key: string]: any;
}): Observable<T>;
private request;
private processBatch;
private processBatchedRequest;
private prepareRequest;
private buildBatchQuery;
private aliasQuery;
static ɵfac: i0.ɵɵFactoryDeclaration<GraphQLService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<GraphQLService>;
}
declare class NgHttpSpringModule {
static ɵfac: i0.ɵɵFactoryDeclaration<NgHttpSpringModule, never>;
static ɵmod: i0.ɵɵNgModuleDeclaration<NgHttpSpringModule, never, [typeof i1.HttpClientModule], never>;
static ɵinj: i0.ɵɵInjectorDeclaration<NgHttpSpringModule>;
}
interface NgHttpSpringConfig {
withAuth?: boolean;
withOffline?: boolean;
withWebSocket?: boolean;
withGraphQL?: boolean;
}
declare function provideNgHttpSpring(config?: NgHttpSpringConfig): Provider[];
export { AuthInterceptor, Delete, ErrorInterceptor, FileUploadService, Get, GraphQLService, Header, HttpError, HttpService, LogLevel, LoggingInterceptor, MemoryCacheService, NgHttpSpringModule, OfflineService, Patch, PathVariable, Post, Put, RequestBody, RequestParam, RequestQueueService, ResponseTransformerService, WebSocketService, authInterceptor, errorInterceptor, loggingInterceptor, provideNgHttpSpring };
export type { AuthConfig, BatchedGraphQLRequest, CacheConfig, CacheEntry, CacheStorage, ChunkMetadata, ErrorConfig, ErrorHandler, GraphQLConfig, GraphQLRequest, GraphQLResponse, HttpConfig, LogConfig, NgHttpSpringConfig, OfflineConfig, QueueConfig, QueuedRequest, RequestMetadata, TokenResponse, TransformConfig, UploadConfig, UploadProgress, WebSocketConfig, WebSocketMessage, WebSocketStatus };