@mp-front/common 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +280 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1 +1,280 @@
|
|
|
1
|
-
# front
|
|
1
|
+
# @mp-front/common
|
|
2
|
+
|
|
3
|
+
Biblioteca de utilidades comunes para aplicaciones frontend con TypeScript, diseñada para proporcionar funcionalidades esenciales como autenticación, manejo de caché, HTTP client, logging y más.
|
|
4
|
+
|
|
5
|
+
## 📦 Instalación
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @mp-front/common
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 🏗️ Arquitectura
|
|
12
|
+
|
|
13
|
+
La biblioteca está organizada en módulos especializados con exportaciones modulares:
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
src/
|
|
17
|
+
├── adapters/ # Adaptadores para servicios externos
|
|
18
|
+
├── auth/ # Servicios de autenticación
|
|
19
|
+
├── cache/ # Manejadores de caché (sesión, terminal)
|
|
20
|
+
├── cache-providers/ # Proveedores de caché (Redis)
|
|
21
|
+
├── engine/ # Motores de autenticación (Entra ID)
|
|
22
|
+
├── errors/ # Manejo de errores y excepciones
|
|
23
|
+
├── helpers/ # Utilidades (logger, encriptación, codificación)
|
|
24
|
+
├── http/ # Cliente HTTP con RxJS
|
|
25
|
+
├── middleware/ # Middlewares para APIs
|
|
26
|
+
├── rxjs/ # Utilidades RxJS (loading handler)
|
|
27
|
+
└── types.ts # Tipos globales
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 📋 Módulos Disponibles
|
|
31
|
+
|
|
32
|
+
### 🔐 Auth
|
|
33
|
+
```typescript
|
|
34
|
+
import { AuthorizationService } from '@mp-front/common/auth'
|
|
35
|
+
|
|
36
|
+
const authService = new AuthorizationService()
|
|
37
|
+
authService.get().subscribe(token => {
|
|
38
|
+
console.log('Token:', token)
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### 🚀 Engine
|
|
43
|
+
```typescript
|
|
44
|
+
import { AuthEngine } from '@mp-front/common/engine'
|
|
45
|
+
|
|
46
|
+
const authEngine = new AuthEngine()
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 🌐 HTTP Client
|
|
50
|
+
```typescript
|
|
51
|
+
import { HttpClient } from '@mp-front/common/http'
|
|
52
|
+
|
|
53
|
+
const client = new HttpClient()
|
|
54
|
+
|
|
55
|
+
// GET request
|
|
56
|
+
client.get<User>('/api/users/1').subscribe(user => {
|
|
57
|
+
console.log(user)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
// POST request
|
|
61
|
+
client.post<User>('/api/users', { name: 'John' }).subscribe(newUser => {
|
|
62
|
+
console.log(newUser)
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 🗄️ Cache
|
|
67
|
+
```typescript
|
|
68
|
+
import { SessionCache, TerminalCache } from '@mp-front/common/cache'
|
|
69
|
+
|
|
70
|
+
// Session Cache
|
|
71
|
+
const sessionCache = new SessionCache('userId')
|
|
72
|
+
const session = await sessionCache.getBasicSession()
|
|
73
|
+
|
|
74
|
+
// Terminal Cache
|
|
75
|
+
const terminalCache = new TerminalCache()
|
|
76
|
+
await terminalCache.saveTerminalData('keySeller', terminalData)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 🔧 Helpers
|
|
80
|
+
```typescript
|
|
81
|
+
import { Logger, Encoder, Encrypter } from '@mp-front/common/helpers'
|
|
82
|
+
|
|
83
|
+
// Logger
|
|
84
|
+
const logger = new Logger()
|
|
85
|
+
logger.logInfo('Application started')
|
|
86
|
+
logger.logError('Error occurred')
|
|
87
|
+
|
|
88
|
+
// Encoder
|
|
89
|
+
const encoder = new Encoder()
|
|
90
|
+
const encoded = encoder.encode(data, requestId)
|
|
91
|
+
|
|
92
|
+
// Encrypter
|
|
93
|
+
const encrypter = new Encrypter()
|
|
94
|
+
const encrypted = encrypter.encrypt('sensitive data')
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 📡 Cache Providers
|
|
98
|
+
```typescript
|
|
99
|
+
import { RedisCache } from '@mp-front/common/cache-providers'
|
|
100
|
+
|
|
101
|
+
const redis = new RedisCache<UserData>()
|
|
102
|
+
await redis.setRedisState({
|
|
103
|
+
idApi: 'user:123',
|
|
104
|
+
idData: 'profile',
|
|
105
|
+
body: userData,
|
|
106
|
+
expire: 3600
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### ❌ Error Handling
|
|
111
|
+
```typescript
|
|
112
|
+
import { ErrorHandler, RuntimeError } from '@mp-front/common/errors'
|
|
113
|
+
|
|
114
|
+
// Error Handler
|
|
115
|
+
ErrorHandler.getInstance().getSubject().subscribe(error => {
|
|
116
|
+
console.error('Global error:', error)
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
// Custom Runtime Error
|
|
120
|
+
throw new RuntimeError('VALIDATION_ERROR', 'Invalid input data')
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### 🔄 RxJS Utilities
|
|
124
|
+
```typescript
|
|
125
|
+
import { LoadingHandler } from '@mp-front/common/rxjs'
|
|
126
|
+
|
|
127
|
+
// Loading state management
|
|
128
|
+
LoadingHandler.getInstance().getSubject().subscribe(isLoading => {
|
|
129
|
+
console.log('Loading:', isLoading)
|
|
130
|
+
})
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## ⚙️ Configuración
|
|
134
|
+
|
|
135
|
+
### Variables de Entorno
|
|
136
|
+
|
|
137
|
+
```env
|
|
138
|
+
# Logging
|
|
139
|
+
NEXT_PUBLIC_APP_LOGS_NAME=MyApp
|
|
140
|
+
NEXT_PUBLIC_LOGS_LEVEL=debug
|
|
141
|
+
NEXT_PUBLIC_SILENT_LOGS=false
|
|
142
|
+
|
|
143
|
+
# Authentication
|
|
144
|
+
API_AUTH_BACK_URL=https://api.example.com/auth
|
|
145
|
+
API_AUTH_BACK_USERNAME_AUTH=username
|
|
146
|
+
API_AUTH_BACK_PASSWORD_AUTH=password
|
|
147
|
+
ID_FRONT=frontend-app-id
|
|
148
|
+
|
|
149
|
+
# Redis
|
|
150
|
+
REDIS_URL=redis://localhost:6379
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Peer Dependencies
|
|
154
|
+
|
|
155
|
+
```json
|
|
156
|
+
{
|
|
157
|
+
"ioredis": "5.3.2",
|
|
158
|
+
"next-auth": "4.24.13",
|
|
159
|
+
"node-jose": "2.2.0",
|
|
160
|
+
"rxjs": "7.8.1"
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## 🔨 Casos de Uso
|
|
165
|
+
|
|
166
|
+
### 1. Cliente HTTP con Autenticación
|
|
167
|
+
```typescript
|
|
168
|
+
import { HttpClient, AuthorizationService } from '@mp-front/common'
|
|
169
|
+
|
|
170
|
+
const client = new HttpClient()
|
|
171
|
+
const auth = new AuthorizationService()
|
|
172
|
+
|
|
173
|
+
auth.get().subscribe(token => {
|
|
174
|
+
client.get('/api/protected', {
|
|
175
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
176
|
+
}).subscribe(data => {
|
|
177
|
+
console.log('Protected data:', data)
|
|
178
|
+
})
|
|
179
|
+
})
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### 2. Manejo de Sesión con Cache
|
|
183
|
+
```typescript
|
|
184
|
+
import { SessionCache } from '@mp-front/common/cache'
|
|
185
|
+
|
|
186
|
+
const sessionCache = new SessionCache('user123')
|
|
187
|
+
|
|
188
|
+
// Obtener sesión básica
|
|
189
|
+
const basicSession = await sessionCache.getBasicSession()
|
|
190
|
+
|
|
191
|
+
// Obtener sesión con datos de tienda
|
|
192
|
+
const fullSession = await sessionCache.getUserAndShoppingStore()
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### 3. Logging Estructurado
|
|
196
|
+
```typescript
|
|
197
|
+
import { Logger } from '@mp-front/common/helpers'
|
|
198
|
+
|
|
199
|
+
const logger = new Logger()
|
|
200
|
+
|
|
201
|
+
// Diferentes niveles de log
|
|
202
|
+
logger.logError('Database connection failed')
|
|
203
|
+
logger.logWarn('Deprecated API usage')
|
|
204
|
+
logger.logInfo('User logged in')
|
|
205
|
+
logger.logDebug('Processing request', JSON.stringify(requestData))
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### 4. Manejo Global de Errores
|
|
209
|
+
```typescript
|
|
210
|
+
import { ErrorHandler, RuntimeError } from '@mp-front/common/errors'
|
|
211
|
+
|
|
212
|
+
// Suscribirse a errores globales
|
|
213
|
+
ErrorHandler.getInstance().getSubject().subscribe(error => {
|
|
214
|
+
// Mostrar notificación de error
|
|
215
|
+
showErrorNotification(error.message)
|
|
216
|
+
})
|
|
217
|
+
|
|
218
|
+
// Lanzar error personalizado
|
|
219
|
+
if (!isValid) {
|
|
220
|
+
throw new RuntimeError('VALIDATION_ERROR', 'Los datos no son válidos')
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### 5. Estado de Carga Global
|
|
225
|
+
```typescript
|
|
226
|
+
import { LoadingHandler } from '@mp-front/common/rxjs'
|
|
227
|
+
|
|
228
|
+
// Mostrar/ocultar spinner global
|
|
229
|
+
LoadingHandler.getInstance().getSubject().subscribe(isLoading => {
|
|
230
|
+
document.getElementById('spinner').style.display = isLoading ? 'block' : 'none'
|
|
231
|
+
})
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## 🔧 Desarrollo
|
|
235
|
+
|
|
236
|
+
### Scripts Disponibles
|
|
237
|
+
```bash
|
|
238
|
+
npm run build # Compilar la biblioteca
|
|
239
|
+
npm run lint # Ejecutar linter
|
|
240
|
+
npm run package # Crear paquete NPM
|
|
241
|
+
npm run publish-canary # Publicar versión canary
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### Estructura de Build
|
|
245
|
+
- **ESM**: `dist/mp-front-common-*.js`
|
|
246
|
+
- **CommonJS**: `dist/mp-front-common-*.cjs`
|
|
247
|
+
- **Types**: `dist/**/*.d.ts`
|
|
248
|
+
|
|
249
|
+
## 📝 Tipos TypeScript
|
|
250
|
+
|
|
251
|
+
La biblioteca incluye definiciones de tipos completas:
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
import type { HttpOptions, Method, RequestConfig } from '@mp-front/common/http'
|
|
255
|
+
import type { ITerminal } from '@mp-front/common/cache'
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## 🚀 Características
|
|
259
|
+
|
|
260
|
+
- ✅ **TypeScript nativo** con tipos completos
|
|
261
|
+
- ✅ **Modular** - importa solo lo que necesitas
|
|
262
|
+
- ✅ **RxJS** para programación reactiva
|
|
263
|
+
- ✅ **Redis** para caché distribuido
|
|
264
|
+
- ✅ **Logging** estructurado con niveles
|
|
265
|
+
- ✅ **Encriptación** y codificación de datos
|
|
266
|
+
- ✅ **Manejo de errores** centralizado
|
|
267
|
+
- ✅ **Next.js** y **NextAuth** compatible
|
|
268
|
+
- ✅ **ESM** y **CommonJS** support
|
|
269
|
+
|
|
270
|
+
## 📄 Licencia
|
|
271
|
+
|
|
272
|
+
Privada - Uso interno únicamente
|
|
273
|
+
|
|
274
|
+
## 🤝 Contribución
|
|
275
|
+
|
|
276
|
+
1. Fork el repositorio
|
|
277
|
+
2. Crea una rama feature (`git checkout -b feature/nueva-funcionalidad`)
|
|
278
|
+
3. Commit tus cambios (`git commit -am 'Agregar nueva funcionalidad'`)
|
|
279
|
+
4. Push a la rama (`git push origin feature/nueva-funcionalidad`)
|
|
280
|
+
5. Crea un Pull Request
|