-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-registry-example.ts
More file actions
559 lines (496 loc) · 16.1 KB
/
api-registry-example.ts
File metadata and controls
559 lines (496 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* API Registry Example
*
* Demonstrates how to use the API Registry in the ObjectStack kernel
* to register and discover API endpoints across plugins.
*/
import { ObjectKernel, createApiRegistryPlugin, ApiRegistry } from '@objectstack/core';
import type { Plugin } from '@objectstack/core';
import type { ApiRegistryEntry } from '@objectstack/spec/api';
// Example 1: Basic API Registration
async function example1_BasicApiRegistration() {
console.log('\n=== Example 1: Basic API Registration ===\n');
const kernel = new ObjectKernel();
// Register API Registry plugin with default settings
kernel.use(createApiRegistryPlugin());
// Create a plugin that registers a simple REST API
const customerPlugin: Plugin = {
name: 'customer-plugin',
version: '1.0.0',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
const customerApi: ApiRegistryEntry = {
id: 'customer_api',
name: 'Customer Management API',
type: 'rest',
version: 'v1',
basePath: '/api/v1/customers',
description: 'CRUD operations for customer records',
endpoints: [
{
id: 'list_customers',
method: 'GET',
path: '/api/v1/customers',
summary: 'List all customers',
parameters: [
{
name: 'limit',
in: 'query',
schema: { type: 'number' },
description: 'Maximum number of results',
},
{
name: 'offset',
in: 'query',
schema: { type: 'number' },
description: 'Offset for pagination',
},
],
responses: [
{
statusCode: 200,
description: 'Customers retrieved successfully',
schema: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
},
},
},
},
],
},
{
id: 'get_customer',
method: 'GET',
path: '/api/v1/customers/:id',
summary: 'Get customer by ID',
requiredPermissions: ['customer.read'], // RBAC integration
parameters: [
{
name: 'id',
in: 'path',
required: true,
schema: { type: 'string', format: 'uuid' },
},
],
responses: [
{
statusCode: 200,
description: 'Customer found',
},
{
statusCode: 404,
description: 'Customer not found',
},
],
},
{
id: 'create_customer',
method: 'POST',
path: '/api/v1/customers',
summary: 'Create new customer',
requiredPermissions: ['customer.create'],
requestBody: {
required: true,
contentType: 'application/json',
schema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
},
},
},
responses: [
{
statusCode: 201,
description: 'Customer created',
},
],
},
],
metadata: {
status: 'active',
tags: ['customer', 'crm', 'data'],
owner: 'sales_team',
},
};
registry.registerApi(customerApi);
ctx.logger.info('Customer API registered', {
endpointCount: customerApi.endpoints.length,
});
},
};
kernel.use(customerPlugin);
await kernel.bootstrap();
// Access the registry
const registry = kernel.getService<ApiRegistry>('api-registry');
const snapshot = registry.getRegistry();
console.log(`Total APIs: ${snapshot.totalApis}`);
console.log(`Total Endpoints: ${snapshot.totalEndpoints}`);
console.log('\nRegistered APIs:');
snapshot.apis.forEach((api) => {
console.log(` - ${api.name} (${api.type}) - ${api.endpoints.length} endpoints`);
});
await kernel.shutdown();
}
// Example 2: Multi-Plugin API Discovery
async function example2_MultiPluginDiscovery() {
console.log('\n=== Example 2: Multi-Plugin API Discovery ===\n');
const kernel = new ObjectKernel();
kernel.use(createApiRegistryPlugin());
// Data Plugin - REST APIs
const dataPlugin: Plugin = {
name: 'data-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'customer_api',
name: 'Customer API',
type: 'rest',
version: 'v1',
basePath: '/api/v1/customers',
endpoints: [
{
id: 'get_customers',
method: 'GET',
path: '/api/v1/customers',
responses: [],
},
],
metadata: {
status: 'active',
tags: ['data', 'crm'],
},
});
registry.registerApi({
id: 'product_api',
name: 'Product API',
type: 'rest',
version: 'v1',
basePath: '/api/v1/products',
endpoints: [
{
id: 'get_products',
method: 'GET',
path: '/api/v1/products',
responses: [],
},
],
metadata: {
status: 'active',
tags: ['data', 'inventory'],
},
});
},
};
// GraphQL Plugin
const graphqlPlugin: Plugin = {
name: 'graphql-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'graphql_api',
name: 'GraphQL API',
type: 'graphql',
version: 'v1',
basePath: '/graphql',
endpoints: [
{
id: 'query',
path: '/graphql',
summary: 'GraphQL Query Endpoint',
responses: [],
},
],
metadata: {
status: 'active',
tags: ['query', 'flexible'],
},
});
},
};
// Analytics Plugin - Beta API
const analyticsPlugin: Plugin = {
name: 'analytics-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'analytics_api',
name: 'Analytics API',
type: 'rest',
version: 'v1',
basePath: '/api/v1/analytics',
endpoints: [
{
id: 'get_reports',
method: 'GET',
path: '/api/v1/analytics/reports',
responses: [],
},
],
metadata: {
status: 'beta',
tags: ['analytics', 'reporting'],
},
});
},
};
kernel.use(dataPlugin);
kernel.use(graphqlPlugin);
kernel.use(analyticsPlugin);
await kernel.bootstrap();
const registry = kernel.getService<ApiRegistry>('api-registry');
// Discovery 1: Find all REST APIs
console.log('All REST APIs:');
const restApis = registry.findApis({ type: 'rest' });
restApis.apis.forEach((api) => console.log(` - ${api.name}`));
// Discovery 2: Find active APIs
console.log('\nActive APIs:');
const activeApis = registry.findApis({ status: 'active' });
console.log(` Total: ${activeApis.total}`);
// Discovery 3: Find data-related APIs
console.log('\nData-related APIs:');
const dataApis = registry.findApis({ tags: ['data'] });
dataApis.apis.forEach((api) => console.log(` - ${api.name}`));
// Discovery 4: Search by name
console.log('\nSearch for "analytics":');
const analyticsApis = registry.findApis({ search: 'analytics' });
analyticsApis.apis.forEach((api) => console.log(` - ${api.name} (${api.metadata?.status})`));
await kernel.shutdown();
}
// Example 3: Route Conflict Resolution
async function example3_ConflictResolution() {
console.log('\n=== Example 3: Route Conflict Resolution ===\n');
const kernel = new ObjectKernel();
// Use priority-based conflict resolution
kernel.use(
createApiRegistryPlugin({
conflictResolution: 'priority',
})
);
// Core Plugin - High priority
const corePlugin: Plugin = {
name: 'core-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'core_data_api',
name: 'Core Data API',
type: 'rest',
version: 'v1',
basePath: '/api',
endpoints: [
{
id: 'core_data',
method: 'GET',
path: '/api/data/:object',
priority: 900, // High priority
summary: 'Core data endpoint (generic)',
responses: [],
},
],
});
ctx.logger.info('Core API registered with priority 900');
},
};
// Custom Plugin - Medium priority
const customPlugin: Plugin = {
name: 'custom-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'custom_data_api',
name: 'Custom Data API',
type: 'rest',
version: 'v1',
basePath: '/api',
endpoints: [
{
id: 'custom_data',
method: 'GET',
path: '/api/data/:object',
priority: 300, // Lower priority
summary: 'Custom data endpoint (specialized)',
responses: [],
},
],
});
ctx.logger.info('Custom API registered with priority 300');
},
};
kernel.use(corePlugin);
kernel.use(customPlugin);
await kernel.bootstrap();
const registry = kernel.getService<ApiRegistry>('api-registry');
// Check which endpoint won
const winner = registry.findEndpointByRoute('GET', '/api/data/:object');
console.log('\nConflict Resolution Result:');
console.log(` Route: GET /api/data/:object`);
console.log(` Winner: ${winner?.api.name}`);
console.log(` Endpoint: ${winner?.endpoint.summary}`);
console.log(` Priority: ${winner?.endpoint.priority}`);
await kernel.shutdown();
}
// Example 4: Plugin-specific APIs with Custom Protocol
async function example4_CustomProtocol() {
console.log('\n=== Example 4: Custom Protocol Support ===\n');
const kernel = new ObjectKernel();
kernel.use(createApiRegistryPlugin());
const websocketPlugin: Plugin = {
name: 'websocket-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'realtime_api',
name: 'Real-time WebSocket API',
type: 'websocket',
version: 'v1',
basePath: '/ws',
endpoints: [
{
id: 'customer_updates',
path: '/ws/customers',
summary: 'Customer update notifications',
protocolConfig: {
subProtocol: 'websocket',
eventName: 'customer.updated',
direction: 'server-to-client',
},
responses: [],
},
{
id: 'order_updates',
path: '/ws/orders',
summary: 'Order update notifications',
protocolConfig: {
subProtocol: 'websocket',
eventName: 'order.updated',
direction: 'bidirectional',
},
responses: [],
},
],
metadata: {
status: 'active',
tags: ['realtime', 'websocket'],
pluginSource: 'websocket-plugin',
},
});
},
};
kernel.use(websocketPlugin);
await kernel.bootstrap();
const registry = kernel.getService<ApiRegistry>('api-registry');
const wsApis = registry.findApis({ type: 'websocket' });
console.log('WebSocket APIs:');
wsApis.apis.forEach((api) => {
console.log(`\n${api.name}:`);
api.endpoints.forEach((endpoint) => {
console.log(` - ${endpoint.summary}`);
console.log(` Event: ${endpoint.protocolConfig?.eventName}`);
console.log(` Direction: ${endpoint.protocolConfig?.direction}`);
});
});
await kernel.shutdown();
}
// Example 5: Dynamic Schema Linking with ObjectQL
async function example5_DynamicSchemas() {
console.log('\n=== Example 5: Dynamic Schema Linking ===\n');
const kernel = new ObjectKernel();
kernel.use(createApiRegistryPlugin());
const dynamicPlugin: Plugin = {
name: 'dynamic-plugin',
init: async (ctx) => {
const registry = ctx.getService<ApiRegistry>('api-registry');
registry.registerApi({
id: 'dynamic_customer_api',
name: 'Dynamic Customer API',
type: 'rest',
version: 'v1',
basePath: '/api/v1/customers',
endpoints: [
{
id: 'get_customer_dynamic',
method: 'GET',
path: '/api/v1/customers/:id',
summary: 'Get customer (with dynamic schema)',
responses: [
{
statusCode: 200,
description: 'Customer retrieved',
// Dynamic schema linked to ObjectQL
//
// IMPORTANT: The API Registry stores this ObjectQL reference as-is.
// The actual schema resolution (expanding the reference into a full JSON Schema)
// is performed by downstream tools:
// - API Gateway: For runtime request/response validation
// - OpenAPI/Swagger Generator: For API documentation generation
// - GraphQL Schema Builder: For GraphQL type generation
//
// The Registry's responsibility is to STORE the reference metadata,
// not to resolve or transform it.
schema: {
$ref: {
objectId: 'customer', // References ObjectQL object
excludeFields: ['password_hash', 'internal_notes'], // Exclude sensitive fields
includeRelated: ['account', 'primary_contact'], // Include related objects
},
},
},
],
},
],
});
ctx.logger.info('Dynamic Customer API registered with ObjectQL schema references');
},
};
kernel.use(dynamicPlugin);
await kernel.bootstrap();
const registry = kernel.getService<ApiRegistry>('api-registry');
const endpoint = registry.getEndpoint('dynamic_customer_api', 'get_customer_dynamic');
console.log('Dynamic Endpoint:');
console.log(` Path: ${endpoint?.path}`);
console.log(` Summary: ${endpoint?.summary}`);
if (endpoint?.responses?.[0]?.schema && '$ref' in endpoint.responses[0].schema) {
const ref = endpoint.responses[0].schema.$ref;
console.log('\n Schema Reference (stored as metadata):');
console.log(` Object: ${ref.objectId}`);
console.log(` Excluded Fields: ${ref.excludeFields?.join(', ')}`);
console.log(` Included Related: ${ref.includeRelated?.join(', ')}`);
console.log('\n ℹ️ Note: Schema resolution is handled by gateway/documentation tools,');
console.log(' not by the API Registry itself.');
}
await kernel.shutdown();
}
// Run all examples
async function main() {
try {
await example1_BasicApiRegistration();
await example2_MultiPluginDiscovery();
await example3_ConflictResolution();
await example4_CustomProtocol();
await example5_DynamicSchemas();
console.log('\n=== All examples completed successfully! ===\n');
} catch (error) {
console.error('Example failed:', error);
process.exit(1);
}
}
// Only run if this file is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}
export {
example1_BasicApiRegistration,
example2_MultiPluginDiscovery,
example3_ConflictResolution,
example4_CustomProtocol,
example5_DynamicSchemas,
};