Created
July 18, 2019 10:16
-
-
Save geakstr/097cc9df0a58be5ea3fab3e92b2ffd98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EventEmitter } from "events"; | |
const eventEmitter = new EventEmitter(); | |
const stubMailApi = (address: string, message: string) => { | |
return new Promise<{ address: string; message: string; status: string }>( | |
resolve => { | |
resolve({ address, message, status: "ok" }); | |
} | |
); | |
}; | |
const stubPushNotificationsApi = (message: string) => { | |
return new Promise<{ message: string; status: string }>(resolve => { | |
resolve({ message, status: "ok" }); | |
}); | |
}; | |
class EmailService { | |
send(address: string, message: string) { | |
stubMailApi(address, message).then(response => { | |
eventEmitter.emit("email-sent", response); | |
}); | |
} | |
} | |
class PushNotificationsService { | |
send(message: string) { | |
stubPushNotificationsApi(message).then(response => { | |
eventEmitter.emit("push-notification-sent", response); | |
}); | |
} | |
} | |
class AuthService { | |
private loggedIn: string | null = null; | |
login(emailAddress: string) { | |
this.logout(); | |
this.loggedIn = emailAddress; | |
eventEmitter.emit("auth-logged-in", emailAddress); | |
} | |
logout() { | |
if (this.loggedIn) { | |
const emailAddress = this.loggedIn; | |
this.loggedIn = null; | |
eventEmitter.emit("auth-logged-out", emailAddress); | |
} | |
} | |
} | |
class LoggerService { | |
constructor() { | |
eventEmitter.on("logger-log", this.log); | |
} | |
log(data: any) { | |
console.log(data); | |
} | |
} | |
const authService = new AuthService(); | |
const emailService = new EmailService(); | |
const pushNotificationsService = new PushNotificationsService(); | |
const loggerService = new LoggerService(); | |
eventEmitter.on("auth-logged-in", emailAddress => { | |
loggerService.log(`User ${emailAddress} was logged in`); | |
emailService.send(emailAddress, "You were logged in"); | |
}); | |
eventEmitter.on("auth-logged-out", emailAddress => { | |
loggerService.log(`User ${emailAddress} was logged out`); | |
emailService.send(emailAddress, "You were logged out"); | |
}); | |
eventEmitter.on("email-sent", response => { | |
loggerService.log(`Email ${JSON.stringify(response)} was sent`); | |
pushNotificationsService.send(response.message); | |
}); | |
eventEmitter.on("push-notification-sent", response => { | |
loggerService.log(`Push Notification ${JSON.stringify(response)} was sent`); | |
}); | |
authService.login("[email protected]"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment