u-mapsnpm
v1.9.1
Published
Core utilities, Angular helpers, shared types, and UI base for U-Maps platform
Downloads
2,203
Maintainers
Readme
u-mapsnpm
Core utilities, Angular infrastructure, and shared types for the U-Maps platform.
Installation
npm install u-mapsnpmEntry Points
import { capitalize, clamp, formatDate } from 'u-mapsnpm';
import { HttpService, API_URL, createLoadingState } from 'u-mapsnpm/angular';
import type { ApiResponse, BaseEntity } from 'u-mapsnpm/types';
import { UiBaseModule } from 'u-mapsnpm/ui-base';Core Utilities
Framework-agnostic yordamchi funksiyalar.
String
import { capitalize, truncate, toKebabCase, toCamelCase } from 'u-mapsnpm';
capitalize('hello'); // 'Hello'
truncate('long text here', 8); // 'long tex…'
toKebabCase('helloWorld'); // 'hello-world'
toCamelCase('hello-world'); // 'helloWorld'Number
import { formatCurrency, clamp, roundTo } from 'u-mapsnpm';
formatCurrency(1500, 'UZS'); // '1 500 UZS'
clamp(15, 0, 10); // 10
roundTo(3.14159, 2); // 3.14Date
import { formatDate, isToday, daysBetween } from 'u-mapsnpm';
formatDate(new Date());
isToday(new Date()); // true
daysBetween(new Date('2025-01-01'), new Date()); // kunlar soniAngular
Setup
import {
API_URL,
AUTH_CONFIG,
LANGUAGE_CONFIG,
GEOLOCATION_CONFIG,
AUTH_LOGIN_ROUTE,
AUTH_HOME_ROUTE,
ERROR_HANDLER_CONFIG,
authInterceptor,
errorInterceptor,
} from 'u-mapsnpm/angular';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),
{ provide: API_URL, useValue: 'https://api.example.com/v1' },
{ provide: AUTH_CONFIG, useValue: {
loginUrl: '/auth/login',
refreshUrl: '/auth/refresh',
logoutUrl: '/auth/logout',
prefix: 'my_app',
}},
{ provide: LANGUAGE_CONFIG, useValue: {
defaultLang: 'uz',
supportedLangs: ['uz', 'oz', 'ru'],
}},
{ provide: GEOLOCATION_CONFIG, useValue: {
fallback: { lng: 69.2401, lat: 41.2995 },
bounds: { minLng: 55.99, maxLng: 73.13, minLat: 37.17, maxLat: 45.59 },
}},
{ provide: AUTH_LOGIN_ROUTE, useValue: '/auth/login' },
{ provide: AUTH_HOME_ROUTE, useValue: '/dashboard' },
{ provide: ERROR_HANDLER_CONFIG, useValue: {
on401: () => console.log('Unauthorized'),
on403: () => console.log('Forbidden'),
on404: () => console.log('Not found'),
onServerError: (err) => console.error('Server error', err),
onNetworkError: () => console.error('Network error'),
excludeUrls: ['/auth/refresh'],
}},
],
});HttpService
import { HttpService } from 'u-mapsnpm/angular';
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpService);
getUsers() {
return this.http.getList<User>('/users');
}
getUser(id: string) {
return this.http.get<User>(`/users/${id}`);
}
createUser(data: CreateUserDto) {
return this.http.post<User>('/users', data);
}
updateUser(id: string, data: UpdateUserDto) {
return this.http.put<User>(`/users/${id}`, data);
}
deleteUser(id: string) {
return this.http.delete(`/users/${id}`);
}
}TokenStorageService
import { TokenStorageService } from 'u-mapsnpm/angular';
const tokenService = inject(TokenStorageService);
tokenService.setAccessToken('jwt-token'); // sessionStorage
tokenService.setRefreshToken('refresh-tok'); // localStorage
tokenService.getAccessToken(); // string | null
tokenService.getRefreshToken(); // string | null
tokenService.setStoredUser({ id: 1, name: 'Ali' });
tokenService.getStoredUser();
tokenService.hasToken(); // boolean
tokenService.clear(); // barcha token va user ma'lumotlarini o'chiradiLoadingService
import { LoadingService } from 'u-mapsnpm/angular';
const loading = inject(LoadingService);
loading.show(); // counter++
loading.show(); // counter++ (parallel request)
loading.hide(); // counter--
loading.hide(); // counter = 0, isLoading = false
loading.reset(); // counter = 0
// Template
@Component({
template: `@if (loading.isLoading()) { <app-spinner /> }`,
})LanguageService
import { LanguageService } from 'u-mapsnpm/angular';
const lang = inject(LanguageService);
lang.currentLang(); // 'uz' (Signal)
lang.supportedLangs; // ['uz', 'ru']
lang.setLanguage('ru');
lang.toggleLanguage(); // keyingi tilga o'tadi
lang.isLang('uz'); // Signal<boolean>GeolocationService
import { GeolocationService } from 'u-mapsnpm/angular';
const geo = inject(GeolocationService);
geo.requestPosition();
geo.position(); // Signal<{ lng, lat } | null>
geo.positionOrFallback(); // Signal<{ lng, lat }> (doim qiymat qaytaradi)
geo.error(); // Signal<string | null>
geo.isLocating(); // Signal<boolean>
geo.isWithinBounds(69.24, 41.30); // true
geo.reset();Interceptors
authInterceptor
- Har bir so'rovga
Authorization: Bearer <token>qo'shadi - 401 da refresh token orqali avtomatik yangilaydi
- Refresh paytida boshqa so'rovlarni navbatga qo'yadi
- camelCase va snake_case auth javoblarini qo'llab-quvvatlaydi
errorInterceptor
- Status-specific callback-lar:
on401,on403,on404,onServerError,onNetworkError excludeUrlsorqali ma'lum URL-larni chiqarib tashlash mumkin
Guards
import { authGuard, guestGuard } from 'u-mapsnpm/angular';
const routes: Routes = [
// Faqat autentifikatsiya qilingan foydalanuvchilar
{ path: 'dashboard', canActivate: [authGuard], component: DashboardComponent },
// Faqat mehmonlar (login/register)
{ path: 'login', canActivate: [guestGuard], component: LoginComponent },
];Helpers
createLoadingState
import { createLoadingState } from 'u-mapsnpm/angular';
const state = createLoadingState<User[]>();
state.loading(); // Signal<boolean>
state.data(); // Signal<User[] | null>
state.error(); // Signal<string | null>
state.setLoading(true);
state.set([user1, user2]);
state.setError('Failed to load');
state.reset();Destroy Helpers
import { injectDestroy, takeUntilDestroyed } from 'u-mapsnpm/angular';
export class MyComponent {
private destroy$ = injectDestroy();
ngOnInit() {
obs$.pipe(takeUntil(this.destroy$)).subscribe();
// yoki
obs$.pipe(takeUntilDestroyed()).subscribe();
}
}RxJS Helpers
import { mapResponse, handleError } from 'u-mapsnpm/angular';
// Discriminated union
this.http.get<User>('/user/1').pipe(
mapResponse(),
).subscribe(result => {
if (result.success) console.log(result.data);
else console.error(result.error);
});
// Fallback
this.http.get<User[]>('/users').pipe(
handleError([]),
).subscribe();Types
import type {
ApiResponse,
PaginatedResponse,
ApiMeta,
PaginationMeta,
ApiError,
BaseEntity,
Identifiable,
SoftDeletable,
LoginRequest,
AuthResponse,
UserResponse,
RefreshRequest,
AuthConfig,
} from 'u-mapsnpm/types';API Response
interface ApiResponse<T> {
success: boolean;
data: T;
meta?: ApiMeta;
error?: ApiError;
}
interface PaginatedResponse<T> {
success: boolean;
data: T[];
pagination: PaginationMeta;
meta?: ApiMeta;
}
interface PaginationMeta {
page: number;
pageSize: number;
totalItems: number;
totalPages: number;
}Entity
interface BaseEntity {
id: string | number;
createdAt: string;
updatedAt: string;
}
interface SoftDeletable {
deletedAt: string | null;
isDeleted: boolean;
}UI Base
import { UiBaseModule } from 'u-mapsnpm/ui-base';
@Component({
imports: [UiBaseModule], // TuiRoot, TuiButton, TuiIcon
})
export class AppComponent {}Peer Dependencies
| Package | Version | Required |
|---------|---------|----------|
| @angular/core | >=19.0.0 | Optional |
| @angular/common | >=19.0.0 | Optional |
| @angular/router | >=19.0.0 | Optional |
| @taiga-ui/core | >=4.0.0 | Optional |
| @taiga-ui/kit | >=4.0.0 | Optional |
| @taiga-ui/icons | >=4.0.0 | Optional |
| rxjs | >=7.0.0 | Optional |
| tslib | ^2.8.0 | Required |
Angular, Taiga UI va RxJS faqat u-mapsnpm/angular yoki u-mapsnpm/ui-base ishlatganda kerak.
License
MIT
