Skip to content

Commit bedd543

Browse files
committed
feat(contact): add unified POST /api/contact/submit route
1 parent fce8c7f commit bedd543

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/pages/api/contact/submit.ts

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { tryResult } from '@atb/modules/api-server';
2+
import { handlerWithContactFormClient } from '@atb/server/contact';
3+
import { ContactApiReturnType } from '@atb/server/contact/types';
4+
import type { FormSchemaName } from '@mrfylke/contact-form';
5+
import { NextApiRequest, NextApiResponse } from 'next';
6+
7+
export const config = {
8+
api: {
9+
bodyParser: {
10+
sizeLimit: '50mb',
11+
},
12+
},
13+
};
14+
15+
function getSubmitForFormType(
16+
client: {
17+
submitTicketControlForm: (body: unknown) => Promise<ContactApiReturnType>;
18+
submitRefundForm: (body: unknown) => Promise<ContactApiReturnType>;
19+
submitMeansOfTransportForm: (body: unknown) => Promise<ContactApiReturnType>;
20+
submitTicketingForm: (body: unknown) => Promise<ContactApiReturnType>;
21+
submitJourneyInfoForm: (body: unknown) => Promise<ContactApiReturnType>;
22+
},
23+
formType: FormSchemaName,
24+
): (body: Record<string, unknown>) => Promise<ContactApiReturnType> {
25+
const map: Record<
26+
FormSchemaName,
27+
(body: Record<string, unknown>) => Promise<ContactApiReturnType>
28+
> = {
29+
ticketControl: (body) => client.submitTicketControlForm(body),
30+
refund: (body) => client.submitRefundForm(body),
31+
meansOfTransport: (body) => client.submitMeansOfTransportForm(body),
32+
ticketing: (body) => client.submitTicketingForm(body),
33+
journeyInfo: (body) => client.submitJourneyInfoForm(body),
34+
};
35+
return map[formType];
36+
}
37+
38+
export default handlerWithContactFormClient<ContactApiReturnType>({
39+
async POST(req: NextApiRequest, res: NextApiResponse, { client, ok }) {
40+
return tryResult(req, res, async () => {
41+
const { formType, ...body } = req.body as Record<string, unknown> & {
42+
formType?: FormSchemaName;
43+
};
44+
if (
45+
!formType ||
46+
typeof formType !== 'string' ||
47+
!['ticketControl', 'refund', 'meansOfTransport', 'ticketing', 'journeyInfo'].includes(formType)
48+
) {
49+
return res.status(400).json({
50+
success: false,
51+
message: 'Missing or invalid formType',
52+
});
53+
}
54+
const submit = getSubmitForFormType(client, formType as FormSchemaName);
55+
return ok(await submit(body as Record<string, unknown>));
56+
});
57+
},
58+
});

0 commit comments

Comments
 (0)