Skip to content

Instantly share code, notes, and snippets.

@s1moe2
Last active November 9, 2020 09:43
Show Gist options
  • Save s1moe2/a38d33abf2f12fc5a693ef390ebf45f0 to your computer and use it in GitHub Desktop.
Save s1moe2/a38d33abf2f12fc5a693ef390ebf45f0 to your computer and use it in GitHub Desktop.
JavaScript (sort of) Abstract Class
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