@geekmidas/services 0.0.1
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 +510 -0
- package/dist/index.cjs +179 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +214 -0
- package/dist/index.d.mts +214 -0
- package/dist/index.mjs +178 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +30 -0
- package/src/__tests__/index.spec.ts +566 -0
- package/src/index.ts +279 -0
- package/tsdown.config.ts +3 -0
package/README.md
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
# @geekmidas/services
|
|
2
|
+
|
|
3
|
+
Service discovery and dependency injection system for TypeScript applications with full type safety and automatic lifecycle management.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Type-Safe Services**: Full TypeScript support with generic type inference
|
|
8
|
+
- **Lazy Initialization**: Services are initialized only when needed
|
|
9
|
+
- **Singleton Pattern**: Services are cached and reused across requests
|
|
10
|
+
- **Dependency Injection**: Automatic service resolution and injection
|
|
11
|
+
- **Environment Integration**: Seamless integration with @geekmidas/envkit
|
|
12
|
+
- **Service Discovery**: Centralized service registry and discovery
|
|
13
|
+
- **Error Handling**: Graceful error handling during service initialization
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pnpm add @geekmidas/services
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
### Define a Service
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import type { Service } from '@geekmidas/services';
|
|
27
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
28
|
+
import { Kysely } from 'kysely';
|
|
29
|
+
|
|
30
|
+
// Define your database service
|
|
31
|
+
const databaseService = {
|
|
32
|
+
serviceName: 'database' as const,
|
|
33
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
34
|
+
const config = envParser.create((get) => ({
|
|
35
|
+
url: get('DATABASE_URL').string(),
|
|
36
|
+
ssl: get('DATABASE_SSL').string().transform(Boolean).default('false')
|
|
37
|
+
})).parse();
|
|
38
|
+
|
|
39
|
+
const db = new Kysely({ /* config */ });
|
|
40
|
+
await db.connection().execute('SELECT 1'); // Health check
|
|
41
|
+
|
|
42
|
+
return db;
|
|
43
|
+
}
|
|
44
|
+
} satisfies Service<'database', Kysely<Database>>;
|
|
45
|
+
|
|
46
|
+
export { databaseService };
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Use Services in Constructs
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { e } from '@geekmidas/constructs/endpoints';
|
|
53
|
+
import { databaseService } from './services/database';
|
|
54
|
+
import { z } from 'zod';
|
|
55
|
+
|
|
56
|
+
export const getUser = e
|
|
57
|
+
.get('/users/:id')
|
|
58
|
+
.params(z.object({ id: z.string() }))
|
|
59
|
+
.services([databaseService])
|
|
60
|
+
.handle(async ({ params, services }) => {
|
|
61
|
+
// services.database is fully typed as Kysely<Database>
|
|
62
|
+
const user = await services.database
|
|
63
|
+
.selectFrom('users')
|
|
64
|
+
.where('id', '=', params.id)
|
|
65
|
+
.selectAll()
|
|
66
|
+
.executeTakeFirstOrThrow();
|
|
67
|
+
|
|
68
|
+
return user;
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Service Discovery
|
|
73
|
+
|
|
74
|
+
The ServiceDiscovery class manages service lifecycle and dependency injection:
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
78
|
+
import { ConsoleLogger } from '@geekmidas/logger/console';
|
|
79
|
+
import { EnvironmentParser } from '@geekmidas/envkit';
|
|
80
|
+
|
|
81
|
+
const logger = new ConsoleLogger();
|
|
82
|
+
const envParser = new EnvironmentParser(process.env).create(() => ({})).parse();
|
|
83
|
+
|
|
84
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(logger, envParser);
|
|
85
|
+
|
|
86
|
+
// Services are lazily initialized
|
|
87
|
+
const database = await serviceDiscovery.discover(databaseService);
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Creating Services
|
|
91
|
+
|
|
92
|
+
### Database Service
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
import type { Service } from '@geekmidas/services';
|
|
96
|
+
import { Kysely, PostgresDialect } from 'kysely';
|
|
97
|
+
import { Pool } from 'pg';
|
|
98
|
+
|
|
99
|
+
const databaseService = {
|
|
100
|
+
serviceName: 'database' as const,
|
|
101
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
102
|
+
const config = envParser.create((get) => ({
|
|
103
|
+
host: get('DB_HOST').string(),
|
|
104
|
+
port: get('DB_PORT').string().transform(Number).default('5432'),
|
|
105
|
+
database: get('DB_NAME').string(),
|
|
106
|
+
user: get('DB_USER').string(),
|
|
107
|
+
password: get('DB_PASSWORD').string(),
|
|
108
|
+
ssl: get('DB_SSL').string().transform(Boolean).default('false')
|
|
109
|
+
})).parse();
|
|
110
|
+
|
|
111
|
+
const db = new Kysely<Database>({
|
|
112
|
+
dialect: new PostgresDialect({
|
|
113
|
+
pool: new Pool({
|
|
114
|
+
host: config.host,
|
|
115
|
+
port: config.port,
|
|
116
|
+
database: config.database,
|
|
117
|
+
user: config.user,
|
|
118
|
+
password: config.password,
|
|
119
|
+
ssl: config.ssl
|
|
120
|
+
})
|
|
121
|
+
})
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return db;
|
|
125
|
+
}
|
|
126
|
+
} satisfies Service<'database', Kysely<Database>>;
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Redis/Cache Service
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import type { Service } from '@geekmidas/services';
|
|
133
|
+
import { UpstashCache } from '@geekmidas/cache/upstash';
|
|
134
|
+
|
|
135
|
+
const cacheService = {
|
|
136
|
+
serviceName: 'cache' as const,
|
|
137
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
138
|
+
const config = envParser.create((get) => ({
|
|
139
|
+
url: get('UPSTASH_REDIS_URL').string().url(),
|
|
140
|
+
token: get('UPSTASH_REDIS_TOKEN').string()
|
|
141
|
+
})).parse();
|
|
142
|
+
|
|
143
|
+
return new UpstashCache({
|
|
144
|
+
url: config.url,
|
|
145
|
+
token: config.token
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
} satisfies Service<'cache', UpstashCache<any>>;
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Email Service
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
import type { Service } from '@geekmidas/services';
|
|
155
|
+
import { createEmailClient } from '@geekmidas/emailkit';
|
|
156
|
+
import * as templates from './email-templates';
|
|
157
|
+
|
|
158
|
+
const emailService = {
|
|
159
|
+
serviceName: 'email' as const,
|
|
160
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
161
|
+
const config = envParser.create((get) => ({
|
|
162
|
+
host: get('SMTP_HOST').string(),
|
|
163
|
+
port: get('SMTP_PORT').string().transform(Number),
|
|
164
|
+
user: get('SMTP_USER').string(),
|
|
165
|
+
pass: get('SMTP_PASS').string(),
|
|
166
|
+
from: get('EMAIL_FROM').string().email()
|
|
167
|
+
})).parse();
|
|
168
|
+
|
|
169
|
+
return createEmailClient({
|
|
170
|
+
smtp: {
|
|
171
|
+
host: config.host,
|
|
172
|
+
port: config.port,
|
|
173
|
+
auth: {
|
|
174
|
+
user: config.user,
|
|
175
|
+
pass: config.pass
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
templates,
|
|
179
|
+
defaults: { from: config.from }
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
} satisfies Service<'email', ReturnType<typeof createEmailClient>>;
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Event Publisher Service
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
import type { Service } from '@geekmidas/services';
|
|
189
|
+
import type { EventPublisher, PublishableMessage } from '@geekmidas/events';
|
|
190
|
+
|
|
191
|
+
type UserEvents =
|
|
192
|
+
| PublishableMessage<'user.created', { userId: string }>
|
|
193
|
+
| PublishableMessage<'user.updated', { userId: string }>;
|
|
194
|
+
|
|
195
|
+
const userEventPublisher = {
|
|
196
|
+
serviceName: 'userEventPublisher' as const,
|
|
197
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
198
|
+
const config = envParser.create((get) => ({
|
|
199
|
+
publisherUrl: get('EVENT_PUBLISHER_URL').string()
|
|
200
|
+
})).parse();
|
|
201
|
+
|
|
202
|
+
const { Publisher } = await import('@geekmidas/events');
|
|
203
|
+
return Publisher.fromConnectionString<UserEvents>(config.publisherUrl);
|
|
204
|
+
}
|
|
205
|
+
} satisfies Service<'userEventPublisher', EventPublisher<UserEvents>>;
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Multiple Services
|
|
209
|
+
|
|
210
|
+
Inject multiple services into a construct:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
import { e } from '@geekmidas/constructs/endpoints';
|
|
214
|
+
import { databaseService } from './services/database';
|
|
215
|
+
import { cacheService } from './services/cache';
|
|
216
|
+
import { emailService } from './services/email';
|
|
217
|
+
import { z } from 'zod';
|
|
218
|
+
|
|
219
|
+
export const createUser = e
|
|
220
|
+
.post('/users')
|
|
221
|
+
.body(z.object({
|
|
222
|
+
name: z.string(),
|
|
223
|
+
email: z.string().email()
|
|
224
|
+
}))
|
|
225
|
+
.services([databaseService, cacheService, emailService])
|
|
226
|
+
.handle(async ({ body, services }) => {
|
|
227
|
+
// Check cache first
|
|
228
|
+
const cached = await services.cache.get(`user:${body.email}`);
|
|
229
|
+
if (cached) {
|
|
230
|
+
return cached;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Create user in database
|
|
234
|
+
const user = await services.database
|
|
235
|
+
.insertInto('users')
|
|
236
|
+
.values(body)
|
|
237
|
+
.returningAll()
|
|
238
|
+
.executeTakeFirstOrThrow();
|
|
239
|
+
|
|
240
|
+
// Send welcome email
|
|
241
|
+
await services.email.sendTemplate('welcome', {
|
|
242
|
+
to: user.email,
|
|
243
|
+
props: { name: user.name }
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// Cache result
|
|
247
|
+
await services.cache.set(`user:${user.email}`, user, 3600);
|
|
248
|
+
|
|
249
|
+
return user;
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## Service Lifecycle
|
|
254
|
+
|
|
255
|
+
### Lazy Initialization
|
|
256
|
+
|
|
257
|
+
Services are only initialized when first requested:
|
|
258
|
+
|
|
259
|
+
```typescript
|
|
260
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(logger, envParser);
|
|
261
|
+
|
|
262
|
+
// Not initialized yet
|
|
263
|
+
const service1 = databaseService;
|
|
264
|
+
|
|
265
|
+
// Initialized here
|
|
266
|
+
const db = await serviceDiscovery.discover(databaseService);
|
|
267
|
+
|
|
268
|
+
// Reuses same instance (singleton)
|
|
269
|
+
const db2 = await serviceDiscovery.discover(databaseService);
|
|
270
|
+
assert(db === db2); // true
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### Singleton Pattern
|
|
274
|
+
|
|
275
|
+
ServiceDiscovery ensures each service is a singleton:
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
// First call initializes the service
|
|
279
|
+
const db1 = await serviceDiscovery.discover(databaseService);
|
|
280
|
+
|
|
281
|
+
// Subsequent calls return cached instance
|
|
282
|
+
const db2 = await serviceDiscovery.discover(databaseService);
|
|
283
|
+
const db3 = await serviceDiscovery.discover(databaseService);
|
|
284
|
+
|
|
285
|
+
// All references point to same instance
|
|
286
|
+
console.log(db1 === db2 && db2 === db3); // true
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
## Error Handling
|
|
290
|
+
|
|
291
|
+
Handle service initialization errors gracefully:
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
const databaseService = {
|
|
295
|
+
serviceName: 'database' as const,
|
|
296
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
297
|
+
try {
|
|
298
|
+
const config = envParser.create((get) => ({
|
|
299
|
+
url: get('DATABASE_URL').string()
|
|
300
|
+
})).parse();
|
|
301
|
+
|
|
302
|
+
const db = new Kysely({ /* config */ });
|
|
303
|
+
|
|
304
|
+
// Test connection
|
|
305
|
+
await db.connection().execute('SELECT 1');
|
|
306
|
+
|
|
307
|
+
return db;
|
|
308
|
+
} catch (error) {
|
|
309
|
+
throw new Error(`Failed to initialize database: ${error.message}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
} satisfies Service<'database', Kysely<Database>>;
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
## Testing
|
|
316
|
+
|
|
317
|
+
Mock services in tests:
|
|
318
|
+
|
|
319
|
+
```typescript
|
|
320
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
321
|
+
import { vi } from 'vitest';
|
|
322
|
+
|
|
323
|
+
// Create mock database
|
|
324
|
+
const mockDb = {
|
|
325
|
+
selectFrom: vi.fn(() => ({
|
|
326
|
+
where: vi.fn(() => ({
|
|
327
|
+
selectAll: vi.fn(() => ({
|
|
328
|
+
executeTakeFirstOrThrow: vi.fn().mockResolvedValue({
|
|
329
|
+
id: '1',
|
|
330
|
+
name: 'Test User'
|
|
331
|
+
})
|
|
332
|
+
}))
|
|
333
|
+
}))
|
|
334
|
+
}))
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
// Create mock service
|
|
338
|
+
const mockDatabaseService = {
|
|
339
|
+
serviceName: 'database' as const,
|
|
340
|
+
async register() {
|
|
341
|
+
return mockDb;
|
|
342
|
+
}
|
|
343
|
+
} satisfies Service<'database', typeof mockDb>;
|
|
344
|
+
|
|
345
|
+
// Use in tests
|
|
346
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(logger, envParser);
|
|
347
|
+
const db = await serviceDiscovery.discover(mockDatabaseService);
|
|
348
|
+
|
|
349
|
+
// Test your code
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Service Patterns
|
|
353
|
+
|
|
354
|
+
### Repository Pattern
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
import type { Service } from '@geekmidas/services';
|
|
358
|
+
|
|
359
|
+
class UserRepository {
|
|
360
|
+
constructor(private db: Kysely<Database>) {}
|
|
361
|
+
|
|
362
|
+
async findById(id: string) {
|
|
363
|
+
return this.db
|
|
364
|
+
.selectFrom('users')
|
|
365
|
+
.where('id', '=', id)
|
|
366
|
+
.selectAll()
|
|
367
|
+
.executeTakeFirst();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async create(data: NewUser) {
|
|
371
|
+
return this.db
|
|
372
|
+
.insertInto('users')
|
|
373
|
+
.values(data)
|
|
374
|
+
.returningAll()
|
|
375
|
+
.executeTakeFirstOrThrow();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const userRepositoryService = {
|
|
380
|
+
serviceName: 'userRepository' as const,
|
|
381
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
382
|
+
const db = await databaseService.register(envParser);
|
|
383
|
+
return new UserRepository(db);
|
|
384
|
+
}
|
|
385
|
+
} satisfies Service<'userRepository', UserRepository>;
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
### Service Composition
|
|
389
|
+
|
|
390
|
+
```typescript
|
|
391
|
+
import type { Service } from '@geekmidas/services';
|
|
392
|
+
|
|
393
|
+
class UserService {
|
|
394
|
+
constructor(
|
|
395
|
+
private repository: UserRepository,
|
|
396
|
+
private email: EmailClient,
|
|
397
|
+
private cache: Cache
|
|
398
|
+
) {}
|
|
399
|
+
|
|
400
|
+
async createUser(data: NewUser) {
|
|
401
|
+
const user = await this.repository.create(data);
|
|
402
|
+
await this.email.sendTemplate('welcome', {
|
|
403
|
+
to: user.email,
|
|
404
|
+
props: { name: user.name }
|
|
405
|
+
});
|
|
406
|
+
await this.cache.set(`user:${user.id}`, user, 3600);
|
|
407
|
+
return user;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const userServiceService = {
|
|
412
|
+
serviceName: 'userService' as const,
|
|
413
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
414
|
+
const repository = await userRepositoryService.register(envParser);
|
|
415
|
+
const email = await emailService.register(envParser);
|
|
416
|
+
const cache = await cacheService.register(envParser);
|
|
417
|
+
|
|
418
|
+
return new UserService(repository, email, cache);
|
|
419
|
+
}
|
|
420
|
+
} satisfies Service<'userService', UserService>;
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
## TypeScript Types
|
|
424
|
+
|
|
425
|
+
```typescript
|
|
426
|
+
import type { Service } from '@geekmidas/services';
|
|
427
|
+
|
|
428
|
+
// Service interface
|
|
429
|
+
interface Service<TName extends string = string, TInstance = unknown> {
|
|
430
|
+
serviceName: TName;
|
|
431
|
+
register(envParser: EnvironmentParser<{}>): Promise<TInstance> | TInstance;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Infer service name
|
|
435
|
+
type ServiceName<T> = T extends Service<infer N, any> ? N : never;
|
|
436
|
+
|
|
437
|
+
// Infer service instance type
|
|
438
|
+
type ServiceInstance<T> = T extends Service<any, infer I> ? I : never;
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
## Best Practices
|
|
442
|
+
|
|
443
|
+
### 1. Use `satisfies` for Type Safety
|
|
444
|
+
|
|
445
|
+
```typescript
|
|
446
|
+
// ✅ Use satisfies to ensure correct implementation
|
|
447
|
+
const service = {
|
|
448
|
+
serviceName: 'myService' as const,
|
|
449
|
+
async register(envParser) {
|
|
450
|
+
return new MyService();
|
|
451
|
+
}
|
|
452
|
+
} satisfies Service<'myService', MyService>;
|
|
453
|
+
|
|
454
|
+
// ❌ Don't use type annotation (loses type inference)
|
|
455
|
+
const service: Service = {
|
|
456
|
+
serviceName: 'myService',
|
|
457
|
+
async register(envParser) {
|
|
458
|
+
return new MyService();
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
### 2. Use `as const` for Service Names
|
|
464
|
+
|
|
465
|
+
```typescript
|
|
466
|
+
// ✅ Literal type for better type inference
|
|
467
|
+
serviceName: 'database' as const
|
|
468
|
+
|
|
469
|
+
// ❌ String type loses specificity
|
|
470
|
+
serviceName: 'database'
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### 3. Validate Configuration
|
|
474
|
+
|
|
475
|
+
```typescript
|
|
476
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
477
|
+
const config = envParser.create((get) => ({
|
|
478
|
+
url: get('DATABASE_URL').string().url(), // Validates URL format
|
|
479
|
+
port: get('PORT').string().transform(Number).default('5432'),
|
|
480
|
+
ssl: get('SSL').string().transform(Boolean).default('false')
|
|
481
|
+
})).parse();
|
|
482
|
+
|
|
483
|
+
return new Database(config);
|
|
484
|
+
}
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
### 4. Test Connections
|
|
488
|
+
|
|
489
|
+
```typescript
|
|
490
|
+
async register(envParser: EnvironmentParser<{}>) {
|
|
491
|
+
const db = new Database(config);
|
|
492
|
+
|
|
493
|
+
// Test connection during initialization
|
|
494
|
+
await db.connection().execute('SELECT 1');
|
|
495
|
+
|
|
496
|
+
return db;
|
|
497
|
+
}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
## Related Packages
|
|
501
|
+
|
|
502
|
+
- [@geekmidas/constructs](../constructs) - Uses services for dependency injection
|
|
503
|
+
- [@geekmidas/envkit](../envkit) - Environment configuration for services
|
|
504
|
+
- [@geekmidas/logger](../logger) - Logging within services
|
|
505
|
+
- [@geekmidas/cache](../cache) - Cache services
|
|
506
|
+
- [@geekmidas/events](../events) - Event publisher services
|
|
507
|
+
|
|
508
|
+
## License
|
|
509
|
+
|
|
510
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* Service discovery container that manages service registration and retrieval.
|
|
5
|
+
* Implements a singleton pattern with lazy initialization of services.
|
|
6
|
+
*
|
|
7
|
+
* @template TServices - Record type mapping service names to their instance types
|
|
8
|
+
* @template TLogger - Logger type for internal logging
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* // Define service types
|
|
13
|
+
* interface MyServices {
|
|
14
|
+
* database: Database;
|
|
15
|
+
* cache: CacheService;
|
|
16
|
+
* auth: AuthService;
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* // Get service discovery instance
|
|
20
|
+
* const discovery = ServiceDiscovery.getInstance<MyServices>(logger, envParser);
|
|
21
|
+
*
|
|
22
|
+
* // Register services
|
|
23
|
+
* await discovery.register([
|
|
24
|
+
* new DatabaseService(),
|
|
25
|
+
* new CacheService(),
|
|
26
|
+
* new AuthService()
|
|
27
|
+
* ]);
|
|
28
|
+
*
|
|
29
|
+
* // Retrieve services
|
|
30
|
+
* const db = await discovery.get('database');
|
|
31
|
+
* const { cache, auth } = await discovery.getMany(['cache', 'auth']);
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
var ServiceDiscovery = class ServiceDiscovery {
|
|
35
|
+
/** Singleton instance of ServiceDiscovery */
|
|
36
|
+
static _instance;
|
|
37
|
+
/** Map of registered service definitions */
|
|
38
|
+
services = /* @__PURE__ */ new Map();
|
|
39
|
+
/** Map of instantiated service instances */
|
|
40
|
+
instances = /* @__PURE__ */ new Map();
|
|
41
|
+
/**
|
|
42
|
+
* Gets the singleton instance of ServiceDiscovery.
|
|
43
|
+
* Creates a new instance if one doesn't exist.
|
|
44
|
+
*
|
|
45
|
+
* @template T - Record type mapping service names to their instance types
|
|
46
|
+
* @template TLogger - Logger type for internal logging
|
|
47
|
+
* @param logger - Logger instance for service logging
|
|
48
|
+
* @param envParser - Environment parser for service configuration
|
|
49
|
+
* @returns The ServiceDiscovery singleton instance
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* const services = ServiceDiscovery.getInstance<MyServices>(logger, envParser);
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
static getInstance(logger, envParser) {
|
|
57
|
+
if (!ServiceDiscovery._instance) ServiceDiscovery._instance = new ServiceDiscovery(logger, envParser);
|
|
58
|
+
return ServiceDiscovery._instance;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Private constructor to enforce singleton pattern.
|
|
62
|
+
*
|
|
63
|
+
* @param logger - Logger instance for service logging
|
|
64
|
+
* @param envParser - Environment parser for service configuration
|
|
65
|
+
* @private
|
|
66
|
+
*/
|
|
67
|
+
constructor(logger, envParser) {
|
|
68
|
+
this.logger = logger;
|
|
69
|
+
this.envParser = envParser;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Register multiple services with the service discovery.
|
|
73
|
+
* Services are instantiated lazily on first access.
|
|
74
|
+
* Already instantiated services are returned from cache.
|
|
75
|
+
*
|
|
76
|
+
* @template T - Array type of services to register
|
|
77
|
+
* @param services - Array of services to register
|
|
78
|
+
* @returns Promise resolving to a record of service names to instances
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```typescript
|
|
82
|
+
* const services = await discovery.register([
|
|
83
|
+
* new DatabaseService(),
|
|
84
|
+
* new CacheService(),
|
|
85
|
+
* new AuthService()
|
|
86
|
+
* ]);
|
|
87
|
+
*
|
|
88
|
+
* // services = {
|
|
89
|
+
* // database: Database instance,
|
|
90
|
+
* // cache: CacheService instance,
|
|
91
|
+
* // auth: AuthService instance
|
|
92
|
+
* // }
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
async register(services) {
|
|
96
|
+
const registeredServices = {};
|
|
97
|
+
for (const service of services) {
|
|
98
|
+
const name = service.serviceName;
|
|
99
|
+
if (this.instances.has(name)) {
|
|
100
|
+
registeredServices[name] = this.instances.get(name);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const instance = await service.register(this.envParser);
|
|
104
|
+
this.instances.set(name, instance);
|
|
105
|
+
registeredServices[name] = instance;
|
|
106
|
+
}
|
|
107
|
+
return registeredServices;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get a service from the service discovery.
|
|
111
|
+
* Services are instantiated on first access if not already cached.
|
|
112
|
+
*
|
|
113
|
+
* @template K - The service name key
|
|
114
|
+
* @param name - The name of the service to get
|
|
115
|
+
* @returns Promise resolving to the service instance
|
|
116
|
+
* @throws {Error} If the service is not registered
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* ```typescript
|
|
120
|
+
* const database = await discovery.get('database');
|
|
121
|
+
* const users = await database.query('SELECT * FROM users');
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
get(name) {
|
|
125
|
+
const service = this.services.get(name);
|
|
126
|
+
if (!service) throw new Error(`Service '${name}' not found in service discovery`);
|
|
127
|
+
return service.register(this.envParser);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Get multiple services from the service discovery.
|
|
131
|
+
* Useful for retrieving multiple dependencies at once.
|
|
132
|
+
*
|
|
133
|
+
* @template K - Array of service name keys
|
|
134
|
+
* @param names - Array of service names to retrieve
|
|
135
|
+
* @returns Promise resolving to an object containing the service instances
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```typescript
|
|
139
|
+
* const { database, cache, auth } = await discovery.getMany([
|
|
140
|
+
* 'database',
|
|
141
|
+
* 'cache',
|
|
142
|
+
* 'auth'
|
|
143
|
+
* ]);
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
async getMany(names) {
|
|
147
|
+
const result = {};
|
|
148
|
+
for (const name of names) result[name] = await this.get(name);
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Check if a service exists in the service discovery.
|
|
153
|
+
* Can check by service name or service instance.
|
|
154
|
+
*
|
|
155
|
+
* @param service - The service name or service instance to check
|
|
156
|
+
* @returns True if the service exists, false otherwise
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```typescript
|
|
160
|
+
* if (discovery.has('database')) {
|
|
161
|
+
* const db = await discovery.get('database');
|
|
162
|
+
* }
|
|
163
|
+
*
|
|
164
|
+
* // Or check with service instance
|
|
165
|
+
* const dbService = new DatabaseService();
|
|
166
|
+
* if (!discovery.has(dbService)) {
|
|
167
|
+
* await discovery.register([dbService]);
|
|
168
|
+
* }
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
has(service) {
|
|
172
|
+
if (typeof service === "string") return this.services.has(service);
|
|
173
|
+
return this.services.has(service.serviceName);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
//#endregion
|
|
178
|
+
exports.ServiceDiscovery = ServiceDiscovery;
|
|
179
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["logger: TLogger","envParser: EnvironmentParser<{}>","services: T","name: K","names: [...K]","service: string | Service"],"sources":["../src/index.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\n/**\n * Service interface for the new simplified service pattern.\n * Services are objects with a serviceName and register method.\n *\n * @template TName - The literal string type for the service name\n * @template TInstance - The type of the service instance that will be registered\n *\n * @example\n * ```typescript\n * class DatabaseService implements Service<'database', Database> {\n * serviceName = 'database' as const;\n *\n * async register(envParser: EnvironmentParser<{}>): Promise<Database> {\n * const config = envParser.create((get) => ({\n * url: get('DATABASE_URL').string()\n * })).parse();\n *\n * return new Database(config.url);\n * }\n * }\n * ```\n */\nexport interface Service<TName extends string = string, TInstance = unknown> {\n /**\n * Unique name for the service, used for lookup via services.get()\n */\n serviceName: TName;\n /**\n * Register method that returns the actual service instance.\n * Called once on first access, then cached.\n */\n register(envParser: EnvironmentParser<{}>): TInstance | Promise<TInstance>;\n}\n\n/**\n * Service discovery container that manages service registration and retrieval.\n * Implements a singleton pattern with lazy initialization of services.\n *\n * @template TServices - Record type mapping service names to their instance types\n * @template TLogger - Logger type for internal logging\n *\n * @example\n * ```typescript\n * // Define service types\n * interface MyServices {\n * database: Database;\n * cache: CacheService;\n * auth: AuthService;\n * }\n *\n * // Get service discovery instance\n * const discovery = ServiceDiscovery.getInstance<MyServices>(logger, envParser);\n *\n * // Register services\n * await discovery.register([\n * new DatabaseService(),\n * new CacheService(),\n * new AuthService()\n * ]);\n *\n * // Retrieve services\n * const db = await discovery.get('database');\n * const { cache, auth } = await discovery.getMany(['cache', 'auth']);\n * ```\n */\nexport class ServiceDiscovery<\n TServices extends Record<string, unknown> = {},\n TLogger extends Logger = Logger,\n> {\n /** Singleton instance of ServiceDiscovery */\n private static _instance: ServiceDiscovery<any, any>;\n /** Map of registered service definitions */\n private services = new Map<string, Service>();\n /** Map of instantiated service instances */\n private instances = new Map<keyof TServices, TServices[keyof TServices]>();\n\n /**\n * Gets the singleton instance of ServiceDiscovery.\n * Creates a new instance if one doesn't exist.\n *\n * @template T - Record type mapping service names to their instance types\n * @template TLogger - Logger type for internal logging\n * @param logger - Logger instance for service logging\n * @param envParser - Environment parser for service configuration\n * @returns The ServiceDiscovery singleton instance\n *\n * @example\n * ```typescript\n * const services = ServiceDiscovery.getInstance<MyServices>(logger, envParser);\n * ```\n */\n static getInstance<\n T extends Record<any, unknown> = any,\n TLogger extends Logger = Logger,\n >(logger: TLogger, envParser: EnvironmentParser<{}>): ServiceDiscovery<T> {\n if (!ServiceDiscovery._instance) {\n ServiceDiscovery._instance = new ServiceDiscovery<T, TLogger>(\n logger,\n envParser,\n );\n }\n return ServiceDiscovery._instance as ServiceDiscovery<T>;\n }\n\n /**\n * Private constructor to enforce singleton pattern.\n *\n * @param logger - Logger instance for service logging\n * @param envParser - Environment parser for service configuration\n * @private\n */\n private constructor(\n readonly logger: TLogger,\n readonly envParser: EnvironmentParser<{}>,\n ) {}\n\n /**\n * Register multiple services with the service discovery.\n * Services are instantiated lazily on first access.\n * Already instantiated services are returned from cache.\n *\n * @template T - Array type of services to register\n * @param services - Array of services to register\n * @returns Promise resolving to a record of service names to instances\n *\n * @example\n * ```typescript\n * const services = await discovery.register([\n * new DatabaseService(),\n * new CacheService(),\n * new AuthService()\n * ]);\n *\n * // services = {\n * // database: Database instance,\n * // cache: CacheService instance,\n * // auth: AuthService instance\n * // }\n * ```\n */\n async register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {\n const registeredServices = {} as ServiceRecord<T>;\n for (const service of services) {\n const name = service.serviceName as T[number]['serviceName'];\n if (this.instances.has(name)) {\n (registeredServices as any)[name] = this.instances.get(\n name,\n ) as TServices[keyof TServices];\n continue;\n }\n\n const instance = await service.register(this.envParser);\n\n this.instances.set(name, instance as TServices[keyof TServices]);\n (registeredServices as any)[name] =\n instance as TServices[keyof TServices];\n }\n\n return registeredServices;\n }\n\n /**\n * Get a service from the service discovery.\n * Services are instantiated on first access if not already cached.\n *\n * @template K - The service name key\n * @param name - The name of the service to get\n * @returns Promise resolving to the service instance\n * @throws {Error} If the service is not registered\n *\n * @example\n * ```typescript\n * const database = await discovery.get('database');\n * const users = await database.query('SELECT * FROM users');\n * ```\n */\n get<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {\n const service = this.services.get(name);\n\n if (!service) {\n throw new Error(`Service '${name}' not found in service discovery`);\n }\n\n return service.register(this.envParser) as Promise<TServices[K]>;\n }\n /**\n * Get multiple services from the service discovery.\n * Useful for retrieving multiple dependencies at once.\n *\n * @template K - Array of service name keys\n * @param names - Array of service names to retrieve\n * @returns Promise resolving to an object containing the service instances\n *\n * @example\n * ```typescript\n * const { database, cache, auth } = await discovery.getMany([\n * 'database',\n * 'cache',\n * 'auth'\n * ]);\n * ```\n */\n async getMany<K extends (keyof TServices & string)[]>(\n names: [...K],\n ): Promise<{ [P in K[number]]: TServices[P] }> {\n const result = {} as { [P in K[number]]: TServices[P] };\n\n for (const name of names) {\n result[name] = await this.get(name);\n }\n\n return result;\n }\n\n /**\n * Check if a service exists in the service discovery.\n * Can check by service name or service instance.\n *\n * @param service - The service name or service instance to check\n * @returns True if the service exists, false otherwise\n *\n * @example\n * ```typescript\n * if (discovery.has('database')) {\n * const db = await discovery.get('database');\n * }\n *\n * // Or check with service instance\n * const dbService = new DatabaseService();\n * if (!discovery.has(dbService)) {\n * await discovery.register([dbService]);\n * }\n * ```\n */\n has(service: string | Service): boolean {\n if (typeof service === 'string') {\n return this.services.has(service);\n }\n\n return this.services.has(service.serviceName);\n }\n}\n\n/**\n * Utility type to extract service names from an array of services.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type Names = ExtractServiceNames<[DatabaseService, CacheService]>;\n * // type Names = 'database' | 'cache'\n * ```\n */\nexport type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];\n\n/**\n * Utility type to create a record type from an array of services.\n * Maps service names to their registered instance types.\n *\n * @template T - Array of Service types\n *\n * @example\n * ```typescript\n * type MyServiceRecord = ServiceRecord<[DatabaseService, CacheService]>;\n * // type MyServiceRecord = {\n * // database: Database;\n * // cache: CacheService;\n * // }\n * ```\n */\nexport type ServiceRecord<T extends Service[]> = {\n [K in T[number] as K['serviceName']]: K extends Service\n ? Awaited<ReturnType<K['register']>>\n : never;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,mBAAb,MAAa,iBAGX;;CAEA,OAAe;;CAEf,AAAQ,2BAAW,IAAI;;CAEvB,AAAQ,4BAAY,IAAI;;;;;;;;;;;;;;;;CAiBxB,OAAO,YAGLA,QAAiBC,WAAuD;AACxE,OAAK,iBAAiB,UACpB,kBAAiB,YAAY,IAAI,iBAC/B,QACA;AAGJ,SAAO,iBAAiB;CACzB;;;;;;;;CASD,AAAQ,YACGD,QACAC,WACT;EAFS;EACA;CACP;;;;;;;;;;;;;;;;;;;;;;;;;CA0BJ,MAAM,SAA8BC,UAAwC;EAC1E,MAAM,qBAAqB,CAAE;AAC7B,OAAK,MAAM,WAAW,UAAU;GAC9B,MAAM,OAAO,QAAQ;AACrB,OAAI,KAAK,UAAU,IAAI,KAAK,EAAE;AAC5B,IAAC,mBAA2B,QAAQ,KAAK,UAAU,IACjD,KACD;AACD;GACD;GAED,MAAM,WAAW,MAAM,QAAQ,SAAS,KAAK,UAAU;AAEvD,QAAK,UAAU,IAAI,MAAM,SAAuC;AAChE,GAAC,mBAA2B,QAC1B;EACH;AAED,SAAO;CACR;;;;;;;;;;;;;;;;CAiBD,IAAwCC,MAAgC;EACtE,MAAM,UAAU,KAAK,SAAS,IAAI,KAAK;AAEvC,OAAK,QACH,OAAM,IAAI,OAAO,WAAW,KAAK;AAGnC,SAAO,QAAQ,SAAS,KAAK,UAAU;CACxC;;;;;;;;;;;;;;;;;;CAkBD,MAAM,QACJC,OAC6C;EAC7C,MAAM,SAAS,CAAE;AAEjB,OAAK,MAAM,QAAQ,MACjB,QAAO,QAAQ,MAAM,KAAK,IAAI,KAAK;AAGrC,SAAO;CACR;;;;;;;;;;;;;;;;;;;;;CAsBD,IAAIC,SAAoC;AACtC,aAAW,YAAY,SACrB,QAAO,KAAK,SAAS,IAAI,QAAQ;AAGnC,SAAO,KAAK,SAAS,IAAI,QAAQ,YAAY;CAC9C;AACF"}
|