|
| 1 | +import { defineAction } from 'astro:actions'; |
| 2 | +import { env } from 'cloudflare:workers'; |
| 3 | +import { createContactActionHandler, extractContactFormValues } from '../lib/contact/contactAction'; |
| 4 | +import { submitContactSubmission } from '../lib/contact/contactService'; |
| 5 | +import { createCloudflareEmailNotifier } from '../lib/contact/cloudflareEmailNotifier'; |
| 6 | +import { createD1ContactSubmissionRepository } from '../lib/contact/d1Repository'; |
| 7 | +import { createTurnstileVerifier } from '../lib/contact/turnstile'; |
| 8 | +import type { ContactRuntimeEnv } from '../lib/contact/types'; |
| 9 | + |
| 10 | +const isContactRuntimeEnv = ( |
| 11 | + runtimeEnv: Partial<ContactRuntimeEnv> |
| 12 | +): runtimeEnv is ContactRuntimeEnv => |
| 13 | + Boolean( |
| 14 | + runtimeEnv.CONTACT_DB && |
| 15 | + runtimeEnv.EMAIL && |
| 16 | + runtimeEnv.CONTACT_TO_EMAIL && |
| 17 | + runtimeEnv.CONTACT_FROM_EMAIL && |
| 18 | + runtimeEnv.TURNSTILE_SECRET_KEY |
| 19 | + ); |
| 20 | + |
| 21 | +export const server = { |
| 22 | + contact: defineAction({ |
| 23 | + accept: 'form', |
| 24 | + handler: async (formData, context) => { |
| 25 | + const runtimeEnv = env as Partial<ContactRuntimeEnv>; |
| 26 | + |
| 27 | + if (!isContactRuntimeEnv(runtimeEnv)) { |
| 28 | + return { |
| 29 | + ok: false as const, |
| 30 | + values: extractContactFormValues(formData), |
| 31 | + fieldErrors: {}, |
| 32 | + message: 'お問い合わせ機能の設定が不足しています。', |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + const actionHandler = createContactActionHandler({ |
| 37 | + submitContactSubmission: (input) => |
| 38 | + submitContactSubmission(input, { |
| 39 | + verifyTurnstile: createTurnstileVerifier({ |
| 40 | + secretKey: runtimeEnv.TURNSTILE_SECRET_KEY, |
| 41 | + }), |
| 42 | + repository: createD1ContactSubmissionRepository(runtimeEnv.CONTACT_DB), |
| 43 | + notifier: createCloudflareEmailNotifier({ |
| 44 | + email: runtimeEnv.EMAIL, |
| 45 | + toEmail: runtimeEnv.CONTACT_TO_EMAIL, |
| 46 | + fromEmail: runtimeEnv.CONTACT_FROM_EMAIL, |
| 47 | + }), |
| 48 | + }), |
| 49 | + }); |
| 50 | + |
| 51 | + return actionHandler(formData, { remoteIp: context.clientAddress }); |
| 52 | + }, |
| 53 | + }), |
| 54 | +}; |
0 commit comments