120 lines
3.0 KiB
TypeScript
120 lines
3.0 KiB
TypeScript
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
|
|
import { SendEmailCommand, SESClient, SESClientConfig } from '@aws-sdk/client-ses';
|
|
|
|
interface ContactRequest {
|
|
name: string;
|
|
email: string;
|
|
institution: string;
|
|
message: string;
|
|
}
|
|
|
|
interface ValidationError {
|
|
field: keyof ContactRequest;
|
|
message: string;
|
|
}
|
|
|
|
interface ValidationErrorsResponse {
|
|
errors: ValidationError[];
|
|
}
|
|
|
|
const sesClient = new SESClient({
|
|
region: 'us-east-2'
|
|
} satisfies SESClientConfig);
|
|
|
|
export async function handler(event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
|
|
if (event.body === null) {
|
|
return {
|
|
statusCode: 400,
|
|
body: JSON.stringify({
|
|
message: 'ContactRequest body required.'
|
|
})
|
|
};
|
|
}
|
|
|
|
const { name, email, institution, message } = JSON.parse(event.body) as ContactRequest;
|
|
const errors: ValidationError[] = [];
|
|
|
|
// name
|
|
if (!name) {
|
|
errors.push({
|
|
field: 'name',
|
|
message: 'Name is required.'
|
|
});
|
|
} else if (name.trim().length === 0) {
|
|
errors.push({
|
|
field: 'name',
|
|
message: 'Name may not be blank.'
|
|
});
|
|
}
|
|
|
|
// email
|
|
if (!email) {
|
|
errors.push({
|
|
field: 'email',
|
|
message: 'Email is required.'
|
|
});
|
|
} else if (email.trim().length === 0) {
|
|
errors.push({
|
|
field: 'email',
|
|
message: 'Email may not be blank.'
|
|
});
|
|
}
|
|
|
|
// message
|
|
if (!message) {
|
|
errors.push({
|
|
field: 'message',
|
|
message: 'Message is required.'
|
|
});
|
|
} else if (message.trim().length === 0) {
|
|
errors.push({
|
|
field: 'message',
|
|
message: 'Message may not be blank.'
|
|
});
|
|
}
|
|
|
|
if (errors.length) {
|
|
return {
|
|
statusCode: 400,
|
|
headers: {
|
|
'Content-type': 'application/json'
|
|
},
|
|
body: JSON.stringify({ errors } satisfies ValidationErrorsResponse)
|
|
};
|
|
} else {
|
|
const sendEmailCommand = new SendEmailCommand({
|
|
Source: 'noreply@api.jessebrault.com',
|
|
Destination: {
|
|
ToAddresses: ['jesse@jessebrault.com']
|
|
},
|
|
Message: {
|
|
Subject: {
|
|
Charset: 'UTF-8',
|
|
Data: 'Contact request'
|
|
},
|
|
Body: {
|
|
Text: {
|
|
Charset: 'utf-8',
|
|
Data: `
|
|
Contact Request from jessebrault.com
|
|
From ${name}
|
|
Email ${email}
|
|
Institution ${institution ?? '<none>'}
|
|
--- Message ---
|
|
|
|
${message}
|
|
`.trim()
|
|
}
|
|
}
|
|
}
|
|
});
|
|
await sesClient.send(sendEmailCommand);
|
|
return {
|
|
statusCode: 200,
|
|
body: JSON.stringify({
|
|
message: 'Success'
|
|
})
|
|
};
|
|
}
|
|
}
|