@geekmidas/services 0.0.1 → 0.2.0
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/dist/ServiceDiscovery-BO2FzEGt.cjs +200 -0
- package/dist/ServiceDiscovery-BO2FzEGt.cjs.map +1 -0
- package/dist/ServiceDiscovery-CfVBrQHt.d.cts +189 -0
- package/dist/ServiceDiscovery-CfVBrQHt.d.cts.map +1 -0
- package/dist/ServiceDiscovery-DLMyH_yM.mjs +195 -0
- package/dist/ServiceDiscovery-DLMyH_yM.mjs.map +1 -0
- package/dist/ServiceDiscovery-DpeEKNe2.d.mts +189 -0
- package/dist/ServiceDiscovery-DpeEKNe2.d.mts.map +1 -0
- package/dist/ServiceDiscovery.cjs +4 -0
- package/dist/ServiceDiscovery.d.cts +3 -0
- package/dist/ServiceDiscovery.d.mts +3 -0
- package/dist/ServiceDiscovery.mjs +4 -0
- package/dist/context-B5YTspJR.mjs +61 -0
- package/dist/context-B5YTspJR.mjs.map +1 -0
- package/dist/context-BVeZOvOd.d.cts +45 -0
- package/dist/context-BVeZOvOd.d.cts.map +1 -0
- package/dist/context-DMExgNzl.d.mts +45 -0
- package/dist/context-DMExgNzl.d.mts.map +1 -0
- package/dist/context-DUTDtYd2.cjs +95 -0
- package/dist/context-DUTDtYd2.cjs.map +1 -0
- package/dist/context.cjs +4 -0
- package/dist/context.d.cts +3 -0
- package/dist/context.d.mts +3 -0
- package/dist/context.mjs +3 -0
- package/dist/index.cjs +5 -178
- package/dist/index.d.cts +4 -214
- package/dist/index.d.mts +4 -214
- package/dist/index.mjs +3 -177
- package/dist/types-CcHmCx_U.d.mts +86 -0
- package/dist/types-CcHmCx_U.d.mts.map +1 -0
- package/dist/types-D7d_yeU5.d.cts +86 -0
- package/dist/types-D7d_yeU5.d.cts.map +1 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +2 -0
- package/dist/types.d.mts +2 -0
- package/dist/types.mjs +0 -0
- package/package.json +22 -6
- package/src/ServiceDiscovery.ts +254 -0
- package/src/__tests__/context.spec.ts +276 -0
- package/src/__tests__/index.spec.ts +556 -558
- package/src/context.ts +91 -0
- package/src/index.ts +15 -279
- package/src/types.ts +85 -0
- package/tsconfig.json +9 -0
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,178 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Service discovery container that manages service registration and retrieval.
|
|
4
|
-
* Implements a singleton pattern with lazy initialization of services.
|
|
5
|
-
*
|
|
6
|
-
* @template TServices - Record type mapping service names to their instance types
|
|
7
|
-
* @template TLogger - Logger type for internal logging
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```typescript
|
|
11
|
-
* // Define service types
|
|
12
|
-
* interface MyServices {
|
|
13
|
-
* database: Database;
|
|
14
|
-
* cache: CacheService;
|
|
15
|
-
* auth: AuthService;
|
|
16
|
-
* }
|
|
17
|
-
*
|
|
18
|
-
* // Get service discovery instance
|
|
19
|
-
* const discovery = ServiceDiscovery.getInstance<MyServices>(logger, envParser);
|
|
20
|
-
*
|
|
21
|
-
* // Register services
|
|
22
|
-
* await discovery.register([
|
|
23
|
-
* new DatabaseService(),
|
|
24
|
-
* new CacheService(),
|
|
25
|
-
* new AuthService()
|
|
26
|
-
* ]);
|
|
27
|
-
*
|
|
28
|
-
* // Retrieve services
|
|
29
|
-
* const db = await discovery.get('database');
|
|
30
|
-
* const { cache, auth } = await discovery.getMany(['cache', 'auth']);
|
|
31
|
-
* ```
|
|
32
|
-
*/
|
|
33
|
-
var ServiceDiscovery = class ServiceDiscovery {
|
|
34
|
-
/** Singleton instance of ServiceDiscovery */
|
|
35
|
-
static _instance;
|
|
36
|
-
/** Map of registered service definitions */
|
|
37
|
-
services = /* @__PURE__ */ new Map();
|
|
38
|
-
/** Map of instantiated service instances */
|
|
39
|
-
instances = /* @__PURE__ */ new Map();
|
|
40
|
-
/**
|
|
41
|
-
* Gets the singleton instance of ServiceDiscovery.
|
|
42
|
-
* Creates a new instance if one doesn't exist.
|
|
43
|
-
*
|
|
44
|
-
* @template T - Record type mapping service names to their instance types
|
|
45
|
-
* @template TLogger - Logger type for internal logging
|
|
46
|
-
* @param logger - Logger instance for service logging
|
|
47
|
-
* @param envParser - Environment parser for service configuration
|
|
48
|
-
* @returns The ServiceDiscovery singleton instance
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* const services = ServiceDiscovery.getInstance<MyServices>(logger, envParser);
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
static getInstance(logger, envParser) {
|
|
56
|
-
if (!ServiceDiscovery._instance) ServiceDiscovery._instance = new ServiceDiscovery(logger, envParser);
|
|
57
|
-
return ServiceDiscovery._instance;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Private constructor to enforce singleton pattern.
|
|
61
|
-
*
|
|
62
|
-
* @param logger - Logger instance for service logging
|
|
63
|
-
* @param envParser - Environment parser for service configuration
|
|
64
|
-
* @private
|
|
65
|
-
*/
|
|
66
|
-
constructor(logger, envParser) {
|
|
67
|
-
this.logger = logger;
|
|
68
|
-
this.envParser = envParser;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Register multiple services with the service discovery.
|
|
72
|
-
* Services are instantiated lazily on first access.
|
|
73
|
-
* Already instantiated services are returned from cache.
|
|
74
|
-
*
|
|
75
|
-
* @template T - Array type of services to register
|
|
76
|
-
* @param services - Array of services to register
|
|
77
|
-
* @returns Promise resolving to a record of service names to instances
|
|
78
|
-
*
|
|
79
|
-
* @example
|
|
80
|
-
* ```typescript
|
|
81
|
-
* const services = await discovery.register([
|
|
82
|
-
* new DatabaseService(),
|
|
83
|
-
* new CacheService(),
|
|
84
|
-
* new AuthService()
|
|
85
|
-
* ]);
|
|
86
|
-
*
|
|
87
|
-
* // services = {
|
|
88
|
-
* // database: Database instance,
|
|
89
|
-
* // cache: CacheService instance,
|
|
90
|
-
* // auth: AuthService instance
|
|
91
|
-
* // }
|
|
92
|
-
* ```
|
|
93
|
-
*/
|
|
94
|
-
async register(services) {
|
|
95
|
-
const registeredServices = {};
|
|
96
|
-
for (const service of services) {
|
|
97
|
-
const name = service.serviceName;
|
|
98
|
-
if (this.instances.has(name)) {
|
|
99
|
-
registeredServices[name] = this.instances.get(name);
|
|
100
|
-
continue;
|
|
101
|
-
}
|
|
102
|
-
const instance = await service.register(this.envParser);
|
|
103
|
-
this.instances.set(name, instance);
|
|
104
|
-
registeredServices[name] = instance;
|
|
105
|
-
}
|
|
106
|
-
return registeredServices;
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Get a service from the service discovery.
|
|
110
|
-
* Services are instantiated on first access if not already cached.
|
|
111
|
-
*
|
|
112
|
-
* @template K - The service name key
|
|
113
|
-
* @param name - The name of the service to get
|
|
114
|
-
* @returns Promise resolving to the service instance
|
|
115
|
-
* @throws {Error} If the service is not registered
|
|
116
|
-
*
|
|
117
|
-
* @example
|
|
118
|
-
* ```typescript
|
|
119
|
-
* const database = await discovery.get('database');
|
|
120
|
-
* const users = await database.query('SELECT * FROM users');
|
|
121
|
-
* ```
|
|
122
|
-
*/
|
|
123
|
-
get(name) {
|
|
124
|
-
const service = this.services.get(name);
|
|
125
|
-
if (!service) throw new Error(`Service '${name}' not found in service discovery`);
|
|
126
|
-
return service.register(this.envParser);
|
|
127
|
-
}
|
|
128
|
-
/**
|
|
129
|
-
* Get multiple services from the service discovery.
|
|
130
|
-
* Useful for retrieving multiple dependencies at once.
|
|
131
|
-
*
|
|
132
|
-
* @template K - Array of service name keys
|
|
133
|
-
* @param names - Array of service names to retrieve
|
|
134
|
-
* @returns Promise resolving to an object containing the service instances
|
|
135
|
-
*
|
|
136
|
-
* @example
|
|
137
|
-
* ```typescript
|
|
138
|
-
* const { database, cache, auth } = await discovery.getMany([
|
|
139
|
-
* 'database',
|
|
140
|
-
* 'cache',
|
|
141
|
-
* 'auth'
|
|
142
|
-
* ]);
|
|
143
|
-
* ```
|
|
144
|
-
*/
|
|
145
|
-
async getMany(names) {
|
|
146
|
-
const result = {};
|
|
147
|
-
for (const name of names) result[name] = await this.get(name);
|
|
148
|
-
return result;
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Check if a service exists in the service discovery.
|
|
152
|
-
* Can check by service name or service instance.
|
|
153
|
-
*
|
|
154
|
-
* @param service - The service name or service instance to check
|
|
155
|
-
* @returns True if the service exists, false otherwise
|
|
156
|
-
*
|
|
157
|
-
* @example
|
|
158
|
-
* ```typescript
|
|
159
|
-
* if (discovery.has('database')) {
|
|
160
|
-
* const db = await discovery.get('database');
|
|
161
|
-
* }
|
|
162
|
-
*
|
|
163
|
-
* // Or check with service instance
|
|
164
|
-
* const dbService = new DatabaseService();
|
|
165
|
-
* if (!discovery.has(dbService)) {
|
|
166
|
-
* await discovery.register([dbService]);
|
|
167
|
-
* }
|
|
168
|
-
* ```
|
|
169
|
-
*/
|
|
170
|
-
has(service) {
|
|
171
|
-
if (typeof service === "string") return this.services.has(service);
|
|
172
|
-
return this.services.has(service.serviceName);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
1
|
+
import { runWithRequestContext, serviceContext } from "./context-B5YTspJR.mjs";
|
|
2
|
+
import { ServiceDiscovery } from "./ServiceDiscovery-DLMyH_yM.mjs";
|
|
175
3
|
|
|
176
|
-
|
|
177
|
-
export { ServiceDiscovery };
|
|
178
|
-
//# sourceMappingURL=index.mjs.map
|
|
4
|
+
export { ServiceDiscovery, runWithRequestContext, serviceContext };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
|
|
4
|
+
//#region src/types.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Request context available to services.
|
|
8
|
+
* Methods are guaranteed to return values when called within a request context.
|
|
9
|
+
* Throws if called outside a request context (catches bugs early).
|
|
10
|
+
*/
|
|
11
|
+
interface ServiceContext {
|
|
12
|
+
/**
|
|
13
|
+
* Get the current request's logger.
|
|
14
|
+
* @throws Error if called outside a request context
|
|
15
|
+
*/
|
|
16
|
+
getLogger(): Logger;
|
|
17
|
+
/**
|
|
18
|
+
* Get the current request ID.
|
|
19
|
+
* @throws Error if called outside a request context
|
|
20
|
+
*/
|
|
21
|
+
getRequestId(): string;
|
|
22
|
+
/**
|
|
23
|
+
* Get the current request's start time (from Date.now()).
|
|
24
|
+
* Useful for calculating request duration.
|
|
25
|
+
* @throws Error if called outside a request context
|
|
26
|
+
*/
|
|
27
|
+
getRequestStartTime(): number;
|
|
28
|
+
/**
|
|
29
|
+
* Check if currently running inside a request context.
|
|
30
|
+
* Use this to guard calls if you need to handle both cases.
|
|
31
|
+
*/
|
|
32
|
+
hasContext(): boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Options passed to service register method.
|
|
36
|
+
*/
|
|
37
|
+
interface ServiceRegisterOptions {
|
|
38
|
+
/** Environment parser for configuration */
|
|
39
|
+
envParser: EnvironmentParser<{}>;
|
|
40
|
+
/** Request context for logging and tracing */
|
|
41
|
+
context: ServiceContext;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Service interface for the simplified service pattern.
|
|
45
|
+
* Services are objects with a serviceName and register method.
|
|
46
|
+
*
|
|
47
|
+
* @template TName - The literal string type for the service name
|
|
48
|
+
* @template TInstance - The type of the service instance that will be registered
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```typescript
|
|
52
|
+
* const databaseService = {
|
|
53
|
+
* serviceName: 'database' as const,
|
|
54
|
+
* register({ envParser, context }: ServiceRegisterOptions) {
|
|
55
|
+
* const config = envParser.create((get) => ({
|
|
56
|
+
* url: get('DATABASE_URL').string()
|
|
57
|
+
* })).parse();
|
|
58
|
+
*
|
|
59
|
+
* return {
|
|
60
|
+
* async query(sql: string) {
|
|
61
|
+
* const logger = context.getLogger();
|
|
62
|
+
* logger.debug({ sql }, 'Executing query');
|
|
63
|
+
* // ... execute query
|
|
64
|
+
* }
|
|
65
|
+
* };
|
|
66
|
+
* }
|
|
67
|
+
* } satisfies Service<'database', DatabaseInstance>;
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
interface Service<TName extends string = string, TInstance = unknown> {
|
|
71
|
+
/**
|
|
72
|
+
* Unique name for the service, used for lookup via services.get()
|
|
73
|
+
*/
|
|
74
|
+
serviceName: TName;
|
|
75
|
+
/**
|
|
76
|
+
* Register method that returns the actual service instance.
|
|
77
|
+
* Called once on first access, then cached.
|
|
78
|
+
*
|
|
79
|
+
* @param options - Registration options including envParser and context
|
|
80
|
+
*/
|
|
81
|
+
register(options: ServiceRegisterOptions): TInstance | Promise<TInstance>;
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=types.d.ts.map
|
|
84
|
+
//#endregion
|
|
85
|
+
export { Service, ServiceContext, ServiceRegisterOptions };
|
|
86
|
+
//# sourceMappingURL=types-CcHmCx_U.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-CcHmCx_U.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
2
|
+
import { Logger } from "@geekmidas/logger";
|
|
3
|
+
|
|
4
|
+
//#region src/types.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Request context available to services.
|
|
8
|
+
* Methods are guaranteed to return values when called within a request context.
|
|
9
|
+
* Throws if called outside a request context (catches bugs early).
|
|
10
|
+
*/
|
|
11
|
+
interface ServiceContext {
|
|
12
|
+
/**
|
|
13
|
+
* Get the current request's logger.
|
|
14
|
+
* @throws Error if called outside a request context
|
|
15
|
+
*/
|
|
16
|
+
getLogger(): Logger;
|
|
17
|
+
/**
|
|
18
|
+
* Get the current request ID.
|
|
19
|
+
* @throws Error if called outside a request context
|
|
20
|
+
*/
|
|
21
|
+
getRequestId(): string;
|
|
22
|
+
/**
|
|
23
|
+
* Get the current request's start time (from Date.now()).
|
|
24
|
+
* Useful for calculating request duration.
|
|
25
|
+
* @throws Error if called outside a request context
|
|
26
|
+
*/
|
|
27
|
+
getRequestStartTime(): number;
|
|
28
|
+
/**
|
|
29
|
+
* Check if currently running inside a request context.
|
|
30
|
+
* Use this to guard calls if you need to handle both cases.
|
|
31
|
+
*/
|
|
32
|
+
hasContext(): boolean;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Options passed to service register method.
|
|
36
|
+
*/
|
|
37
|
+
interface ServiceRegisterOptions {
|
|
38
|
+
/** Environment parser for configuration */
|
|
39
|
+
envParser: EnvironmentParser<{}>;
|
|
40
|
+
/** Request context for logging and tracing */
|
|
41
|
+
context: ServiceContext;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Service interface for the simplified service pattern.
|
|
45
|
+
* Services are objects with a serviceName and register method.
|
|
46
|
+
*
|
|
47
|
+
* @template TName - The literal string type for the service name
|
|
48
|
+
* @template TInstance - The type of the service instance that will be registered
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```typescript
|
|
52
|
+
* const databaseService = {
|
|
53
|
+
* serviceName: 'database' as const,
|
|
54
|
+
* register({ envParser, context }: ServiceRegisterOptions) {
|
|
55
|
+
* const config = envParser.create((get) => ({
|
|
56
|
+
* url: get('DATABASE_URL').string()
|
|
57
|
+
* })).parse();
|
|
58
|
+
*
|
|
59
|
+
* return {
|
|
60
|
+
* async query(sql: string) {
|
|
61
|
+
* const logger = context.getLogger();
|
|
62
|
+
* logger.debug({ sql }, 'Executing query');
|
|
63
|
+
* // ... execute query
|
|
64
|
+
* }
|
|
65
|
+
* };
|
|
66
|
+
* }
|
|
67
|
+
* } satisfies Service<'database', DatabaseInstance>;
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
interface Service<TName extends string = string, TInstance = unknown> {
|
|
71
|
+
/**
|
|
72
|
+
* Unique name for the service, used for lookup via services.get()
|
|
73
|
+
*/
|
|
74
|
+
serviceName: TName;
|
|
75
|
+
/**
|
|
76
|
+
* Register method that returns the actual service instance.
|
|
77
|
+
* Called once on first access, then cached.
|
|
78
|
+
*
|
|
79
|
+
* @param options - Registration options including envParser and context
|
|
80
|
+
*/
|
|
81
|
+
register(options: ServiceRegisterOptions): TInstance | Promise<TInstance>;
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=types.d.ts.map
|
|
84
|
+
//#endregion
|
|
85
|
+
export { Service, ServiceContext, ServiceRegisterOptions };
|
|
86
|
+
//# sourceMappingURL=types-D7d_yeU5.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-D7d_yeU5.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;AAQA;AA8BA;;AAEY,UAhCK,cAAA,CAgCL;EAAiB;AAEL;AA8BxB;;EAAwB,SAIV,EAAA,EA/DA,MA+DA;EAAK;;;;EAO4C,YAAA,EAAA,EAAA,MAAA;;;;;;;;;;;;;;;;UA7C9C,sBAAA;;aAEL;;WAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BO;;;;eAIH;;;;;;;oBAOK,yBAAyB,YAAY,QAAQ"}
|
package/dist/types.cjs
ADDED
|
File without changes
|
package/dist/types.d.cts
ADDED
package/dist/types.d.mts
ADDED
package/dist/types.mjs
ADDED
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geekmidas/services",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -8,21 +8,37 @@
|
|
|
8
8
|
"types": "./dist/index.d.ts",
|
|
9
9
|
"import": "./dist/index.mjs",
|
|
10
10
|
"require": "./dist/index.cjs"
|
|
11
|
+
},
|
|
12
|
+
"./context": {
|
|
13
|
+
"types": "./dist/context.d.ts",
|
|
14
|
+
"import": "./dist/context.mjs",
|
|
15
|
+
"require": "./dist/context.cjs"
|
|
11
16
|
}
|
|
12
17
|
},
|
|
13
18
|
"repository": {
|
|
14
19
|
"type": "git",
|
|
15
|
-
"url": "https://github.com/geekmidas/toolbox
|
|
20
|
+
"url": "https://github.com/geekmidas/toolbox"
|
|
16
21
|
},
|
|
17
22
|
"publishConfig": {
|
|
18
23
|
"registry": "https://registry.npmjs.org/",
|
|
19
24
|
"access": "public"
|
|
20
25
|
},
|
|
21
|
-
"dependencies": {
|
|
22
|
-
"@geekmidas/logger": "0.0.1"
|
|
23
|
-
},
|
|
26
|
+
"dependencies": {},
|
|
24
27
|
"peerDependencies": {
|
|
25
|
-
"@geekmidas/
|
|
28
|
+
"@geekmidas/logger": "^0.4.0",
|
|
29
|
+
"@geekmidas/envkit": "^0.3.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@geekmidas/envkit": {
|
|
33
|
+
"optional": true
|
|
34
|
+
},
|
|
35
|
+
"@geekmidas/logger": {
|
|
36
|
+
"optional": true
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@geekmidas/envkit": "^0.3.0",
|
|
41
|
+
"@geekmidas/logger": "^0.4.0"
|
|
26
42
|
},
|
|
27
43
|
"scripts": {
|
|
28
44
|
"ts": "tsc --noEmit --skipLibCheck src/**/*.ts"
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
2
|
+
import { serviceContext } from './context';
|
|
3
|
+
import type { Service } from './types';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Service discovery container that manages service registration and retrieval.
|
|
7
|
+
* Implements a singleton pattern with lazy initialization of services.
|
|
8
|
+
*
|
|
9
|
+
* @template TServices - Record type mapping service names to their instance types
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* // Define service types
|
|
14
|
+
* interface MyServices {
|
|
15
|
+
* database: Database;
|
|
16
|
+
* cache: CacheService;
|
|
17
|
+
* auth: AuthService;
|
|
18
|
+
* }
|
|
19
|
+
*
|
|
20
|
+
* // Get service discovery instance
|
|
21
|
+
* const discovery = ServiceDiscovery.getInstance<MyServices>(envParser);
|
|
22
|
+
*
|
|
23
|
+
* // Register services
|
|
24
|
+
* await discovery.register([
|
|
25
|
+
* databaseService,
|
|
26
|
+
* cacheService,
|
|
27
|
+
* authService
|
|
28
|
+
* ]);
|
|
29
|
+
*
|
|
30
|
+
* // Retrieve services
|
|
31
|
+
* const db = await discovery.get('database');
|
|
32
|
+
* const { cache, auth } = await discovery.getMany(['cache', 'auth']);
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export class ServiceDiscovery<TServices extends Record<string, unknown> = {}> {
|
|
36
|
+
/** Singleton instance of ServiceDiscovery */
|
|
37
|
+
private static _instance: ServiceDiscovery<any>;
|
|
38
|
+
/** Map of registered service definitions */
|
|
39
|
+
private services = new Map<string, Service>();
|
|
40
|
+
/** Map of instantiated service instances */
|
|
41
|
+
private instances = new Map<keyof TServices, TServices[keyof TServices]>();
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Gets the singleton instance of ServiceDiscovery.
|
|
45
|
+
* Creates a new instance if one doesn't exist.
|
|
46
|
+
*
|
|
47
|
+
* @template T - Record type mapping service names to their instance types
|
|
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>(envParser);
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
static getInstance<T extends Record<any, unknown> = any>(
|
|
57
|
+
envParser: EnvironmentParser<{}>,
|
|
58
|
+
): ServiceDiscovery<T> {
|
|
59
|
+
if (!ServiceDiscovery._instance) {
|
|
60
|
+
ServiceDiscovery._instance = new ServiceDiscovery<T>(envParser);
|
|
61
|
+
}
|
|
62
|
+
return ServiceDiscovery._instance as ServiceDiscovery<T>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Resets the singleton instance. Use only for testing purposes.
|
|
67
|
+
* This clears all cached services and allows a fresh instance to be created.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```typescript
|
|
71
|
+
* // In test teardown
|
|
72
|
+
* afterEach(() => {
|
|
73
|
+
* ServiceDiscovery.reset();
|
|
74
|
+
* });
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
static reset(): void {
|
|
78
|
+
ServiceDiscovery._instance = undefined as any;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Private constructor to enforce singleton pattern.
|
|
83
|
+
*
|
|
84
|
+
* @param envParser - Environment parser for service configuration
|
|
85
|
+
* @private
|
|
86
|
+
*/
|
|
87
|
+
private constructor(readonly envParser: EnvironmentParser<{}>) {}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Register multiple services with the service discovery.
|
|
91
|
+
* Services are instantiated lazily on first access.
|
|
92
|
+
* Already instantiated services are returned from cache.
|
|
93
|
+
*
|
|
94
|
+
* @template T - Array type of services to register
|
|
95
|
+
* @param services - Array of services to register
|
|
96
|
+
* @returns Promise resolving to a record of service names to instances
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* const services = await discovery.register([
|
|
101
|
+
* databaseService,
|
|
102
|
+
* cacheService,
|
|
103
|
+
* authService
|
|
104
|
+
* ]);
|
|
105
|
+
*
|
|
106
|
+
* // services = {
|
|
107
|
+
* // database: Database instance,
|
|
108
|
+
* // cache: CacheService instance,
|
|
109
|
+
* // auth: AuthService instance
|
|
110
|
+
* // }
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
async register<T extends Service[]>(services: T): Promise<ServiceRecord<T>> {
|
|
114
|
+
const registeredServices = {} as ServiceRecord<T>;
|
|
115
|
+
for (const service of services) {
|
|
116
|
+
const name = service.serviceName as T[number]['serviceName'];
|
|
117
|
+
if (this.instances.has(name)) {
|
|
118
|
+
(registeredServices as any)[name] = this.instances.get(
|
|
119
|
+
name,
|
|
120
|
+
) as TServices[keyof TServices];
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Pass both envParser and context to service
|
|
125
|
+
const instance = await service.register({
|
|
126
|
+
envParser: this.envParser,
|
|
127
|
+
context: serviceContext,
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
this.instances.set(name, instance as TServices[keyof TServices]);
|
|
131
|
+
(registeredServices as any)[name] =
|
|
132
|
+
instance as TServices[keyof TServices];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return registeredServices;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Get a service from the service discovery.
|
|
140
|
+
* Services are instantiated on first access if not already cached.
|
|
141
|
+
*
|
|
142
|
+
* @template K - The service name key
|
|
143
|
+
* @param name - The name of the service to get
|
|
144
|
+
* @returns Promise resolving to the service instance
|
|
145
|
+
* @throws {Error} If the service is not registered
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```typescript
|
|
149
|
+
* const database = await discovery.get('database');
|
|
150
|
+
* const users = await database.query('SELECT * FROM users');
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
get<K extends keyof TServices & string>(name: K): Promise<TServices[K]> {
|
|
154
|
+
const service = this.services.get(name);
|
|
155
|
+
|
|
156
|
+
if (!service) {
|
|
157
|
+
throw new Error(`Service '${name}' not found in service discovery`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return service.register({
|
|
161
|
+
envParser: this.envParser,
|
|
162
|
+
context: serviceContext,
|
|
163
|
+
}) as Promise<TServices[K]>;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Get multiple services from the service discovery.
|
|
167
|
+
* Useful for retrieving multiple dependencies at once.
|
|
168
|
+
*
|
|
169
|
+
* @template K - Array of service name keys
|
|
170
|
+
* @param names - Array of service names to retrieve
|
|
171
|
+
* @returns Promise resolving to an object containing the service instances
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```typescript
|
|
175
|
+
* const { database, cache, auth } = await discovery.getMany([
|
|
176
|
+
* 'database',
|
|
177
|
+
* 'cache',
|
|
178
|
+
* 'auth'
|
|
179
|
+
* ]);
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
async getMany<K extends (keyof TServices & string)[]>(
|
|
183
|
+
names: [...K],
|
|
184
|
+
): Promise<{ [P in K[number]]: TServices[P] }> {
|
|
185
|
+
const result = {} as { [P in K[number]]: TServices[P] };
|
|
186
|
+
|
|
187
|
+
for (const name of names) {
|
|
188
|
+
result[name] = await this.get(name);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return result;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Check if a service exists in the service discovery.
|
|
196
|
+
* Can check by service name or service instance.
|
|
197
|
+
*
|
|
198
|
+
* @param service - The service name or service instance to check
|
|
199
|
+
* @returns True if the service exists, false otherwise
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```typescript
|
|
203
|
+
* if (discovery.has('database')) {
|
|
204
|
+
* const db = await discovery.get('database');
|
|
205
|
+
* }
|
|
206
|
+
*
|
|
207
|
+
* // Or check with service instance
|
|
208
|
+
* if (!discovery.has(databaseService)) {
|
|
209
|
+
* await discovery.register([databaseService]);
|
|
210
|
+
* }
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
has(service: string | Service): boolean {
|
|
214
|
+
if (typeof service === 'string') {
|
|
215
|
+
return this.services.has(service);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return this.services.has(service.serviceName);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Utility type to extract service names from an array of services.
|
|
224
|
+
*
|
|
225
|
+
* @template T - Array of Service types
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```typescript
|
|
229
|
+
* type Names = ExtractServiceNames<[typeof databaseService, typeof cacheService]>;
|
|
230
|
+
* // type Names = 'database' | 'cache'
|
|
231
|
+
* ```
|
|
232
|
+
*/
|
|
233
|
+
export type ExtractServiceNames<T extends Service[]> = T[number]['serviceName'];
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Utility type to create a record type from an array of services.
|
|
237
|
+
* Maps service names to their registered instance types.
|
|
238
|
+
*
|
|
239
|
+
* @template T - Array of Service types
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* ```typescript
|
|
243
|
+
* type MyServiceRecord = ServiceRecord<[typeof databaseService, typeof cacheService]>;
|
|
244
|
+
* // type MyServiceRecord = {
|
|
245
|
+
* // database: DatabaseInstance;
|
|
246
|
+
* // cache: CacheInstance;
|
|
247
|
+
* // }
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
export type ServiceRecord<T extends Service[]> = {
|
|
251
|
+
[K in T[number] as K['serviceName']]: K extends Service
|
|
252
|
+
? Awaited<ReturnType<K['register']>>
|
|
253
|
+
: never;
|
|
254
|
+
};
|