@avtechno/sfr 1.0.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/README.md +72 -0
- package/dist/example.mjs +33 -0
- package/dist/index.mjs +84 -0
- package/dist/logger.mjs +37 -0
- package/dist/mq.mjs +217 -0
- package/dist/sfr-pipeline.mjs +465 -0
- package/dist/templates.mjs +47 -0
- package/dist/types/example.d.mts +11 -0
- package/dist/types/index.d.mts +7 -0
- package/dist/types/logger.d.mts +3 -0
- package/dist/types/mq.d.mts +105 -0
- package/dist/types/sfr-pipeline.d.mts +33 -0
- package/dist/types/templates.d.mts +8 -0
- package/dist/types/util.d.mts +7 -0
- package/dist/util.mjs +25 -0
- package/package.json +51 -0
- package/src/example.mts +35 -0
- package/src/index.mts +99 -0
- package/src/logger.mts +52 -0
- package/src/mq.mts +236 -0
- package/src/sfr-pipeline.mts +508 -0
- package/src/templates.mts +55 -0
- package/src/types/index.d.ts +395 -0
- package/src/util.mts +32 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import fs from "fs/promises";
|
|
3
|
+
import { template } from "./util.mjs";
|
|
4
|
+
import { BroadcastMQ, TargetedMQ } from "./mq.mjs";
|
|
5
|
+
import j2s from "joi-to-swagger";
|
|
6
|
+
import { logger } from "./logger.mjs";
|
|
7
|
+
const CWD = process.cwd();
|
|
8
|
+
const PATTERNS = ["Point-to-Point", "Request-Reply", "Publish-Subscribe", "Routing", "Topic"];
|
|
9
|
+
const TARGETED_PATTERN = ["Point-to-Point", "Request-Reply"];
|
|
10
|
+
export class SFRPipeline {
|
|
11
|
+
cfg;
|
|
12
|
+
oas_cfg;
|
|
13
|
+
comms;
|
|
14
|
+
base_url;
|
|
15
|
+
pattern_channels;
|
|
16
|
+
mount_data = {
|
|
17
|
+
rest: 0,
|
|
18
|
+
ws: 0,
|
|
19
|
+
mq: 0
|
|
20
|
+
};
|
|
21
|
+
/* Contains values that are injected into each protocol's handlers. */
|
|
22
|
+
static injections = {
|
|
23
|
+
rest: {
|
|
24
|
+
handlers: {},
|
|
25
|
+
controllers: {}
|
|
26
|
+
},
|
|
27
|
+
mq: {
|
|
28
|
+
handlers: {},
|
|
29
|
+
controllers: {}
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
constructor(cfg, oas_cfg, comms) {
|
|
33
|
+
this.cfg = cfg;
|
|
34
|
+
this.oas_cfg = oas_cfg;
|
|
35
|
+
this.comms = comms;
|
|
36
|
+
}
|
|
37
|
+
async init(base_url) {
|
|
38
|
+
this.base_url = base_url;
|
|
39
|
+
if (this.comms["MQ"]) {
|
|
40
|
+
//Create channels for each type of Communication Pattern
|
|
41
|
+
const channels = await Promise.all(PATTERNS.map(async (v) => {
|
|
42
|
+
const channel = await this.comms["MQ"].createChannel();
|
|
43
|
+
const mq = TARGETED_PATTERN.includes(v) ? new TargetedMQ(channel, v) : new BroadcastMQ(channel, v);
|
|
44
|
+
return [v, mq];
|
|
45
|
+
}));
|
|
46
|
+
this.pattern_channels = Object.fromEntries(channels);
|
|
47
|
+
SFRPipeline.injections.rest.handlers = {
|
|
48
|
+
...SFRPipeline.injections.rest.handlers,
|
|
49
|
+
mq: this.pattern_channels
|
|
50
|
+
};
|
|
51
|
+
SFRPipeline.injections.mq.handlers = {
|
|
52
|
+
...SFRPipeline.injections.mq.handlers,
|
|
53
|
+
mq: this.pattern_channels
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//Declarations for each protocol in key/value pairs.
|
|
57
|
+
let protocols = await this.file_parsing();
|
|
58
|
+
//Filter protocols that have been parsed if its' associated SFRProtocol has been defined
|
|
59
|
+
/* @ts-ignore */
|
|
60
|
+
protocols = Object.fromEntries(Object.entries(protocols).filter(([k]) => this.comms[k]).map(([k, v]) => [k, v]));
|
|
61
|
+
await this.fn_binding(protocols);
|
|
62
|
+
this.print_to_console();
|
|
63
|
+
return this.spec_generation(protocols);
|
|
64
|
+
}
|
|
65
|
+
// Handles the parsing of SFR files from the directory specified under cfg.out config.
|
|
66
|
+
// It returns a standard NamespaceDeclaration containing each declaration of each supported protocol.
|
|
67
|
+
async file_parsing() {
|
|
68
|
+
//These are the officially supported protocols of the SFR library
|
|
69
|
+
const SUPPORTED_PROTOCOLS = ["rest", "ws", "mq"];
|
|
70
|
+
/*
|
|
71
|
+
Look for folders that match the supported protocols listed above in the designated directory
|
|
72
|
+
|
|
73
|
+
cfg.root = "Specifies the working directory"
|
|
74
|
+
cfg.path = "Specifies the API directory i.e: where SFR files reside"
|
|
75
|
+
cfg.out = "Specifies the directory where the resulting OAS documents are outputted"
|
|
76
|
+
*/
|
|
77
|
+
const directory = path.join(CWD, this.cfg.root);
|
|
78
|
+
let paths = SUPPORTED_PROTOCOLS.map((v) => path.join(directory, `${this.cfg.path}/${v}`));
|
|
79
|
+
//Create the directories if it doesn't exist.
|
|
80
|
+
await Promise.all(paths.map((v) => fs.mkdir(v, { recursive: true })));
|
|
81
|
+
//Recursively retrieve all SFRs of each protocol
|
|
82
|
+
let sfr_paths = await Promise.all(paths.map((path) => resolve_sfrs(path)));
|
|
83
|
+
//Import SFRs
|
|
84
|
+
const protocols = await Promise.all(sfr_paths.map((protocol) => import_sfrs(protocol)));
|
|
85
|
+
const REST = protocols[0];
|
|
86
|
+
logger.info(`${Object.keys(protocols[0]).length} REST SFR`);
|
|
87
|
+
const WS = protocols[1];
|
|
88
|
+
logger.info(`${Object.keys(protocols[1]).length} WS SFR`);
|
|
89
|
+
const MQ = protocols[2];
|
|
90
|
+
logger.info(`${Object.keys(protocols[2]).length} MQ SFR`);
|
|
91
|
+
return { REST, WS, MQ };
|
|
92
|
+
}
|
|
93
|
+
// Handles the binding of the components of each SFR (e.g: executing validators of matching endpoints, injecting controllers to each handler, etc.)
|
|
94
|
+
//Owing to their differing nature, spec generation and fn_binding is handled this way so as to split up the individual logics involved in parsing them.
|
|
95
|
+
async fn_binding(protocols) {
|
|
96
|
+
Object.entries(protocols).forEach(([protocol, declaration]) => {
|
|
97
|
+
switch (protocol) {
|
|
98
|
+
case "REST":
|
|
99
|
+
this.bind_rest_fns(declaration);
|
|
100
|
+
break;
|
|
101
|
+
case "WS":
|
|
102
|
+
this.bind_ws_fns(declaration);
|
|
103
|
+
break;
|
|
104
|
+
case "MQ":
|
|
105
|
+
this.bind_mq_fns(declaration);
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/* Fn Binding */
|
|
111
|
+
async bind_rest_fns(declaration) {
|
|
112
|
+
const comms = this.comms["REST"];
|
|
113
|
+
if (!comms)
|
|
114
|
+
throw new Error(`FN Binding failed: \nREST protocol lacks it's associated SFRProtocols`);
|
|
115
|
+
Object.entries(declaration).forEach(([namespace, module]) => {
|
|
116
|
+
let { cfg, validators, handlers } = module.content;
|
|
117
|
+
//Set base_directory
|
|
118
|
+
/*
|
|
119
|
+
Directory Order:
|
|
120
|
+
this.base_url -> Folder Structure -> cfg.base_dir
|
|
121
|
+
*/
|
|
122
|
+
let base_dir = "";
|
|
123
|
+
if (this.base_url)
|
|
124
|
+
base_dir = `/${this.base_url}`;
|
|
125
|
+
if (module.dir)
|
|
126
|
+
base_dir += `/${module.dir.toString().replaceAll(",", "/")}`;
|
|
127
|
+
if (cfg.base_dir)
|
|
128
|
+
base_dir += `/${cfg.base_dir}`;
|
|
129
|
+
logger.info(`[SFR ${module.name}] resolved path: ${base_dir}/${namespace}`);
|
|
130
|
+
const is_public = Boolean(cfg.public);
|
|
131
|
+
//Loop over all methods and their respective handlers
|
|
132
|
+
Object.entries(handlers).forEach(([method, handler_map]) => {
|
|
133
|
+
for (const [name, handler] of Object.entries(handler_map).filter(([k]) => validators[k])) {
|
|
134
|
+
const dir = `${base_dir}/${namespace}/${name}`;
|
|
135
|
+
console.log(dir);
|
|
136
|
+
const validator = validators[name];
|
|
137
|
+
const validator_type = typeof validator !== "function" ? "joi" : "multer";
|
|
138
|
+
/* bind validators */
|
|
139
|
+
switch (validator_type) {
|
|
140
|
+
case "joi":
|
|
141
|
+
{
|
|
142
|
+
comms[method.toLowerCase()](dir, (req, res, next) => {
|
|
143
|
+
let error = true;
|
|
144
|
+
if (is_public) {
|
|
145
|
+
//if(!req.session.user)return res.status(401).json({error : "Session not found."});
|
|
146
|
+
}
|
|
147
|
+
error = template(validator, method === "GET" ? req.query : req.body);
|
|
148
|
+
if (error)
|
|
149
|
+
return res.status(400).json({ error });
|
|
150
|
+
next();
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
case "multer":
|
|
155
|
+
{
|
|
156
|
+
comms[method.toLowerCase()](dir, validator);
|
|
157
|
+
/* @ts-ignore */
|
|
158
|
+
comms.use((err, req, res, next) => {
|
|
159
|
+
let temp = { error: err.message, details: err.cause };
|
|
160
|
+
if (err)
|
|
161
|
+
return res.status(400).json(temp);
|
|
162
|
+
next();
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
/* Bind to express app */
|
|
168
|
+
comms[method.toLowerCase()](dir, handler.fn);
|
|
169
|
+
this.mount_data.rest++;
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
async bind_ws_fns(declaration) {
|
|
175
|
+
}
|
|
176
|
+
async bind_mq_fns(declaration) {
|
|
177
|
+
const comms = this.comms["MQ"];
|
|
178
|
+
if (!comms)
|
|
179
|
+
throw new Error(`FN Binding failed: \nMQ protocol lacks it's associated SFRProtocols`);
|
|
180
|
+
Object.entries(declaration).forEach(([namespace, module]) => {
|
|
181
|
+
let { cfg, validators, handlers } = module.content;
|
|
182
|
+
//Set base_directory
|
|
183
|
+
let base_dir = cfg.base_dir ? `/${cfg.base_dir}` : "";
|
|
184
|
+
if (this.base_url)
|
|
185
|
+
base_dir = `/${this.base_url}/${base_dir}`;
|
|
186
|
+
if (module.dir)
|
|
187
|
+
base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
|
|
188
|
+
const is_public = Boolean(cfg.public);
|
|
189
|
+
//Loop over all methods and their respective handlers
|
|
190
|
+
Object.entries(handlers).forEach(([pattern, handler_map]) => {
|
|
191
|
+
//Get associated MQ for pattern
|
|
192
|
+
let mq = this.pattern_channels[pattern];
|
|
193
|
+
//Get all valid handlers (i.e: those with matching validators)
|
|
194
|
+
const valid_handlers = Object.entries(handler_map).filter(([k]) => validators[k]);
|
|
195
|
+
//Loop over each handler
|
|
196
|
+
for (let [name, handler] of valid_handlers) {
|
|
197
|
+
const dir = `${base_dir}${namespace}/${name}`;
|
|
198
|
+
const validator = validators[name];
|
|
199
|
+
const validator_type = typeof validator !== "function" ? "joi" : "multer"; // TODO: Dynamically update parameter content based on validator type.
|
|
200
|
+
let validator_fn = function (msg) {
|
|
201
|
+
const error = template(validator, msg.content);
|
|
202
|
+
if (error) {
|
|
203
|
+
if (mq instanceof TargetedMQ) {
|
|
204
|
+
if (error) {
|
|
205
|
+
switch (pattern) {
|
|
206
|
+
case "Request-Reply":
|
|
207
|
+
mq.reply(msg, { error });
|
|
208
|
+
break;
|
|
209
|
+
default: mq.channel.reject(msg, false);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (mq instanceof BroadcastMQ) {
|
|
214
|
+
mq.channel.reject(msg, false);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
handler.fn(msg);
|
|
218
|
+
};
|
|
219
|
+
/* bind validators */
|
|
220
|
+
if (mq instanceof TargetedMQ) {
|
|
221
|
+
mq.consume(dir, {
|
|
222
|
+
options: handler.options,
|
|
223
|
+
fn: validator_fn
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
if (mq instanceof BroadcastMQ) {
|
|
227
|
+
switch (pattern) {
|
|
228
|
+
case "Publish-Subscribe":
|
|
229
|
+
{
|
|
230
|
+
mq.subscribe(dir, "", {
|
|
231
|
+
options: handler.options,
|
|
232
|
+
fn: validator_fn
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
break;
|
|
236
|
+
case "Routing": {
|
|
237
|
+
/* @ts-ignore */
|
|
238
|
+
mq.subscribe(dir, handler.routing_key, {
|
|
239
|
+
options: handler.options,
|
|
240
|
+
fn: validator_fn
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
case "Topic": {
|
|
244
|
+
/* @ts-ignore */
|
|
245
|
+
mq.subscribe(dir, handler.binding_key, {
|
|
246
|
+
options: handler.options
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
this.mount_data.mq++;
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
// Generate OpenAPI and AsyncAPI specification.
|
|
257
|
+
spec_generation(protocols) {
|
|
258
|
+
// Holds the key/value pair of protocols and their respective API Documentation
|
|
259
|
+
const documents = Object.entries(protocols).map(([protocol, declaration]) => {
|
|
260
|
+
switch (protocol) {
|
|
261
|
+
case "REST": return [protocol, this.generate_open_api_document(declaration)];
|
|
262
|
+
case "WS": return [protocol, this.generate_async_api_document(declaration)];
|
|
263
|
+
case "MQ": return [protocol, this.generate_async_api_document(declaration)];
|
|
264
|
+
default: throw new Error(`Failed to generate SFR Spec: ${protocol} protocol is unknown.`);
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
return Object.fromEntries(documents);
|
|
268
|
+
}
|
|
269
|
+
generate_open_api_document(declaration) {
|
|
270
|
+
// This will hold the final OpenAPI Document.
|
|
271
|
+
const spec = {
|
|
272
|
+
openapi: "3.0.0",
|
|
273
|
+
info: Object.assign({}, this.oas_cfg),
|
|
274
|
+
paths: {}
|
|
275
|
+
};
|
|
276
|
+
// Iterate through each protocol (e.g., REST, WS, MQ)
|
|
277
|
+
Object.entries(declaration).forEach(([namespace, module]) => {
|
|
278
|
+
const { cfg, handlers, validators } = module.content;
|
|
279
|
+
//Set base_directory
|
|
280
|
+
let base_dir = cfg.base_dir ? `/${cfg.base_dir}/` : "/";
|
|
281
|
+
if (this.base_url)
|
|
282
|
+
base_dir = `/${this.base_url}${base_dir}`;
|
|
283
|
+
if (module.dir)
|
|
284
|
+
base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
|
|
285
|
+
// Collect the OpenAPI path object for each handler (method)
|
|
286
|
+
for (let [method, handler_map] of Object.entries(handlers)) {
|
|
287
|
+
//Transform method to lowercase
|
|
288
|
+
method = method.toLowerCase();
|
|
289
|
+
// Define the operation (method) for this endpoint
|
|
290
|
+
for (const [endpoint, body] of Object.entries(handler_map)) {
|
|
291
|
+
const validator = validators[endpoint];
|
|
292
|
+
// Skip if no matching validator
|
|
293
|
+
if (!validator)
|
|
294
|
+
continue;
|
|
295
|
+
const validator_type = typeof validator !== "function" ? "joi" : "multer";
|
|
296
|
+
//Default tags are used for service and router level classification (developer platform)
|
|
297
|
+
let default_tags = [
|
|
298
|
+
`sfr-router:${namespace}`,
|
|
299
|
+
`sfr-service:${this.oas_cfg.title || "unspecified"}`
|
|
300
|
+
];
|
|
301
|
+
if (body.tags && Array.isArray(body.tags))
|
|
302
|
+
default_tags.push(...body.tags);
|
|
303
|
+
const operation_id = `${base_dir}${namespace}/${endpoint}`;
|
|
304
|
+
const document = {
|
|
305
|
+
operationId: `${method.toUpperCase()}:${operation_id}`,
|
|
306
|
+
summary: body.summary || "",
|
|
307
|
+
description: body.description || "",
|
|
308
|
+
tags: default_tags,
|
|
309
|
+
public: Boolean(cfg.public),
|
|
310
|
+
responses: {
|
|
311
|
+
"200": {
|
|
312
|
+
description: "Successful operation",
|
|
313
|
+
content: { "application/json": { schema: { type: "object" } } }
|
|
314
|
+
},
|
|
315
|
+
"400": {
|
|
316
|
+
description: "An error has occured",
|
|
317
|
+
content: { "application/json": { schema: { type: "object" } } }
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
//Insert either a parameter or a requestBody according to the method type
|
|
322
|
+
if (validator_type === "joi") {
|
|
323
|
+
document[method === "GET" ? "parameters" : "requestBody"] = j2s(validator).swagger;
|
|
324
|
+
}
|
|
325
|
+
//Haven't found a library for converting multer validators to swagger doc
|
|
326
|
+
if (validator_type === "multer") {
|
|
327
|
+
}
|
|
328
|
+
//Create path if it does not exist.
|
|
329
|
+
if (!spec.paths[operation_id])
|
|
330
|
+
spec.paths[operation_id] = {};
|
|
331
|
+
if (!spec.paths[operation_id][method.toLowerCase()])
|
|
332
|
+
spec.paths[operation_id][method.toLowerCase()] = document;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
//Conform to OAPI standards by appending "x-property" on each field under "meta"
|
|
337
|
+
/* @ts-ignore */
|
|
338
|
+
spec.info.meta = Object.fromEntries(Object.entries(spec.info.meta).map(([k, v]) => [`x-${k}`, v]));
|
|
339
|
+
return spec;
|
|
340
|
+
}
|
|
341
|
+
// Method to generate an AsyncAPI document from an MQNamespaceDeclaration
|
|
342
|
+
generate_async_api_document(declaration) {
|
|
343
|
+
// This will hold the final AsyncAPI Document.
|
|
344
|
+
const spec = {
|
|
345
|
+
asyncapi: '3.0.0',
|
|
346
|
+
info: Object.assign({}, this.oas_cfg),
|
|
347
|
+
channels: {},
|
|
348
|
+
operations: {},
|
|
349
|
+
components: {
|
|
350
|
+
messages: {},
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
//Conform to OAPI standards by appending "x-property" on each field under "meta"
|
|
354
|
+
/* @ts-ignore */
|
|
355
|
+
spec.info.meta = Object.fromEntries(Object.entries(spec.info.meta).map(([k, v]) => [`x-${k}`, v]));
|
|
356
|
+
Object.entries(declaration).forEach(([namespace, module]) => {
|
|
357
|
+
let { cfg, validators, handlers } = module.content;
|
|
358
|
+
//Set base_directory
|
|
359
|
+
let base_dir = cfg.base_dir ? `/${cfg.base_dir}/` : "";
|
|
360
|
+
if (this.base_url)
|
|
361
|
+
base_dir = `/${this.base_url}/${base_dir}`;
|
|
362
|
+
if (module.dir)
|
|
363
|
+
base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
|
|
364
|
+
const is_public = Boolean(cfg.public);
|
|
365
|
+
//Loop over all methods and their respective handlers
|
|
366
|
+
Object.entries(handlers).forEach(([pattern, handler_map]) => {
|
|
367
|
+
//Get associated MQ for pattern
|
|
368
|
+
let mq = this.pattern_channels[pattern];
|
|
369
|
+
//Get all valid handlers (i.e: those with matching validators)
|
|
370
|
+
const valid_handlers = Object.entries(handler_map).filter(([k]) => validators[k]);
|
|
371
|
+
//Loop over each handler
|
|
372
|
+
for (let [name, handler] of valid_handlers) {
|
|
373
|
+
const dir = `${base_dir}${namespace}/${name}`;
|
|
374
|
+
const validator = validators[name];
|
|
375
|
+
const validator_type = typeof validator !== "function" ? "joi" : "multer"; // TODO: Dynamically update parameter content based on validator type.
|
|
376
|
+
const channel_document = {
|
|
377
|
+
address: dir,
|
|
378
|
+
messages: {}
|
|
379
|
+
};
|
|
380
|
+
const operation_document = {
|
|
381
|
+
action: "receive",
|
|
382
|
+
summary: handler.summary || "",
|
|
383
|
+
description: handler.description || "",
|
|
384
|
+
channel: `#/channels/${name}`
|
|
385
|
+
};
|
|
386
|
+
//Insert either a parameter or a requestBody according to the method type
|
|
387
|
+
if (validator_type === "joi") {
|
|
388
|
+
channel_document.messages[`${name}-message`] = {
|
|
389
|
+
name: `${name}-message`,
|
|
390
|
+
payload: j2s(validator).swagger
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
//Haven't found a library for converting multer validators to swagger doc
|
|
394
|
+
if (validator_type === "multer") {
|
|
395
|
+
}
|
|
396
|
+
spec.channels[name] = channel_document;
|
|
397
|
+
spec.operations[name] = operation_document;
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
return spec;
|
|
402
|
+
}
|
|
403
|
+
// Method to print SFR info to console
|
|
404
|
+
print_to_console() {
|
|
405
|
+
console.log(`____________________________
|
|
406
|
+
| | Mounted
|
|
407
|
+
| ░██████╗███████╗██████╗░ | REST : ${this.mount_data.rest}
|
|
408
|
+
| ██╔════╝██╔════╝██╔══██╗ | WS : ${this.mount_data.ws}
|
|
409
|
+
| ╚█████╗░█████╗░░██████╔╝ | MQ : ${this.mount_data.mq}
|
|
410
|
+
| ░╚═══██╗██╔══╝░░██╔══██╗ |-----------
|
|
411
|
+
| ██████╔╝██║░░░░░██║░░██║ | Protocols
|
|
412
|
+
| ╚═════╝░╚═╝░░░░░╚═╝░░╚═╝ | REST : ${this.comms["REST"] ? "✅" : "❌"}
|
|
413
|
+
| Single File Router | MQ : ${this.comms["MQ"] ? "✅" : "❌"}
|
|
414
|
+
| | WS : ${this.comms["WS"] ? "✅" : "❌"}
|
|
415
|
+
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
/* Utility fns */
|
|
419
|
+
/* File Parsing */
|
|
420
|
+
async function resolve_sfrs(dir, prefix) {
|
|
421
|
+
//Get Directory Contents
|
|
422
|
+
const contents = await fs.readdir(dir);
|
|
423
|
+
const results = [];
|
|
424
|
+
//Loop over contents
|
|
425
|
+
await Promise.all(contents.map(async (v) => {
|
|
426
|
+
const content_path = path.join(dir, v);
|
|
427
|
+
const is_dir = (await fs.lstat(content_path)).isDirectory();
|
|
428
|
+
//If Directory, perform a recursion and return output of contents.map fn.
|
|
429
|
+
if (is_dir) {
|
|
430
|
+
const dir_output = await resolve_sfrs(content_path, prefix ? `${prefix}/${v}` : v);
|
|
431
|
+
results.push(dir_output);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
;
|
|
435
|
+
let output = { name: v, path: content_path };
|
|
436
|
+
if (prefix)
|
|
437
|
+
output.dir = prefix.split("/");
|
|
438
|
+
results.push(output);
|
|
439
|
+
}));
|
|
440
|
+
return results.flat();
|
|
441
|
+
}
|
|
442
|
+
async function import_sfrs(protocol_files) {
|
|
443
|
+
const protocols = await Promise.all(protocol_files.map(async (v) => {
|
|
444
|
+
const import_task = await import(`file:///${v.path}`);
|
|
445
|
+
return [v.name.replace(".mjs", ""), {
|
|
446
|
+
...v,
|
|
447
|
+
content: import_task.default
|
|
448
|
+
}];
|
|
449
|
+
}));
|
|
450
|
+
//Removes SFRs without body.
|
|
451
|
+
return Object.fromEntries(protocols.filter((v) => v[1].content));
|
|
452
|
+
}
|
|
453
|
+
// Method to generate JSON schema for the payload based on handler metadata
|
|
454
|
+
function generate_json_schema(metadata) {
|
|
455
|
+
return {
|
|
456
|
+
type: 'object',
|
|
457
|
+
properties: {
|
|
458
|
+
example_field: {
|
|
459
|
+
type: 'string',
|
|
460
|
+
...metadata
|
|
461
|
+
},
|
|
462
|
+
},
|
|
463
|
+
required: ['example_field'],
|
|
464
|
+
};
|
|
465
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//Previous Name: RequestHandlerFactory
|
|
2
|
+
//Dependencies are imported and used by the functions below
|
|
3
|
+
import { SFRPipeline } from "./sfr-pipeline.mjs";
|
|
4
|
+
export function REST(struct) {
|
|
5
|
+
const validators = struct.validators || {};
|
|
6
|
+
const controllers = struct.controllers || {};
|
|
7
|
+
const handlers = struct.handlers || {};
|
|
8
|
+
const cfg = struct.cfg || {};
|
|
9
|
+
//Bind controller injections to each controllers
|
|
10
|
+
Object.entries(controllers).map(([k, v]) => controllers[k] = v.bind({ ...SFRPipeline.injections.rest.controllers }));
|
|
11
|
+
//Bind handler injections and SFR controllers into each handlers.
|
|
12
|
+
Object.entries(handlers).forEach(([method, handlermap]) => {
|
|
13
|
+
Object.entries(handlermap).forEach(([k, v]) => {
|
|
14
|
+
/* @ts-ignore */
|
|
15
|
+
handlers[method][k] = { ...v, fn: v.fn.bind({ ...controllers, ...SFRPipeline.injections.rest.handlers }) };
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
/* @ts-ignore */
|
|
19
|
+
return { validators, controllers, handlers, cfg };
|
|
20
|
+
}
|
|
21
|
+
export function WS(struct) {
|
|
22
|
+
const validators = struct.validators || {};
|
|
23
|
+
const controllers = struct.controllers || {};
|
|
24
|
+
const handlers = struct.handlers || {};
|
|
25
|
+
const cfg = struct.cfg || {};
|
|
26
|
+
//Dependency injection happens here...npm
|
|
27
|
+
return { validators, controllers, handlers, cfg };
|
|
28
|
+
}
|
|
29
|
+
export function MQ(struct) {
|
|
30
|
+
const validators = struct.validators || {};
|
|
31
|
+
const controllers = struct.controllers || {};
|
|
32
|
+
const handlers = struct.handlers || {};
|
|
33
|
+
const cfg = struct.cfg || {};
|
|
34
|
+
//Bind controller injections to each controllers
|
|
35
|
+
Object.entries(controllers).map(([k, v]) => controllers[k] = v.bind({ ...SFRPipeline.injections.mq.controllers }));
|
|
36
|
+
//Bind handler injections and SFR controllers into each handlers.
|
|
37
|
+
Object.entries(handlers).forEach(([pattern, handlermap]) => {
|
|
38
|
+
Object.entries(handlermap).forEach(([k, v]) => {
|
|
39
|
+
/* @ts-ignore */
|
|
40
|
+
const { mq } = (SFRPipeline.injections.mq.handlers || {});
|
|
41
|
+
/* @ts-ignore */
|
|
42
|
+
handlers[pattern][k] = { ...v, fn: v.fn.bind({ ...controllers, mq: mq ? mq[pattern] : null }) };
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
/* @ts-ignore */
|
|
46
|
+
return { validators, controllers, handlers, cfg };
|
|
47
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
declare const _default: {
|
|
2
|
+
GET: {
|
|
3
|
+
"get-something": {
|
|
4
|
+
description: string;
|
|
5
|
+
fn(req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>): Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
};
|
|
8
|
+
} & {
|
|
9
|
+
db_call(): Promise<string>;
|
|
10
|
+
};
|
|
11
|
+
export default _default;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/// <reference path="../../src/types/index.d.ts" />
|
|
2
|
+
import { REST, WS, MQ } from "./templates.mjs";
|
|
3
|
+
import { MQLib } from "./mq.mjs";
|
|
4
|
+
declare const _default: (cfg: ParserCFG, oas_cfg: OASConfig, connectors: SFRProtocols, base_url?: string) => Promise<ServiceManifest>;
|
|
5
|
+
export default _default;
|
|
6
|
+
declare function inject(injections: InjectedFacilities): void;
|
|
7
|
+
export { REST, WS, MQ, MQLib, inject };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { Connection, Options, Channel, ConsumeMessage } from "amqplib";
|
|
2
|
+
/**
|
|
3
|
+
* MQLib class for establishing a connection to the message queue and creating channels.
|
|
4
|
+
*/
|
|
5
|
+
export declare class MQLib {
|
|
6
|
+
private connection?;
|
|
7
|
+
private channel?;
|
|
8
|
+
/**
|
|
9
|
+
* Initializes the connection and channel to the message queue.
|
|
10
|
+
*
|
|
11
|
+
* @param MQ_URL - The URL of the message queue.
|
|
12
|
+
* @example
|
|
13
|
+
* const mqLib = new MQLib();
|
|
14
|
+
* await mqLib.init("amqp://localhost");
|
|
15
|
+
*/
|
|
16
|
+
init(MQ_URL: string): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Returns the connection object.
|
|
19
|
+
*
|
|
20
|
+
* @returns The connection object to the message queue.
|
|
21
|
+
*/
|
|
22
|
+
get_connection(): Connection;
|
|
23
|
+
/**
|
|
24
|
+
* Returns the channel object.
|
|
25
|
+
*
|
|
26
|
+
* @returns The channel object to the message queue.
|
|
27
|
+
*/
|
|
28
|
+
get_channel(): Channel;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* BroadcastMQ class to handle different types of broadcast communication patterns: Publish-Subscribe, Routing, and Topic.
|
|
32
|
+
*/
|
|
33
|
+
export declare class BroadcastMQ {
|
|
34
|
+
channel: Channel;
|
|
35
|
+
protected type: CommunicationPattern;
|
|
36
|
+
constructor(channel: Channel, type: CommunicationPattern);
|
|
37
|
+
/**
|
|
38
|
+
* Publishes a message to the specified exchange based on the communication pattern.
|
|
39
|
+
*
|
|
40
|
+
* @param exchange - The name of the exchange to send the message to.
|
|
41
|
+
* @param key - The routing key or pattern to use, depending on the communication pattern.
|
|
42
|
+
* @param payload - The message to be sent.
|
|
43
|
+
* @param options - Additional publishing options.
|
|
44
|
+
* @example
|
|
45
|
+
* // Publish a message to a 'logsExchange' with a routing key 'error' for a routing pattern.
|
|
46
|
+
* const mq = new BroadcastMQ(channel, "Routing");
|
|
47
|
+
* mq.publish("logsExchange", "error", { level: "error", message: "Something went wrong" });
|
|
48
|
+
*/
|
|
49
|
+
publish(exchange: string, key: string, payload: any, options?: Options.Publish): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Subscribes to an exchange to receive messages based on the communication pattern.
|
|
52
|
+
*
|
|
53
|
+
* @param exchange - The name of the exchange to subscribe to.
|
|
54
|
+
* @param key - The routing key or pattern to listen for.
|
|
55
|
+
* @param cfg - Configuration options for the consumer, including the callback function.
|
|
56
|
+
* @param options - Additional consumption options.
|
|
57
|
+
* @example
|
|
58
|
+
* // Subscribe to the 'logsExchange' for all 'error' messages in the Routing pattern.
|
|
59
|
+
* const mq = new BroadcastMQ(channel, "Routing");
|
|
60
|
+
* mq.subscribe("logsExchange", "error", { fn: handleErrorLogs, options: { noAck: true } });
|
|
61
|
+
*/
|
|
62
|
+
subscribe(exchange: string, key: string, cfg: ConsumerConfig, options?: Options.Publish): Promise<void>;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* TargetedMQ class to handle Point-to-Point and Request-Reply communication patterns.
|
|
66
|
+
*/
|
|
67
|
+
export declare class TargetedMQ {
|
|
68
|
+
channel: Channel;
|
|
69
|
+
protected type: CommunicationPattern;
|
|
70
|
+
constructor(channel: Channel, type: CommunicationPattern);
|
|
71
|
+
/**
|
|
72
|
+
* Sends a message to the specified queue depending on the communication pattern.
|
|
73
|
+
*
|
|
74
|
+
* @param binding - The name of the queue or binding to send the message to.
|
|
75
|
+
* @param payload - The message to be sent.
|
|
76
|
+
* @param options - Additional publishing options.
|
|
77
|
+
* @example
|
|
78
|
+
* // Send a message to a queue for point-to-point communication
|
|
79
|
+
* const mq = new TargetedMQ(channel, "Point-to-Point");
|
|
80
|
+
* mq.produce("taskQueue", { taskId: 1, action: "process" });
|
|
81
|
+
*/
|
|
82
|
+
produce(binding: string, payload: any, options?: Options.Publish): Promise<boolean>;
|
|
83
|
+
/**
|
|
84
|
+
* Sends a reply to the message sender in a Request-Reply pattern.
|
|
85
|
+
*
|
|
86
|
+
* @param msg - The original message to reply to.
|
|
87
|
+
* @param payload - The reply message to send back to the requester.
|
|
88
|
+
* @example
|
|
89
|
+
* // Send a response back to the client in a Request-Reply pattern
|
|
90
|
+
* const mq = new TargetedMQ(channel, "Request-Reply");
|
|
91
|
+
* mq.reply(msg, { result: "Processed successfully" });
|
|
92
|
+
*/
|
|
93
|
+
reply(msg: ConsumeMessage, payload: any): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Consumes messages from the specified queue based on the communication pattern.
|
|
96
|
+
*
|
|
97
|
+
* @param queue - The name of the queue to consume messages from.
|
|
98
|
+
* @param cfg - Configuration options for the consumer, including the callback function.
|
|
99
|
+
* @example
|
|
100
|
+
* // Consume a message from the 'taskQueue' in a Point-to-Point communication pattern
|
|
101
|
+
* const mq = new TargetedMQ(channel, "Point-to-Point");
|
|
102
|
+
* mq.consume("taskQueue", { fn: processTask, options: { noAck: true } });
|
|
103
|
+
*/
|
|
104
|
+
consume(queue: string, cfg: ConsumerConfig): Promise<void>;
|
|
105
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare class SFRPipeline {
|
|
2
|
+
private cfg;
|
|
3
|
+
private oas_cfg;
|
|
4
|
+
private comms;
|
|
5
|
+
base_url: string;
|
|
6
|
+
pattern_channels: PatternMQSet;
|
|
7
|
+
mount_data: {
|
|
8
|
+
rest: number;
|
|
9
|
+
ws: number;
|
|
10
|
+
mq: number;
|
|
11
|
+
};
|
|
12
|
+
static injections: {
|
|
13
|
+
rest: {
|
|
14
|
+
handlers: {};
|
|
15
|
+
controllers: {};
|
|
16
|
+
};
|
|
17
|
+
mq: {
|
|
18
|
+
handlers: {};
|
|
19
|
+
controllers: {};
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
constructor(cfg: ParserCFG, oas_cfg: OASConfig, comms: SFRProtocols);
|
|
23
|
+
init(base_url?: string): Promise<ServiceDocuments>;
|
|
24
|
+
private file_parsing;
|
|
25
|
+
private fn_binding;
|
|
26
|
+
private bind_rest_fns;
|
|
27
|
+
private bind_ws_fns;
|
|
28
|
+
private bind_mq_fns;
|
|
29
|
+
private spec_generation;
|
|
30
|
+
private generate_open_api_document;
|
|
31
|
+
private generate_async_api_document;
|
|
32
|
+
private print_to_console;
|
|
33
|
+
}
|