Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement