Skip to content

Commit

Permalink
[DEV-2007][DEV-2008] Implement create list active campaign lambda, Im…
Browse files Browse the repository at this point in the history
…plement delete list from active campaign (#1250)

* Add delete and update contact lambdas + test

* Update deleteContact.test.ts

Co-authored-by: marcobottaro <[email protected]>

* Update updateContact.test.ts

Co-authored-by: marcobottaro <[email protected]>

* Update deleteContact.ts

Co-authored-by: marcobottaro <[email protected]>

* changeset

* Add handlers for create list and delete list on Active Campaign

* Fix delete list

* Skiiip

---------

Co-authored-by: t <[email protected]>
Co-authored-by: marcobottaro <[email protected]>
  • Loading branch information
3 people authored Nov 20, 2024
1 parent 1342788 commit 3197206
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/many-pens-grab.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"active-campaign-client": minor
---

Add handlers for create list and delete list on Active Campaign
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { handler } from '../../handlers/createList';
import { SQSEvent } from 'aws-lambda';

describe.skip('createList handler', () => {
it('should create a list successfully', async () => {
const event: SQSEvent = {
Records: [
{
messageId: '1',
receiptHandle: '1',
body: JSON.stringify({
title: `Test Webinar ${new Date().getTime()}`,
slug: `test-webinar-${new Date().getTime()}`,
description: 'Test Description',
subscribeCtaLabel: 'Subscribe to webinar',
isVisibleInList: true,
imagePath: '/path/to/image.jpg',
}),
attributes: {
ApproximateReceiveCount: '1',
SentTimestamp: '1',
SenderId: '1',
ApproximateFirstReceiveTimestamp: '1',
},
messageAttributes: {},
md5OfBody: '1',
eventSource: 'aws:sqs',
eventSourceARN: 'arn:aws:sqs:region:account-id:queue-name',
awsRegion: 'region',
},
],
};

const response = await handler(event);
expect(response.statusCode).toBe(200);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { handler } from '../../handlers/deleteList';
import { SQSEvent } from 'aws-lambda';

describe.skip('deleteList handler', () => {
it('should delete a list successfully', async () => {
const event: SQSEvent = {
Records: [
{
messageId: '1',
receiptHandle: '1',
body: JSON.stringify({
slug: 'test-webinar-1732097293540',
}),
attributes: {
ApproximateReceiveCount: '1',
SentTimestamp: '1',
SenderId: '1',
ApproximateFirstReceiveTimestamp: '1',
},
messageAttributes: {},
md5OfBody: '1',
eventSource: 'aws:sqs',
eventSourceARN: 'arn:aws:sqs:region:account-id:queue-name',
awsRegion: 'region',
},
],
};
const response = await handler(event);
expect(response.statusCode).toBe(200);
});
});
23 changes: 23 additions & 0 deletions packages/active-campaign-client/src/activeCampaignClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios from 'axios';
import * as dotenv from 'dotenv';
import { ContactPayload } from './types/contactPayload';
import { ListPayload } from './types/listPayload';

dotenv.config({ path: '.env' });

Expand Down Expand Up @@ -51,6 +52,28 @@ export class ActiveCampaignClient {
});
return response.data?.contacts?.[0]?.id;
}

async createList(data: ListPayload) {
const response = await axios.post(`${this.baseUrl}/api/3/lists`, data, {
headers: this.getHeaders(),
});
return response.data;
}

async getListIdByName(name: string) {
const response = await axios.get(`${this.baseUrl}/api/3/lists`, {
headers: this.getHeaders(),
params: { 'filters[name][eq]': name },
});
return response.data?.lists[0]?.id;
}

async deleteList(id: number) {
const response = await axios.delete(`${this.baseUrl}/api/3/lists/${id}`, {
headers: this.getHeaders(),
});
return response.data;
}
}

export const acClient = new ActiveCampaignClient(
Expand Down
37 changes: 37 additions & 0 deletions packages/active-campaign-client/src/handlers/createList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda';
import { acClient } from '../activeCampaignClient';
import { Webinar } from 'nextjs-website/src/lib/types/webinar';
import { ListPayload } from '../types/listPayload';

export async function handler(event: {
readonly Records: SQSEvent['Records'];
}): Promise<APIGatewayProxyResult> {
try {
const firstMessage = event.Records[0] ?? { body: '{}' };
const webinarData: Webinar = JSON.parse(firstMessage.body);

const acPayload: ListPayload = {
list: {
name: webinarData.slug,
stringid: webinarData.title, // Using slug as the stringid
sender_url: process.env.SENDER_URL || '',
sender_reminder: webinarData.subscribeCtaLabel || '',
subscription_notify: '',
unsubscription_notify: '',
},
};

const response = await acClient.createList(acPayload);

return {
statusCode: 200,
body: JSON.stringify(response),
};
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal server error' }),
};
}
}
42 changes: 42 additions & 0 deletions packages/active-campaign-client/src/handlers/deleteList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda';
import { acClient } from '../activeCampaignClient';

export async function handler(event: {
readonly Records: SQSEvent['Records'];
}): Promise<APIGatewayProxyResult> {
try {
const firstMessage = event.Records[0] ?? { body: '{}' };
const { slug } = JSON.parse(firstMessage.body);

if (!slug) {
return {
statusCode: 400,
body: JSON.stringify({ message: 'Webinar slug is required' }),
};
}

// Get list ID using the slug (name)
const listId = await acClient.getListIdByName(slug);

if (!listId) {
return {
statusCode: 404,
body: JSON.stringify({ message: 'List not found' }),
};
}

// Delete the list
await acClient.deleteList(Number(listId));

return {
statusCode: 200,
body: JSON.stringify({ message: 'List deleted successfully' }),
};
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal server error' }),
};
}
}

0 comments on commit 3197206

Please sign in to comment.