Last active
June 17, 2020 20:24
-
-
Save wswoodruff/a890fe7571b25c1b8ca9b0eec6c1d054 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
const Hoek = require('@hapi/hoek'); | |
const Wreck = require('@hapi/wreck'); | |
const Schmervice = require('schmervice'); | |
module.exports = class MailchimpService extends Schmervice.Service { | |
constructor(server, options) { | |
super(server, options); | |
const { | |
apiKey, | |
baseUrl, | |
listId | |
} = options.mailchimp || {}; | |
Hoek.assert(apiKey && baseUrl && listId, 'Must specify options.mailchimp.apiKey, options.mailchimp.baseUrl, and options.mailchimp.listId'); | |
this.apiKey = apiKey; | |
this.baseUrl = baseUrl; // Ex: 'https://us20.api.mailchimp.com/3.0' | |
this.listId = listId; | |
} | |
async subscribe(newUsers) { | |
// Here's where it's really nice having schmervices with nicely-cut concerns to compose together! | |
const { logService: { log } } = this.server.services(); | |
// See the Mailchimp docs to better understand what's happening here: https://mailchimp.com/developer/reference/lists/#post_/lists/-list_id- | |
const rawResult = await Wreck.request('POST', `${this.baseUrl}/lists/${this.listId}`, { | |
headers: { | |
Authorization: `apikey ${this.apiKey}` | |
}, | |
payload: { | |
members: [].concat(newUsers).map(({ email }) => ({ | |
email_address: email, | |
status: 'subscribed' | |
})), | |
update_existing: true | |
} | |
}); | |
const readResult = await Wreck.read(rawResult); | |
const res = JSON.parse(readResult.toString('utf8')); | |
const updates = { | |
new: res.new_members.map(({ email_address }) => email_address), | |
updated: res.updated_members.map(({ email_address }) => email_address) | |
}; | |
log(['mailchimp', updates.new.length ? 'signup' : 'update'], updates); | |
return updates; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment