|
| 1 | +const https = require('node:https'); |
| 2 | + |
| 3 | +/** |
| 4 | + * EN: Real World Example for the Command Design Pattern |
| 5 | + * |
| 6 | + * Need: Execute a command to retrieve random information every X seconds |
| 7 | + * |
| 8 | + * Solution: Create an object that has all the information to execute the query |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * EN: The Command interface declares a method for executing a command. |
| 13 | + */ |
| 14 | +interface Command { |
| 15 | + execute(): void; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * EN: We will use a receiver object to run the business logic |
| 20 | + */ |
| 21 | +class PrintRandomFactCommand implements Command { |
| 22 | + constructor(protected randomFactDomainServiceReceiver: RandomFactDomainServiceReceiver) { |
| 23 | + } |
| 24 | + |
| 25 | + public async execute(): Promise<void> { |
| 26 | + const fact = await this.randomFactDomainServiceReceiver.getRandomFact(); |
| 27 | + console.info(fact); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * EN: The Receiver class contains all the business logic to retrieve the |
| 33 | + * information |
| 34 | + */ |
| 35 | +class RandomFactDomainServiceReceiver { |
| 36 | + public getRandomFact(): Promise<string> { |
| 37 | + return new Promise((resolve, reject) => { |
| 38 | + https.get('https://uselessfacts.jsph.pl/api/v2/facts/random', (res) => { |
| 39 | + res.on('data', (d) => { |
| 40 | + const data = JSON.parse(d); |
| 41 | + const fact = data.text; |
| 42 | + resolve(fact); |
| 43 | + }); |
| 44 | + }).on('error', (error) => { |
| 45 | + reject(error); |
| 46 | + }); |
| 47 | + }); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * EN: The Invoker will execute any command every X seconds. |
| 53 | + */ |
| 54 | +class CommandInvoker { |
| 55 | + constructor(protected command: Command, protected seconds: number = 5) { |
| 56 | + } |
| 57 | + |
| 58 | + start(): void { |
| 59 | + setInterval(() => { |
| 60 | + this.command.execute(); |
| 61 | + }, this.seconds * 1000); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +/** |
| 66 | + * EN: The client code invokes the command |
| 67 | + */ |
| 68 | +const randomFactDomainServiceReceiver = new RandomFactDomainServiceReceiver(); |
| 69 | +const command = new PrintRandomFactCommand(randomFactDomainServiceReceiver); |
| 70 | +const commandInvoker = new CommandInvoker(command, 3); |
| 71 | + |
| 72 | +commandInvoker.start(); |
0 commit comments