Skip to content

Instantly share code, notes, and snippets.

@michelepatrassi
Created September 6, 2019 09:37
Show Gist options
  • Save michelepatrassi/97f179ead35e1f1e62662c2af44f4a8a to your computer and use it in GitHub Desktop.
Save michelepatrassi/97f179ead35e1f1e62662c2af44f4a8a to your computer and use it in GitHub Desktop.
Cloud function add update with config variables
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import MailchimpApi = require('mailchimp-api-v3');
import md5 = require('crypto-js/md5');
const CRON_SCHEDULE = '* * * * *';
export const cronMailchimp = functions.region('europe-west1').pubsub
.schedule(CRON_SCHEDULE).onRun(async context => {
const { audience, apikey } = functions.config().mailchimp;
if (!audience || !apikey) {
throw new Error(`Missing mailchimp config! Current config is ${JSON.stringify(functions.config(), null, 2)}`);
}
const mailchimpApi = new MailchimpApi(apikey);
const userRefs = await admin.firestore().collection('users').listDocuments();
for (const userRef of userRefs) {
const userDoc = await userRef.get();
const user = userDoc.data();
console.log(`mailchimp.ts - handling user ${userRef.id} with email ${user.email}`);
try {
await patchContact(mailchimpApi, audience, user);
console.log(`mailchimp.ts - user updated!`, );
} catch (e) {
console.log(`mailchimp.ts - catched updated error (probably contact does not exist)`, e);
try {
await createContact(mailchimpApi, AUDIENCE_ID, user);
console.log(`mailchimp.ts - user created!`, );
} catch (e) {
console.error(`mailchimp.ts - failed to create contact!`, e);
}
}
}
})
const createContact = async (mailchimpApi, audienceId, user) => {
const body = {
email_address: user.email,
status: "subscribed",
merge_fields: {
FNAME: user.name,
LNAME: user.surname
}
};
return mailchimpApi.post(`/lists/${audienceId}/members/`, body);
}
const patchContact = async (mailchimpApi, audienceId, user) => {
const body = {
merge_fields: {
FNAME: user.name,
LNAME: user.surname
}
};
const memberId = md5(user.email.toLowerCase());
return mailchimpApi.patch(`/lists/${audienceId}/members/${memberId}`, body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment