From 4984a2a4f22763d38182c358c641af86b5eff468 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Dec 2024 15:48:26 +0100 Subject: [PATCH 01/12] sync user wip --- .../fetchSubscribedWebinarsFromDynamo.ts | 30 ++++++ .../src/helpers/getUserFromCognito.ts | 8 +- .../src/helpers/resyncUser.ts | 96 +++++++++++++++++++ 3 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts create mode 100644 packages/active-campaign-client/src/helpers/resyncUser.ts diff --git a/packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts b/packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts new file mode 100644 index 0000000000..7f59d6d1bc --- /dev/null +++ b/packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts @@ -0,0 +1,30 @@ +import { DynamoDBClient, QueryCommand } from '@aws-sdk/client-dynamodb'; +import { APIGatewayProxyResult } from 'aws-lambda'; + +export async function fetchSubscribedWebinarsFromDynamo( + username: string +): Promise { + try { + const dynamoClient = new DynamoDBClient({ region: process.env.AWS_REGION }); + const command = new QueryCommand({ + TableName: process.env.DYNAMO_WEBINARS_TABLE_NAME, + KeyConditionExpression: 'username = :username', + ExpressionAttributeValues: { + ':username': { S: username }, + }, + }); + + const response = await dynamoClient.send(command); + console.log('getWebinarSubscriptions', response); + return { + statusCode: 200, + body: JSON.stringify(response.Items), + }; + } catch (error) { + console.error('Error querying items by username:', error); + return { + statusCode: 500, + body: JSON.stringify({ message: 'Internal server error' }), + }; + } +} diff --git a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts index 41d02e7c7b..325b4d2efd 100644 --- a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts +++ b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts @@ -4,9 +4,15 @@ import { QueueEvent } from '../types/queueEvent'; import { listUsersCommandOutputToUser } from './listUsersCommandOutputToUser'; export async function getUserFromCognito(queueEvent: QueueEvent) { + return await getUserFromCognitoByUsername( + queueEvent.detail.additionalEventData.sub + ); +} + +export async function getUserFromCognitoByUsername(username: string) { const command = new ListUsersCommand({ UserPoolId: process.env.COGNITO_USER_POOL_ID, - Filter: `username = "${queueEvent.detail.additionalEventData.sub}"`, + Filter: `username = "${username}"`, }); const listUsersCommandOutput = await cognitoClient.send(command); const user = listUsersCommandOutputToUser(listUsersCommandOutput); diff --git a/packages/active-campaign-client/src/helpers/resyncUser.ts b/packages/active-campaign-client/src/helpers/resyncUser.ts new file mode 100644 index 0000000000..59bc5576d7 --- /dev/null +++ b/packages/active-campaign-client/src/helpers/resyncUser.ts @@ -0,0 +1,96 @@ +import { deleteContact } from './deleteContact'; +import { getUserFromCognitoByUsername } from './getUserFromCognito'; +import { fetchSubscribedWebinarsFromDynamo } from './fetchSubscribedWebinarsFromDynamo'; +import { addContact } from './addContact'; +import { User } from '../types/user'; +import { APIGatewayProxyResult } from 'aws-lambda'; + +export async function resyncUser( + cognitoId: string +): Promise { + /* + La lambda cancella l’utente e, se esiste ancora su Cognito, lo ricrea e lo associa ai webinar corrispondenti (liste su AC). + + Capire se esiste già uno script python (fatto da Christian) che fa la stessa cosa. + + */ + // Step 1: Delete user on active campaign + const deletionResult = await deleteContact(cognitoId); + if (deletionResult.statusCode != 200 && deletionResult.statusCode != 404) { + console.log('Error deleting contact', deletionResult); + return deletionResult; + } + + // Step 2: Check if user exists on Cognito + // eslint-disable-next-line functional/no-let + let user: User | null = null; + + try { + user = await getUserFromCognitoByUsername(cognitoId); + } catch (e) { + // User not found -> user stays null + } + + // If the user is not present the sync is done + if (!user) { + console.log(`User: ${cognitoId} not present on Cognito, sync done.`); + return { + statusCode: 200, + body: JSON.stringify({ + message: 'User not present on Cognito, sync done.', + }), + }; + } + + // Fetch all the webinars the user is subscribed to + const webinars = await fetchSubscribedWebinarsFromDynamo(cognitoId); + /* + { + "statusCode": 200, + "body": "[{\"createdAt\":{\"S\":\"2024-12-05T14:18:28.601Z\"},\"username\":{\"S\":\"56beb230-f081-70a4-f0e1-4b09723b4771\"},\"webinarId\":{\"S\":\"DevTalks-pagoPA-IBAN\"}},{\"createdAt\":{\"S\":\"2024-12-05T14:18:22.429Z\"},\"username\":{\"S\":\"56beb230-f081-70a4-f0e1-4b09723b4771\"},\"webinarId\":{\"S\":\"PagoPALAB-sanita\"}}]" +} + */ + const webinarIds = JSON.parse(webinars.body) + .map( + (webinar: { readonly webinarId: { readonly S: string } }) => + webinar?.webinarId?.S + ) + .filter(Boolean); + + console.log('Webinar IDs:', webinarIds); + + // Step 3: Create user on active campaign + addContact(user); + + // Step 4: Add user to the webinars lists + // TBD + + return { + statusCode: 200, + body: JSON.stringify({ message: 'User resynced' }), + }; +} + +/* + +{ + "Records": [ + { + "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", + "receiptHandle": "MessageReceiptHandle", + "body": "{\"detail\":{\"eventName\":\"ResyncUser\", \"additionalEventData\" : {\"sub\": \"56beb230-f081-70a4-f0e1-4b09723b4771\"}}}", + "attributes": { + "ApproximateReceiveCount": "1", + "SentTimestamp": "1523232000000", + "SenderId": "123456789012", + "ApproximateFirstReceiveTimestamp": "1523232000001" + }, + "messageAttributes": {}, + "md5OfBody": "{{{md5_of_body}}}", + "eventSource": "aws:sqs", + "eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue", + "awsRegion": "us-east-1" + } + ] +} + */ From 33802ef0ac469e013e91eb2768331f156030bf34 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Dec 2024 16:08:13 +0100 Subject: [PATCH 02/12] sync user --- .../src/helpers/resyncUser.ts | 48 +++++++------------ packages/active-campaign-client/src/index.ts | 10 ++++ 2 files changed, 26 insertions(+), 32 deletions(-) diff --git a/packages/active-campaign-client/src/helpers/resyncUser.ts b/packages/active-campaign-client/src/helpers/resyncUser.ts index 59bc5576d7..13cf815b7b 100644 --- a/packages/active-campaign-client/src/helpers/resyncUser.ts +++ b/packages/active-campaign-client/src/helpers/resyncUser.ts @@ -4,6 +4,7 @@ import { fetchSubscribedWebinarsFromDynamo } from './fetchSubscribedWebinarsFrom import { addContact } from './addContact'; import { User } from '../types/user'; import { APIGatewayProxyResult } from 'aws-lambda'; +import { addContactToList } from './manageListSubscription'; export async function resyncUser( cognitoId: string @@ -44,12 +45,7 @@ export async function resyncUser( // Fetch all the webinars the user is subscribed to const webinars = await fetchSubscribedWebinarsFromDynamo(cognitoId); - /* - { - "statusCode": 200, - "body": "[{\"createdAt\":{\"S\":\"2024-12-05T14:18:28.601Z\"},\"username\":{\"S\":\"56beb230-f081-70a4-f0e1-4b09723b4771\"},\"webinarId\":{\"S\":\"DevTalks-pagoPA-IBAN\"}},{\"createdAt\":{\"S\":\"2024-12-05T14:18:22.429Z\"},\"username\":{\"S\":\"56beb230-f081-70a4-f0e1-4b09723b4771\"},\"webinarId\":{\"S\":\"PagoPALAB-sanita\"}}]" -} - */ + const webinarIds = JSON.parse(webinars.body) .map( (webinar: { readonly webinarId: { readonly S: string } }) => @@ -60,37 +56,25 @@ export async function resyncUser( console.log('Webinar IDs:', webinarIds); // Step 3: Create user on active campaign - addContact(user); + const res = await addContact(user); + console.log('Add contact result:', res); // Step 4: Add user to the webinars lists - // TBD + // eslint-disable-next-line functional/no-loop-statements + for (const webinarId of webinarIds) { + console.log('Adding contact to list:', webinarId); + try { + const result = await addContactToList(cognitoId, webinarId); + console.log('Add contact to list result:', result); + // wait 1 sec to avoid rate limiting + await new Promise((resolve) => setTimeout(resolve, 1000)); + } catch (e) { + console.error('Error adding contact to list', e); + } + } return { statusCode: 200, body: JSON.stringify({ message: 'User resynced' }), }; } - -/* - -{ - "Records": [ - { - "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78", - "receiptHandle": "MessageReceiptHandle", - "body": "{\"detail\":{\"eventName\":\"ResyncUser\", \"additionalEventData\" : {\"sub\": \"56beb230-f081-70a4-f0e1-4b09723b4771\"}}}", - "attributes": { - "ApproximateReceiveCount": "1", - "SentTimestamp": "1523232000000", - "SenderId": "123456789012", - "ApproximateFirstReceiveTimestamp": "1523232000001" - }, - "messageAttributes": {}, - "md5OfBody": "{{{md5_of_body}}}", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue", - "awsRegion": "us-east-1" - } - ] -} - */ diff --git a/packages/active-campaign-client/src/index.ts b/packages/active-campaign-client/src/index.ts index 0d1edb3b65..f939993611 100644 --- a/packages/active-campaign-client/src/index.ts +++ b/packages/active-campaign-client/src/index.ts @@ -1,8 +1,18 @@ import { SQSEvent } from 'aws-lambda'; import { sqsQueueHandler } from './handlers/sqsQueueHandler'; +import { resyncUser } from './helpers/resyncUser'; export async function sqsQueue(event: { readonly Records: SQSEvent['Records']; }) { return await sqsQueueHandler(event); } + +export async function handler(event: { + readonly Records: SQSEvent['Records']; +}) { + //return await sqsQueueHandler(event); + const cognitoId = event.Records[0].body; + console.log('cognitoId: ', cognitoId); + return await resyncUser(cognitoId); +} From c432ad43c9611ea4d7d45a43a4a3021518e87605 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Dec 2024 16:11:56 +0100 Subject: [PATCH 03/12] changeset --- .changeset/cuddly-cats-retire.md | 5 +++++ packages/active-campaign-client/src/helpers/resyncUser.ts | 6 ------ 2 files changed, 5 insertions(+), 6 deletions(-) create mode 100644 .changeset/cuddly-cats-retire.md diff --git a/.changeset/cuddly-cats-retire.md b/.changeset/cuddly-cats-retire.md new file mode 100644 index 0000000000..ee0ece7cd1 --- /dev/null +++ b/.changeset/cuddly-cats-retire.md @@ -0,0 +1,5 @@ +--- +"active-campaign-client": minor +--- + +Resync user diff --git a/packages/active-campaign-client/src/helpers/resyncUser.ts b/packages/active-campaign-client/src/helpers/resyncUser.ts index 13cf815b7b..ae916f7004 100644 --- a/packages/active-campaign-client/src/helpers/resyncUser.ts +++ b/packages/active-campaign-client/src/helpers/resyncUser.ts @@ -9,12 +9,6 @@ import { addContactToList } from './manageListSubscription'; export async function resyncUser( cognitoId: string ): Promise { - /* - La lambda cancella l’utente e, se esiste ancora su Cognito, lo ricrea e lo associa ai webinar corrispondenti (liste su AC). - - Capire se esiste già uno script python (fatto da Christian) che fa la stessa cosa. - - */ // Step 1: Delete user on active campaign const deletionResult = await deleteContact(cognitoId); if (deletionResult.statusCode != 200 && deletionResult.statusCode != 404) { From 5865dc1ebddea177125d758ab5e5cdbbc3897147 Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Fri, 6 Dec 2024 10:38:52 +0100 Subject: [PATCH 04/12] Update .changeset/cuddly-cats-retire.md Co-authored-by: Marco Ponchia --- .changeset/cuddly-cats-retire.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/cuddly-cats-retire.md b/.changeset/cuddly-cats-retire.md index ee0ece7cd1..ef17a074d8 100644 --- a/.changeset/cuddly-cats-retire.md +++ b/.changeset/cuddly-cats-retire.md @@ -2,4 +2,4 @@ "active-campaign-client": minor --- -Resync user +Add resync user handler From b1b81805cb6afd5cfb315975cfc09b40bc7c52db Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Fri, 6 Dec 2024 10:39:47 +0100 Subject: [PATCH 05/12] Update packages/active-campaign-client/src/index.ts Co-authored-by: Marco Ponchia --- packages/active-campaign-client/src/index.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/active-campaign-client/src/index.ts b/packages/active-campaign-client/src/index.ts index f939993611..9c6f30827c 100644 --- a/packages/active-campaign-client/src/index.ts +++ b/packages/active-campaign-client/src/index.ts @@ -11,8 +11,5 @@ export async function sqsQueue(event: { export async function handler(event: { readonly Records: SQSEvent['Records']; }) { - //return await sqsQueueHandler(event); - const cognitoId = event.Records[0].body; - console.log('cognitoId: ', cognitoId); - return await resyncUser(cognitoId); + return await resyncUserHandler(event); } From 6ec2fc2bbd87cea73442ec080c2220f35d5d54bb Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Fri, 6 Dec 2024 10:39:55 +0100 Subject: [PATCH 06/12] Update packages/active-campaign-client/src/index.ts Co-authored-by: Marco Ponchia --- packages/active-campaign-client/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/active-campaign-client/src/index.ts b/packages/active-campaign-client/src/index.ts index 9c6f30827c..f35d8db501 100644 --- a/packages/active-campaign-client/src/index.ts +++ b/packages/active-campaign-client/src/index.ts @@ -1,6 +1,6 @@ import { SQSEvent } from 'aws-lambda'; import { sqsQueueHandler } from './handlers/sqsQueueHandler'; -import { resyncUser } from './helpers/resyncUser'; +import { resyncUserHandler } from './helpers/resyncUser'; export async function sqsQueue(event: { readonly Records: SQSEvent['Records']; From b102553c95480da29f2636bb083fd970871bf1ea Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Fri, 6 Dec 2024 10:40:06 +0100 Subject: [PATCH 07/12] Update packages/active-campaign-client/src/helpers/resyncUser.ts Co-authored-by: Marco Ponchia --- .../src/helpers/resyncUser.ts | 122 +++++++++--------- 1 file changed, 64 insertions(+), 58 deletions(-) diff --git a/packages/active-campaign-client/src/helpers/resyncUser.ts b/packages/active-campaign-client/src/helpers/resyncUser.ts index ae916f7004..32bcd19a84 100644 --- a/packages/active-campaign-client/src/helpers/resyncUser.ts +++ b/packages/active-campaign-client/src/helpers/resyncUser.ts @@ -2,73 +2,79 @@ import { deleteContact } from './deleteContact'; import { getUserFromCognitoByUsername } from './getUserFromCognito'; import { fetchSubscribedWebinarsFromDynamo } from './fetchSubscribedWebinarsFromDynamo'; import { addContact } from './addContact'; -import { User } from '../types/user'; -import { APIGatewayProxyResult } from 'aws-lambda'; +import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda'; import { addContactToList } from './manageListSubscription'; +import { queueEventParser } from './queueEventParser'; -export async function resyncUser( - cognitoId: string -): Promise { - // Step 1: Delete user on active campaign - const deletionResult = await deleteContact(cognitoId); - if (deletionResult.statusCode != 200 && deletionResult.statusCode != 404) { - console.log('Error deleting contact', deletionResult); - return deletionResult; - } - - // Step 2: Check if user exists on Cognito - // eslint-disable-next-line functional/no-let - let user: User | null = null; - +export async function resyncUserHandler(event: { + readonly Records: SQSEvent['Records']; +}): Promise { try { - user = await getUserFromCognitoByUsername(cognitoId); - } catch (e) { - // User not found -> user stays null - } + const queueEvent = queueEventParser(event); + const cognitoId = queueEvent.detail.additionalEventData.sub; + const deletionResult = await deleteContact(cognitoId); + if (deletionResult.statusCode != 200 && deletionResult.statusCode != 404) { + // eslint-disable-next-line functional/no-throw-statements + throw new Error('Error adding contact'); + } - // If the user is not present the sync is done - if (!user) { - console.log(`User: ${cognitoId} not present on Cognito, sync done.`); - return { - statusCode: 200, - body: JSON.stringify({ - message: 'User not present on Cognito, sync done.', - }), - }; - } + const user = await getUserFromCognitoByUsername(cognitoId); - // Fetch all the webinars the user is subscribed to - const webinars = await fetchSubscribedWebinarsFromDynamo(cognitoId); + if (!user) { + console.log(`User: ${cognitoId} not present on Cognito, sync done.`); + return { + statusCode: 200, + body: JSON.stringify({ + message: 'User not present on Cognito, sync done.', + }), + }; + } - const webinarIds = JSON.parse(webinars.body) - .map( - (webinar: { readonly webinarId: { readonly S: string } }) => - webinar?.webinarId?.S - ) - .filter(Boolean); + const userWebinarsSubscriptions = await fetchSubscribedWebinarsFromDynamo( + cognitoId + ); - console.log('Webinar IDs:', webinarIds); + const webinarIds = JSON.parse(userWebinarsSubscriptions.body) + .map( + (webinar: { readonly webinarId: { readonly S: string } }) => + webinar?.webinarId?.S + ) + .filter(Boolean); - // Step 3: Create user on active campaign - const res = await addContact(user); - console.log('Add contact result:', res); + console.log('Webinar IDs:', webinarIds); // TODO: Remove after testing - // Step 4: Add user to the webinars lists - // eslint-disable-next-line functional/no-loop-statements - for (const webinarId of webinarIds) { - console.log('Adding contact to list:', webinarId); - try { - const result = await addContactToList(cognitoId, webinarId); - console.log('Add contact to list result:', result); - // wait 1 sec to avoid rate limiting - await new Promise((resolve) => setTimeout(resolve, 1000)); - } catch (e) { - console.error('Error adding contact to list', e); + const res = await addContact(user); + if (res.statusCode !== 200) { + // eslint-disable-next-line functional/no-throw-statements + throw new Error('Error adding contact'); } - } - return { - statusCode: 200, - body: JSON.stringify({ message: 'User resynced' }), - }; + await webinarIds.reduce( + async ( + prevPromise: Promise, + webinarId: string + ) => { + await prevPromise; + try { + const result = await addContactToList(cognitoId, webinarId); + console.log('Add contact to list result:', result, webinarId); // TODO: Remove after testing + await new Promise((resolve) => setTimeout(resolve, 1000)); // wait 1 sec to avoid rate limiting + } catch (e) { + console.error('Error adding contact to list', e); // TODO: Remove after testing + } + }, + Promise.resolve() + ); + + return { + statusCode: 200, + body: JSON.stringify({ message: 'User resynced' }), + }; + } catch (error) { + return { + statusCode: 500, + body: JSON.stringify({ message: error }), + }; + } } + From 3a7569d888870aa1090d2c29ff634d3308914730 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Dec 2024 10:43:50 +0100 Subject: [PATCH 08/12] pr comments --- .../resyncUserHandler.ts} | 13 ++++++------- .../src/helpers/getUserFromCognito.ts | 14 +++++++------- packages/active-campaign-client/src/index.ts | 4 ++-- 3 files changed, 15 insertions(+), 16 deletions(-) rename packages/active-campaign-client/src/{helpers/resyncUser.ts => handlers/resyncUserHandler.ts} (84%) diff --git a/packages/active-campaign-client/src/helpers/resyncUser.ts b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts similarity index 84% rename from packages/active-campaign-client/src/helpers/resyncUser.ts rename to packages/active-campaign-client/src/handlers/resyncUserHandler.ts index 32bcd19a84..a2496306a9 100644 --- a/packages/active-campaign-client/src/helpers/resyncUser.ts +++ b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts @@ -1,10 +1,10 @@ -import { deleteContact } from './deleteContact'; -import { getUserFromCognitoByUsername } from './getUserFromCognito'; -import { fetchSubscribedWebinarsFromDynamo } from './fetchSubscribedWebinarsFromDynamo'; -import { addContact } from './addContact'; +import { deleteContact } from '../helpers/deleteContact'; +import { getUserFromCognitoByUsername } from '../helpers/getUserFromCognito'; +import { fetchSubscribedWebinarsFromDynamo } from '../helpers/fetchSubscribedWebinarsFromDynamo'; +import { addContact } from '../helpers/addContact'; import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda'; -import { addContactToList } from './manageListSubscription'; -import { queueEventParser } from './queueEventParser'; +import { addContactToList } from '../helpers/manageListSubscription'; +import { queueEventParser } from '../helpers/queueEventParser'; export async function resyncUserHandler(event: { readonly Records: SQSEvent['Records']; @@ -77,4 +77,3 @@ export async function resyncUserHandler(event: { }; } } - diff --git a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts index 325b4d2efd..30bec5a410 100644 --- a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts +++ b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts @@ -4,9 +4,13 @@ import { QueueEvent } from '../types/queueEvent'; import { listUsersCommandOutputToUser } from './listUsersCommandOutputToUser'; export async function getUserFromCognito(queueEvent: QueueEvent) { - return await getUserFromCognitoByUsername( - queueEvent.detail.additionalEventData.sub - ); + const username = queueEvent.detail.additionalEventData.sub; + const user = await getUserFromCognitoByUsername(username); + if (!user) { + // eslint-disable-next-line functional/no-throw-statements + throw new Error('User not found'); + } + return user; } export async function getUserFromCognitoByUsername(username: string) { @@ -16,10 +20,6 @@ export async function getUserFromCognitoByUsername(username: string) { }); const listUsersCommandOutput = await cognitoClient.send(command); const user = listUsersCommandOutputToUser(listUsersCommandOutput); - if (!user) { - // eslint-disable-next-line functional/no-throw-statements - throw new Error('User not found'); - } console.log('User:', JSON.stringify(user, null, 2)); // TODO: Remove after testing return user; } diff --git a/packages/active-campaign-client/src/index.ts b/packages/active-campaign-client/src/index.ts index f35d8db501..cab74a8145 100644 --- a/packages/active-campaign-client/src/index.ts +++ b/packages/active-campaign-client/src/index.ts @@ -1,6 +1,6 @@ import { SQSEvent } from 'aws-lambda'; import { sqsQueueHandler } from './handlers/sqsQueueHandler'; -import { resyncUserHandler } from './helpers/resyncUser'; +import { resyncUserHandler } from './handlers/resyncUserHandler'; export async function sqsQueue(event: { readonly Records: SQSEvent['Records']; @@ -8,7 +8,7 @@ export async function sqsQueue(event: { return await sqsQueueHandler(event); } -export async function handler(event: { +export async function resyncQueue(event: { readonly Records: SQSEvent['Records']; }) { return await resyncUserHandler(event); From 2fc6b3d78062b59b3617d52bfea7da6dacc65bf3 Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Tue, 17 Dec 2024 20:20:47 +0100 Subject: [PATCH 09/12] Update packages/active-campaign-client/src/handlers/resyncUserHandler.ts Co-authored-by: marcobottaro <39835990+marcobottaro@users.noreply.github.com> --- .../active-campaign-client/src/handlers/resyncUserHandler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts index a2496306a9..2a15ed3804 100644 --- a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts +++ b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts @@ -13,7 +13,7 @@ export async function resyncUserHandler(event: { const queueEvent = queueEventParser(event); const cognitoId = queueEvent.detail.additionalEventData.sub; const deletionResult = await deleteContact(cognitoId); - if (deletionResult.statusCode != 200 && deletionResult.statusCode != 404) { + if (deletionResult.statusCode !== 200 && deletionResult.statusCode !== 404) { // eslint-disable-next-line functional/no-throw-statements throw new Error('Error adding contact'); } From dab5b50e4bbfd72a585f7bc7a133f9e5bd867b79 Mon Sep 17 00:00:00 2001 From: tommaso1 Date: Tue, 17 Dec 2024 20:20:53 +0100 Subject: [PATCH 10/12] Update packages/active-campaign-client/src/handlers/resyncUserHandler.ts Co-authored-by: marcobottaro <39835990+marcobottaro@users.noreply.github.com> --- .../active-campaign-client/src/handlers/resyncUserHandler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts index 2a15ed3804..9e2eb6d1e6 100644 --- a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts +++ b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts @@ -18,7 +18,7 @@ export async function resyncUserHandler(event: { throw new Error('Error adding contact'); } - const user = await getUserFromCognitoByUsername(cognitoId); + const user = await getCognitoUserById(cognitoId); if (!user) { console.log(`User: ${cognitoId} not present on Cognito, sync done.`); From d607a424d518bae14f43fd1d21e4bc7b8462b488 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 17 Dec 2024 20:29:37 +0100 Subject: [PATCH 11/12] pr changes --- .../src/handlers/resyncUserHandler.ts | 23 +++++++++++-------- .../src/helpers/getUserFromCognito.ts | 4 ++-- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts index 9e2eb6d1e6..cf59d7d046 100644 --- a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts +++ b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts @@ -1,5 +1,5 @@ import { deleteContact } from '../helpers/deleteContact'; -import { getUserFromCognitoByUsername } from '../helpers/getUserFromCognito'; +import { getUserFromCognitoUsername } from '../helpers/getUserFromCognito'; import { fetchSubscribedWebinarsFromDynamo } from '../helpers/fetchSubscribedWebinarsFromDynamo'; import { addContact } from '../helpers/addContact'; import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda'; @@ -11,17 +11,22 @@ export async function resyncUserHandler(event: { }): Promise { try { const queueEvent = queueEventParser(event); - const cognitoId = queueEvent.detail.additionalEventData.sub; - const deletionResult = await deleteContact(cognitoId); - if (deletionResult.statusCode !== 200 && deletionResult.statusCode !== 404) { + const cognitoUsername = queueEvent.detail.additionalEventData.sub; + const deletionResult = await deleteContact(cognitoUsername); + if ( + deletionResult.statusCode !== 200 && + deletionResult.statusCode !== 404 + ) { // eslint-disable-next-line functional/no-throw-statements throw new Error('Error adding contact'); } - const user = await getCognitoUserById(cognitoId); + const user = await getUserFromCognitoUsername(cognitoUsername); if (!user) { - console.log(`User: ${cognitoId} not present on Cognito, sync done.`); + console.log( + `User: ${cognitoUsername} not present on Cognito, sync done.` + ); return { statusCode: 200, body: JSON.stringify({ @@ -31,7 +36,7 @@ export async function resyncUserHandler(event: { } const userWebinarsSubscriptions = await fetchSubscribedWebinarsFromDynamo( - cognitoId + cognitoUsername ); const webinarIds = JSON.parse(userWebinarsSubscriptions.body) @@ -41,8 +46,6 @@ export async function resyncUserHandler(event: { ) .filter(Boolean); - console.log('Webinar IDs:', webinarIds); // TODO: Remove after testing - const res = await addContact(user); if (res.statusCode !== 200) { // eslint-disable-next-line functional/no-throw-statements @@ -56,7 +59,7 @@ export async function resyncUserHandler(event: { ) => { await prevPromise; try { - const result = await addContactToList(cognitoId, webinarId); + const result = await addContactToList(cognitoUsername, webinarId); console.log('Add contact to list result:', result, webinarId); // TODO: Remove after testing await new Promise((resolve) => setTimeout(resolve, 1000)); // wait 1 sec to avoid rate limiting } catch (e) { diff --git a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts index 30bec5a410..c3630ad897 100644 --- a/packages/active-campaign-client/src/helpers/getUserFromCognito.ts +++ b/packages/active-campaign-client/src/helpers/getUserFromCognito.ts @@ -5,7 +5,7 @@ import { listUsersCommandOutputToUser } from './listUsersCommandOutputToUser'; export async function getUserFromCognito(queueEvent: QueueEvent) { const username = queueEvent.detail.additionalEventData.sub; - const user = await getUserFromCognitoByUsername(username); + const user = await getUserFromCognitoUsername(username); if (!user) { // eslint-disable-next-line functional/no-throw-statements throw new Error('User not found'); @@ -13,7 +13,7 @@ export async function getUserFromCognito(queueEvent: QueueEvent) { return user; } -export async function getUserFromCognitoByUsername(username: string) { +export async function getUserFromCognitoUsername(username: string) { const command = new ListUsersCommand({ UserPoolId: process.env.COGNITO_USER_POOL_ID, Filter: `username = "${username}"`, From 599d42cbb2861bc0e525b0fd96697f17e7ac6f87 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 17 Dec 2024 20:32:25 +0100 Subject: [PATCH 12/12] pr changes --- .../active-campaign-client/src/handlers/resyncUserHandler.ts | 4 ++-- ...bscribedWebinarsFromDynamo.ts => getSubscribedWebinars.ts} | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename packages/active-campaign-client/src/helpers/{fetchSubscribedWebinarsFromDynamo.ts => getSubscribedWebinars.ts} (94%) diff --git a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts index cf59d7d046..a9edc97d5d 100644 --- a/packages/active-campaign-client/src/handlers/resyncUserHandler.ts +++ b/packages/active-campaign-client/src/handlers/resyncUserHandler.ts @@ -1,6 +1,6 @@ import { deleteContact } from '../helpers/deleteContact'; import { getUserFromCognitoUsername } from '../helpers/getUserFromCognito'; -import { fetchSubscribedWebinarsFromDynamo } from '../helpers/fetchSubscribedWebinarsFromDynamo'; +import { getSubscribedWebinars } from '../helpers/getSubscribedWebinars'; import { addContact } from '../helpers/addContact'; import { APIGatewayProxyResult, SQSEvent } from 'aws-lambda'; import { addContactToList } from '../helpers/manageListSubscription'; @@ -35,7 +35,7 @@ export async function resyncUserHandler(event: { }; } - const userWebinarsSubscriptions = await fetchSubscribedWebinarsFromDynamo( + const userWebinarsSubscriptions = await getSubscribedWebinars( cognitoUsername ); diff --git a/packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts b/packages/active-campaign-client/src/helpers/getSubscribedWebinars.ts similarity index 94% rename from packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts rename to packages/active-campaign-client/src/helpers/getSubscribedWebinars.ts index 7f59d6d1bc..1d6d757381 100644 --- a/packages/active-campaign-client/src/helpers/fetchSubscribedWebinarsFromDynamo.ts +++ b/packages/active-campaign-client/src/helpers/getSubscribedWebinars.ts @@ -1,7 +1,7 @@ import { DynamoDBClient, QueryCommand } from '@aws-sdk/client-dynamodb'; import { APIGatewayProxyResult } from 'aws-lambda'; -export async function fetchSubscribedWebinarsFromDynamo( +export async function getSubscribedWebinars( username: string ): Promise { try {