Skip to content

Commit

Permalink
update cdk contact postl route
Browse files Browse the repository at this point in the history
  • Loading branch information
aasmal97 committed Jul 25, 2024
1 parent 8399cc3 commit 3d1497b
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 70 deletions.
90 changes: 72 additions & 18 deletions app/lib/restAPI/resources/contact/contactPost/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,85 @@
import { APIGatewayEvent } from "aws-lambda";
import { sendEmail } from "./sendEmail";
import { corsPostHeaders} from "../../utils/corsLambda";
export type ContactMeInputProps = {
sender: string;
subject: string;
message: string;
type?: "phone" | "email";
};
import { corsPostHeaders } from "../../utils/corsLambda";
import { z } from "zod";
import parsePhoneNumber, { AsYouType } from "libphonenumber-js";
export function isOnlyCountryCode(number: string) {
const currNumber = new AsYouType();
currNumber.input(number);
const nationalNumber = currNumber.getNationalNumber();
const result = nationalNumber.length > 0;
return !result;
}
//zod schema validations
export const ContactFormNameSchema = z
.string()
.min(1, { message: "Name is required" });
export const ContactFormSubjectSchema = z
.string()
.min(1, { message: "Subject is required" });
export const ContactFormPhoneSchema = z
.string()
.transform((arg) => (!isOnlyCountryCode(arg) ? arg : undefined))
.optional()
.refine(
(arg) => {
if (!arg) return true;
return parsePhoneNumber(arg)?.isValid();
},
{
message: "Invalid phone number",
}
);
export const ContactFormEmailSchema = z
.string()
.email({ message: "Invalid email address" });
export const ContactFormMessageSchema = z
.string()
.min(10, { message: "Message should be >10 charaters long" });
export const ContactFormSchema = z.object({
sender: z
.object({
name: ContactFormNameSchema,
email: ContactFormEmailSchema,
phone: ContactFormPhoneSchema,
})
.refine(
(arg) => {
return arg.email || arg.phone;
},
{
message: "Either email or phone number is required",
}
),
subject: ContactFormSubjectSchema,
message: ContactFormMessageSchema,
});

export type ContactFormSchemaType = z.infer<typeof ContactFormSchema>;
//handler
export async function handler(e: APIGatewayEvent) {
try {
const body = e.body;
const parsedBody = body ? JSON.parse(body) : {};
const { sender, subject, message, type } =
parsedBody as ContactMeInputProps;
if (!sender || !subject || !message || !type) {
let parsedBody: any;
try {
parsedBody = body ? JSON.parse(body) : {};
} catch (err) {
return {
statusCode: 400,
headers: corsPostHeaders,
body: "Missing required fields",
body: "Invalid JSON",
};
}
if (type === "email") return await sendEmail({ sender, subject, message });
return {
statusCode: 400,
headers: corsPostHeaders,
body: "Invalid type",
};
const validationResult = ContactFormSchema.safeParse(parsedBody);
if (validationResult.error) {
return {
statusCode: 400,
headers: corsPostHeaders,
body: validationResult.error.errors[0].message,
};
}
const { sender, subject, message } = validationResult.data;
return await sendEmail({ sender, subject, message });
} catch (err) {
return {
statusCode: 500,
Expand Down
56 changes: 12 additions & 44 deletions app/lib/restAPI/resources/contact/contactPost/sendEmail.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,25 @@
import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";
import { validate } from "email-validator";
import { ContactMeInputProps } from ".";
import { ContactFormSchemaType } from ".";
import { convertToStr } from "../../../../../../utils/general/convertToStr";
import { corsHeaders } from "../../utils/corsLambda";
import axios from "axios";
//we need to apply for app verification to use this
export const sendEmailUsingSes = async ({
sender,
subject,
message,
}: ContactMeInputProps) => {
const client = new SESClient({ region: "us-east-1" }); // Replace with your desired region
const params = {
Destination: {
ToAddresses: [
convertToStr(process.env.SES_EMAIL_ADDRESS), // Replace with the email address of the recipient
],
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: `<html><body><p>${message}</p></body></html>`, // Replace with the HTML content of your email
},
},
Subject: {
Charset: "UTF-8",
Data: subject, // Replace with the subject of your email
},
},
Source: sender, // Replace with the email address of the sender
};
const command = new SendEmailCommand(params);
const response = await client.send(command);
return {
statusCode: 200,
headers: corsHeaders,
body: `Succesfully sent email: ${response.MessageId}`,
};
};
//we use send in blue since it doesnt rquire verification, just an account
//we use send in blue since it doesnt require verification, just an account
export const sendEmailUsingSendInBlue = async ({
sender,
subject,
message,
}: ContactMeInputProps) => {
}: ContactFormSchemaType) => {
const url = "https://api.sendinblue.com/v3/smtp/email";
const api_key = convertToStr(process.env.SEND_IN_BLUE_API_KEY);
const payload = {
sender: { email: sender },
sender: { email: sender.email },
to: [{ email: convertToStr(process.env.SES_EMAIL_ADDRESS) }],
subject: subject,
htmlContent: `<html><body><p>${message}</p></body></html>`,
subject: `[Arky's Portfolio Site - ${sender.name}] - ${subject}`,
htmlContent: `<html><body><p>Name:<br>${
sender.name
}</p><br><p>Message:<br>${message}</p><br>${
sender.phone ? `<p>Phone:<br>${sender.phone}</p>` : ""
}</body></html>`,
};
const result = await axios({
method: "post",
Expand All @@ -71,8 +39,8 @@ export const sendEmail = async ({
sender,
subject,
message,
}: ContactMeInputProps) => {
const isEmail = validate(sender);
}: ContactFormSchemaType) => {
const isEmail = validate(sender.email);
if (!isEmail)
return {
statusCode: 400,
Expand Down
19 changes: 12 additions & 7 deletions app/lib/restAPI/resources/contact/contactPost/test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { sendEmailUsingSendInBlue, sendEmailUsingSes } from "./sendEmail";
import { sendEmailUsingSendInBlue } from "./sendEmail";
import * as dotenv from "dotenv";
dotenv.config();
sendEmailUsingSendInBlue({
sender: 'arkyasmal97@gmail.com',
subject:"okay",
message: "Hello"
}).then((res) => {
console.log(res)
}).catch(err=> console.error(err))
sender: {
name: "Arky",
email: "arkyasmal97@gmail.com",
},
subject: "okay",
message: "Hello",
})
.then((res) => {
console.log(res);
})
.catch((err) => console.error(err));
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"libphonenumber-js": "=1.10.26",
"lodash": "=4.17.21",
"source-map-support": "=0.5.21",
"uuid": "=9.0.0"
"uuid": "=9.0.0",
"zod": "^3.23.8"
}
}

0 comments on commit 3d1497b

Please sign in to comment.