@cms-libs/http
v1.0.10
Published
A lightweight, extensible HTTP utility library for Angular projects that simplifies API requests, error handling, file downloads, and caching. This library provides a base HTTP service (`BaseHttpService`) with common CRUD operations and a `CommonHttpSer
Readme
Angular Base HTTP Service Library
A lightweight, extensible HTTP utility library for Angular projects that simplifies API requests, error handling, file downloads, and caching.
This library provides a base HTTP service (BaseHttpService) with common CRUD operations and a CommonHttpService extension that integrates caching and global error handling via an event bus.
✨ Features
- 🔗 Base URL support – automatically appends endpoint paths.
- 📄 CRUD operations –
get,post,put,patch,delete. - 💾 File downloads with file-saver.
- 🔄 FormData conversion from JSON objects.
- ⚡ Centralized error handling with
AppError. - 🛠 Customizable response mapping to adapt to any backend structure.
- 🧩 Cache support with @ngneat/cashew.
- 📢 Global error broadcasting with ng-event-bus.
📦 Installation
npm install @ngneat/cashew ng-event-bus @cms-libs/httpMake sure HttpClient is imported in your app.config.ts:
import { provideHttpClient, withInterceptors } from "@angular/common/http";
import { provideHttpCache, withHttpCacheInterceptor } from "@ngneat/cashew";
import { ApplicationConfig, provideZoneChangeDetection } from "@angular/core";
import { NgEventBus } from "ng-event-bus";
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
// your app providers
NgEventBus,
provideHttpClient(withInterceptors([withHttpCacheInterceptor()])),
provideHttpCache(),
],
};🚀 Usage
1. Extend BaseHttpService
import { Injectable } from '@angular/core';
import { CommonHttpService } from '@cms-libs/http';
const BASE_URL = 'http://localhost:3000';
@Injectable()
export class UsersService extends BaseHttpService {
constructor() {
super(`${BASE_URL}/api/users`); // Base URL for users endpoints
}
}2. Perform API Requests
// inside a component or another service
this.usersService.get<User[]>()
.subscribe({
next: (res) => console.log('Users:', res.data),
error: (err) => console.error('Error:', err),
});3. Download Files
this.usersService.download('export', 'users', 'csv')
.subscribe(() => console.log('File downloaded!'));4. Convert JSON to FormData
const formData = this.usersService.parseToFormData({ name: 'John', avatar: file });🧩 Advanced: Using CommonHttpService
CommonHttpService extends BaseHttpService and adds:
- Cache invalidation with Cashew.
- Error broadcasting with
NgEventBus.
import { Injectable } from '@angular/core';
import { CommonHttpService } from '@cms-libs/http';
const BASE_URL = 'http://localhost:3000';
@Injectable({ providedIn: 'root' })
export class ProductsService extends CommonHttpService {
constructor() {
super(`${BASE_URL}/api/products`);
}
}Invalidate Cache
this.productsService.invalidateCache();Listen to Errors
this.eventBus.on('http:error').subscribe((error) => {
console.error('Global HTTP error:', error);
// display your error as you wish...
});📑 Interfaces
BaseResponse<T>
export interface BaseResponse<T> {
message?: string;
success?: boolean;
data: T;
statusCode?: number;
errors?: any[];
}ListResponse<T>
export interface ListResponse<T> {
data: T[];
total: number;
metadata?: any;
}AppError
export class AppError {
constructor(
public message?: string,
public cause?: any,
) {}
}🔧 Customizing Response Mapping
If your backend response does not match BaseResponse, override mapResponse in BaseHttpService:
override mapResponse<T>(response: any) {
return {
data: response.data,
success: response.status,
statusCode: response.code,
message: response.msg,
};
}