Skip to content

Commit

Permalink
Update packages/active-campaign-client/src/helpers/resyncUser.ts
Browse files Browse the repository at this point in the history
Co-authored-by: Marco Ponchia <[email protected]>
  • Loading branch information
tommaso1 and MarcoPonchia authored Dec 6, 2024
1 parent 6ec2fc2 commit b102553
Showing 1 changed file with 64 additions and 58 deletions.
122 changes: 64 additions & 58 deletions packages/active-campaign-client/src/helpers/resyncUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<APIGatewayProxyResult> {
// 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<APIGatewayProxyResult> {
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<APIGatewayProxyResult>,
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 }),
};
}
}

0 comments on commit b102553

Please sign in to comment.