Last active
November 9, 2020 09:43
-
-
Save s1moe2/a38d33abf2f12fc5a693ef390ebf45f0 to your computer and use it in GitHub Desktop.
JavaScript (sort of) Abstract Class
This file contains 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
class EmailProvider { | |
#config = {} | |
constructor(config) { | |
this.#config = config | |
if (new.target === EmailProvider) { | |
throw new Error('Cannot construct EmailProvider instances directly') | |
} | |
if (this.send === EmailProvider.prototype.send) { | |
throw new Error(`EmailProvider[${new.target.name}]: missing send implementation`) | |
} | |
} | |
send() { | |
throw new Error('EmailProvider.send should not be called directly') | |
} | |
} | |
class Sendgrid extends EmailProvider { | |
send(message) { | |
console.log('swoosh: ', message) | |
} | |
} | |
class Mailjet extends EmailProvider {} | |
const providers = { | |
SENDGRID: 'sendgrid', | |
MAILJET: 'mailjet', | |
} | |
const MailerFactory = (provider, config = {}) => { | |
switch (provider) { | |
case providers.SENDGRID: return new Sendgrid(config) | |
case providers.MAILJET: return new Mailjet(config) | |
default: throw new Error('Email provider not implemented') | |
} | |
} | |
MailerFactory(providers.SENDGRID) // ok | |
MailerFactory(providers.MAILJET) // throws | |
new EmailProvider() // throws |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment