forked from LeCoupa/awesome-cheatsheets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moleculer.js
747 lines (585 loc) · 21.9 KB
/
moleculer.js
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/* *******************************************************************************************
* MOLECULER MICROSERVICES FRAMEWORK - CORE CHEATSHEET
* http://moleculer.services/0.12/docs/
*
* Version: 0.12.x
* ******************************************************************************************* */
/* *******************************************************************************************
* Install Moleculer
* ******************************************************************************************* */
```bash
npm i moleculer
```
/* *******************************************************************************************
* SERVICE BROKER OPTIONS
* ******************************************************************************************* */
// All ServiceBroker options with default values
const broker = new ServiceBroker({
namespace: "", // Namespace for node segmentation
nodeID: null, // NodeID. Default value is generated from hostname and PID
logger: null, // Logger instance.
logLevel: null, // Log level
logFormatter: "default", // Log formatter. Options: "default", "simple"
transporter: null, // Transporter config
requestTimeout: 0 * 1000, // Timeout of requests
requestRetry: 0, // Retries for requests
maxCallLevel: 0, // Maximum calling level.
heartbeatInterval: 5, // Heartbeat sending interval in seconds
heartbeatTimeout: 15, // Heartbeat timeout in seconds
disableBalancer: false, // Disable the built-in Moleculer balancer
registry: { // Service Registry options
strategy: "RoundRobin", // Invocation strategy
strategyOptions: null, // Strategy options
preferLocal: true // Prefer local invocations
},
circuitBreaker: { // Circuit-breaker options
enabled: false, // Enable circuit-breaker
maxFailures: 3, // Maximum failures
halfOpenTime: 10 * 1000, // Half-open time interval
failureOnTimeout: true, // Failure on timeouts
failureOnReject: true // Failure on rejects
},
transit: { // Transit options
maxQueueSize: 50 * 1000 // Max items in outgoing queue
},
cacher: null, // Cacher config
serializer: null, // Serializer config
validation: true, // Enable params validation
validator: null, // Validator instance
metrics: false, // Enable metrics
metricsRate: 1, // Metrics rate
statistics: false, // Enable statistics
internalServices: true, // Load internal ($node) services
hotReload: false, // Hot-reload services
middlewares: null, // List of middlewares
replCommands: null, // Custom REPL commands
ServiceFactory: null, // Custom Service factory class
ContextFactory: null // Custom Context factory class
});
/* *******************************************************************************************
* SERVICE BROKER METHODS
* ******************************************************************************************* */
// Broker properties
broker.Promise // Pointer to Bluebird Promise lib
broker.namespace // Namespace from options
broker.nodeID // Local NodeID
broker.logger // Logger instance
broker.cacher // Cacher instance
broker.serializer // Serializer instance
broker.validator // Validator instance
// Broker methods
broker.start(); // Start broker & all services. Returns a Promise
broker.stop(); // Stop broker & all services. Returns a Promise
broker.fatal(message, err, needExit = true); // Fired a fatal error.
broker.repl(); // Switch broker to REPL mode.
broker.getLogger(module, service, version); // Create a custom logger instance for modules
broker.loadServices(folder, fileMask); // Load all services from directory
broker.loadService(filePath); // Load a service from a file
broker.createService(schema, schemaMods); // Create a local service from schema
broker.destroyService(service); // Destroy a local service
broker.getLocalService(name, version); // Get a local service instance by name
// Wait for services. Returns a Promise
await broker.waitForServices(serviceNames, timeout, interval);
await broker.waitForServices(["posts", "users"], 5000);
await broker.waitForServices({
name: "posts", version: 2,
name: "users", version: 1
}, 5000);
broker.use(...middlewares); // Register middlewares
broker.call(actionName, params, opts); // Call a service
broker.mcall(def); // Multiple service calls
broker.emit(eventName, payload, groups); // Emit a balanced event
broker.broadcast(eventName, payload, groups = null) // Broadcast an event
broker.broadcastLocal(eventName, payload, groups = null) // Broadcast an event to local services
broker.sendPing(nodeID); // Ping a remote node
broker.MOLECULER_VERSION // Version number of Moleculer lib
broker.PROTOCOL_VERSION // Version number of Moleculer protocol
/* *******************************************************************************************
* BROKER SERVICE CALLS
* ******************************************************************************************* */
// Call the "users.get" service with params
broker.call("users.get", { id: 150 }).then(user => console.log(user));
// Call with async/await
const user = await broker.call("users.get", { id: 150});
// Call with calling options
const user = await broker.call("users.get", { id: 150}, { timeout: 5000, retryCount: 3 });
// Direct call to a remote node
const info = await broker.call("$node.services", null, { nodeID: "node-123" });
// Multiple calls with array def
const [posts, users] = await broker.mcall([
{ action: "posts.find", params: { limit: 5, offset: 0 } },
{ action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
]);
// Multip calls with object def
const res = await broker.mcall({
posts: { action: "posts.find", params: { limit: 5, offset: 0 } },
users: { action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
});
console.log(res.posts, res.users);
/* *******************************************************************************************
* BROKER EVENTS
* ******************************************************************************************* */
// Send a balanced event with payload
broker.emit("user.created", { user: user });
// Send a balanced event only for "mail" and "payment" service (only one instance)
broker.emit("user.created", { user: user }, ["mail", "payment"]);
// Send a broadcast event (for all service instances)
broker.broadcast("user.created", { user: user });
// Send a broadcast event only for "mail" and "payment" services (all instances)
broker.broadcast("user.created", { user: user }, ["mail", "payment"]);
/* *******************************************************************************************
* NATS TRANSPORTER
* Requirement: `npm i nats`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "NATS"
});
// With URI
const broker = new ServiceBroker({
transporter: "nats://localhost:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
user: "admin",
pass: "1234"
}
}
});
// With TLS (https://github.com/nats-io/node-nats#tls)
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
tls: {
key: fs.readFileSync('./client-key.pem'),
cert: fs.readFileSync('./client-cert.pem'),
ca: [ fs.readFileSync('./ca.pem') ]
}
}
}
});
/* *******************************************************************************************
* REDIS TRANSPORTER
* Requirement: `npm i ioredis`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Redis"
});
// With URI
const broker = new ServiceBroker({
transporter: "redis://redis-server:6379"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "Redis",
options: {
port: 6379, // Redis port
host: 'redis-server', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: 'auth', // Password
db: 0 // Database index
}
}
});
/* *******************************************************************************************
* MQTT TRANSPORTER
* Requirement: `npm i mqtt`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "MQTT"
});
// With URI
const broker = new ServiceBroker({
transporter: "mqtt://mqtt-server:1883"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "MQTT",
options: {
host: "mqtt-server",
port: 1883,
username: "admin",
password: "1234"
}
}
});
/* *******************************************************************************************
* AMQP TRANSPORTER
* Requirement: `npm i amqplib`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "AMQP"
});
// With URI
const broker = new ServiceBroker({
transporter: "amqp://rabbitmq-server:5672"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "AMQP",
options: {
url: "amqp://user:pass@rabbitmq-server:5672",
eventTimeToLive: 5000,
prefetch: 1
}
}
});
/* *******************************************************************************************
* KAFKA TRANSPORTER
* Requirement: `npm i kafka-node`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Kafka"
});
// With URI
const broker = new ServiceBroker({
transporter: "kafka://192.168.51.29:2181"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "kafka",
options: {
host: "192.168.51.29:2181",
// KafkaClient options. More info: https://github.com/SOHU-Co/kafka-node#clientconnectionstring-clientid-zkoptions-noackbatchoptions-ssloptions
client: {
zkOptions: undefined,
noAckBatchOptions: undefined,
sslOptions: undefined
},
// KafkaProducer options. More info: https://github.com/SOHU-Co/kafka-node#producerclient-options-custompartitioner
producer: {},
customPartitioner: undefined,
// ConsumerGroup options. More info: https://github.com/SOHU-Co/kafka-node#consumergroupoptions-topics
consumer: {
},
// Advanced options for `send`. More info: https://github.com/SOHU-Co/kafka-node#sendpayloads-cb
publish: {
partition: 0,
attributes: 0
}
}
}
});
/* *******************************************************************************************
* NATS STREAMING TRANSPORTER
* Requirement: `npm i node-nats-streaming`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "STAN"
});
// With URI
const broker = new ServiceBroker({
transporter: "stan://192.168.0.120:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "STAN",
options: {
url: "stan://127.0.0.1:4222",
clusterID: "my-cluster"
}
}
});
/* *******************************************************************************************
* TCP STREAMING TRANSPORTER
* No requirements
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "TCP"
});
// With static node list
const broker = new ServiceBroker({
transporter: "tcp://172.17.0.1:6000/node-1,172.17.0.2:6000/node-2"
});
const broker = new ServiceBroker({
nodeID: "node-1",
transporter: {
type: "TCP",
options: {
udpDiscovery: false,
urls: [
"172.17.0.1:6000/node-1",
"172.17.0.2:6000/node-2",
"172.17.0.3:6000/node-3"
]
}
}
});
// With full options
const broker = new ServiceBroker({
logger: true,
transporter: {
type: "TCP",
options: {
// Enable UDP discovery
udpDiscovery: true,
// Reusing UDP server socket
udpReuseAddr: true,
// UDP port
udpPort: 4445,
// UDP bind address
udpBindAddress: null,
// UDP sending period
udpPeriod: 5,
// Multicast address.
udpMulticast: "239.0.0.0",
// Multicast TTL setting
udpMulticastTTL: 1,
// Send broadcast
udpBroadcast: false,
// TCP server port. Null or 0 means random port
port: null,
// Static remote nodes address list (when UDP discovery is not available)
urls: null,
// Use hostname as preffered connection address
useHostname: true,
// Gossip sending period in seconds
gossipPeriod: 2,
// Maximum enabled outgoing connections. If reach, close the old connections
maxConnections: 32,
// Maximum TCP packet size
maxPacketSize: 1 * 1024 * 1024
}
}
});
/* *******************************************************************************************
* CACHERS
* http://moleculer.services/docs/cachers.html
* ******************************************************************************************* */
// Memory cacher
const broker = new ServiceBroker({
cacher: "Memory"
});
// or
const broker = new ServiceBroker({
cacher: true
});
// Memory cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Memory",
options: {
ttl: 30
}
}
});
// Redis cacher
const broker = new ServiceBroker({
cacher: "Redis"
});
// Redis cacher with URI
const broker = new ServiceBroker({
cacher: "redis://redis-server:6379"
});
// Redis cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Redis",
options: {
prefix: "MOL",
redis: {
host: "redis",
port: 6379,
password: "1234",
db: 0
}
}
}
});
/* *******************************************************************************************
* Manual caching
* ******************************************************************************************* */
// Save to cache
broker.cacher.set("mykey.a", { a: 5 });
// Get from cache
const obj = await broker.cacher.get("mykey.a");
// Remove entry from cache
broker.cacher.del("mykey.a");
// Clean all 'mykey' entries
broker.cacher.clean("mykey.*");
// Clean all entries
broker.cacher.clean();
/* *******************************************************************************************
* SERIALIZER
* http://moleculer.services/docs/serializers.html
* ******************************************************************************************* */
// JSON serializer (default)
const broker = new ServiceBroker({
serializer: "JSON"
});
// Avro serializer (need `npm i avsc`)
const broker = new ServiceBroker({
serializer: "Avro"
});
// Protocol Buffer serializer (need `npm i protobufjs`)
const broker = new ServiceBroker({
serializer: "ProtoBuf"
});
// MsgPack serializer (need `npm i msgpack5`)
const broker = new ServiceBroker({
serializer: "MsgPack"
});
/* *******************************************************************************************
* STRATEGY
* ******************************************************************************************* */
// Round-robin strategy (default)
const broker = new ServiceBroker({
registry: {
strategy: "RoundRobin"
}
});
// Random strategy
const broker = new ServiceBroker({
registry: {
strategy: "Random"
}
});
// CPU usage-based strategy
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy"
}
});
// CPU usage-based strategy with options
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy",
strategyOptions: {
sampleCount: 3,
lowCpuUsage: 10
}
}
});
/* *******************************************************************************************
* LOGGER
* http://moleculer.services/docs/logger.html
* ******************************************************************************************* */
// Logger methods
broker.logger.fatal();
broker.logger.error();
broker.logger.warn();
broker.logger.info();
broker.logger.debug();
broker.logger.trace();
// Custom log formatter
const broker = new ServiceBroker({
logger: console,
logFormatter(level, args, bindings) {
return level.toUpperCase() + " " + bindings.nodeID + ": " + args.join(" ");
}
});
// External Pino logger
const pino = require("pino")({ level: "info" });
const broker = new ServiceBroker({
logger: bindings => pino.child(bindings)
});
// External Bunyan logger
const logger = require("bunyan").createLogger({ name: "moleculer", level: "info" });
const broker = new ServiceBroker({
logger: bindings => logger.child(bindings)
});
/* *******************************************************************************************
* SERVICE SCHEMA
* ******************************************************************************************* */
module.exports = {
// Name
name: "greeter",
// Version
version: 2,
// Settings
settings: {},
// Metadata
metadata: {},
// Dependencies
dependencies: [],
// Actions
actions: {
// Shorthand actions
hello() {
// Call a method
this.doSomething();
return "Hello Moleculer";
},
// With properties
welcome: {
// Cache options
cache: {
keys: ["name"]
},
// Validation options
params: {
name: "string"
},
// Action handler
handler(ctx) {
return `Welcome, ${ctx.params.name}`;
}
}
},
events: {
"user.created"(payload, sender) {
}
},
// Service methods
methods: {
doSomething() {}
},
// Lifecycle event handlers
created() {
console.log("Service created");
},
started() {
console.log("Service started");
return Promise.resolve();
},
stopped() {
console.log("Service stopped");
return Promise.resolve();
}
};
/* *******************************************************************************************
* SERVICE
* ******************************************************************************************* */
this.name // Name of service
this.version // Version of service
this.settings // Settings of service
this.schema // Schema definition of service
this.broker // Broker instance
this.Promise // Class of Promise (Bluebird)
this.logger // Logger instance
this.actions // Actions of service.
this.waitForServices // Pointer to ‘broker.waitForServices’ method
/* *******************************************************************************************
* CONTEXT
* ******************************************************************************************* */
ctx.id // Context ID
ctx.broker // Broker instance
ctx.action // Action definition
ctx.nodeID // Node ID
ctx.requestID // Request ID
ctx.parentID // ID of parent context (in case of sub-calls).
ctx.params // Request params
ctx.meta // Request metadata
ctx.callerNodeID // Caller Node ID if it is requested from a remote node.
ctx.level // Request level (in case of sub-calls). The first level is 1.
// Make a sub-call
ctx.call(actionName, params, callingOptions)
// Emit an event
ctx.emit(eventName, payload, groups);