aboutsummaryrefslogtreecommitdiffstats
path: root/tests/msw/handlers/forms/send-email.handler.ts
blob: 89173306252f511578b19026d0dd6ea52c91e879 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { type ExecutionResult, graphql } from 'graphql';
import { HttpResponse } from 'msw';
import type {
  SendEmail,
  SendEmailInput,
  SendEmailResponse,
} from '../../../../src/services/graphql';
import { CONFIG } from '../../../../src/utils/config';
import { wordpressAPI } from '../../instances';
import { schema } from '../../schema';

export const sendEmailHandler = wordpressAPI.mutation<
  SendEmailResponse,
  Record<'input', SendEmailInput>
>('SendEmail', async ({ query, variables }) => {
  const pageParams = new URLSearchParams(window.location.search);
  const isError = pageParams.get('error') === 'true';

  if (isError)
    return HttpResponse.json({
      data: {
        sendEmail: {
          clientMutationId: null,
          message: 'Not allowed.',
          origin: CONFIG.url,
          replyTo: '',
          sent: false,
        },
      },
    });

  const { data, errors } = (await graphql({
    schema,
    source: query,
    variableValues: variables,
    rootValue: {
      sendEmail({ input }: typeof variables): SendEmail {
        const { body, clientMutationId, replyTo, subject } = input;
        const message = `Object: ${subject}\n\n${body}`;

        return {
          clientMutationId,
          message,
          origin: CONFIG.url,
          replyTo,
          sent: replyTo.includes('@'),
        };
      },
    },
  })) as ExecutionResult<SendEmailResponse>;

  return HttpResponse.json({ data, errors });
});