|
| 1 | +/** |
| 2 | + * The following code is only for demonstration purpose. |
| 3 | + * |
| 4 | + * DO NOT use it in production. |
| 5 | + */ |
| 6 | + |
| 7 | +import { |
| 8 | + ComcatPump, |
| 9 | + ComcatPumpOptions, |
| 10 | + ComcatPipe, |
| 11 | + ComcatPipeOptions, |
| 12 | +} from 'comcat'; |
| 13 | + |
| 14 | +/** |
| 15 | + * NOTE |
| 16 | + * |
| 17 | + * This example shows how to create a new class derived from `ComcatPump`, |
| 18 | + * or `ComcatPipe`, to achieve a little bit "cleaner" code. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * In case you need your own constructor parameters, |
| 23 | + * you can extend the definition from `ComcatPumpOptions`. |
| 24 | + */ |
| 25 | +interface PollingPumpOptions extends ComcatPumpOptions { |
| 26 | + myParams?: any; |
| 27 | +} |
| 28 | + |
| 29 | +class PollingPump extends ComcatPump { |
| 30 | + private readonly interval = 60 * 1000; |
| 31 | + private intervalHandler = -1; |
| 32 | + |
| 33 | + public constructor(options: PollingPumpOptions) { |
| 34 | + super(options); |
| 35 | + |
| 36 | + // ... |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * When override the default callback, you should always use "Arrow Function". |
| 41 | + */ |
| 42 | + public onConnect = () => { |
| 43 | + this.intervalHandler = setInterval(() => { |
| 44 | + fetch('http://worldtimeapi.org/api/ip') |
| 45 | + .then((res) => { |
| 46 | + return res.json(); |
| 47 | + }) |
| 48 | + .then((data) => { |
| 49 | + /** |
| 50 | + * Now you can directly use `pump` method. |
| 51 | + */ |
| 52 | + this.pump('Time', data.datetime); |
| 53 | + this.pump('Unix', data.unixtime); |
| 54 | + }); |
| 55 | + }, this.interval); |
| 56 | + }; |
| 57 | + |
| 58 | + public onDisconnect = /** Also "Arrow Function" here. */ () => { |
| 59 | + clearInterval(this.intervalHandler); |
| 60 | + }; |
| 61 | +} |
| 62 | + |
| 63 | +const pump = new PollingPump({ category: 'example' }); |
| 64 | +pump.start(); |
| 65 | + |
| 66 | +/** |
| 67 | + * Now let's create a derived pipe. It's basically the same as creating a pump. |
| 68 | + */ |
| 69 | + |
| 70 | +interface MyPipeOptions extends ComcatPipeOptions { |
| 71 | + myParams?: any; |
| 72 | +} |
| 73 | + |
| 74 | +class MyPipe extends ComcatPipe { |
| 75 | + public constructor(options: MyPipeOptions) { |
| 76 | + super(options); |
| 77 | + |
| 78 | + // ... |
| 79 | + } |
| 80 | + |
| 81 | + public onMessage = /** Also "Arrow Function" here. */ ( |
| 82 | + topic: string, |
| 83 | + data: unknown |
| 84 | + ) => { |
| 85 | + // ... |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +const pipe = new MyPipe({ topic: 'example' }); |
| 90 | +pipe.start(); |
0 commit comments