aboutsummaryrefslogtreecommitdiffstats
path: root/tests/msw/handlers/comments/comments-list.handler.ts
blob: ad760fc6413882eb851809e939442fc45e44d407 (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
import { type ExecutionResult, graphql } from 'graphql';
import { HttpResponse } from 'msw';
import type {
  FetchCommentsListInput,
  CommentsListResponse,
} from '../../../../src/services/graphql';
import { wpCommentsFixture } from '../../../fixtures';
import { wordpressAPI } from '../../instances';
import { schema } from '../../schema';

export const commentsListHandler = wordpressAPI.query<
  CommentsListResponse,
  FetchCommentsListInput
>('CommentsList', async ({ query, variables }) => {
  const pageParams = new URLSearchParams(window.location.search);
  const isError = pageParams.get('error') === 'true';

  if (isError) return HttpResponse.json({ data: { comments: null } });

  const { data, errors } = (await graphql({
    schema,
    source: query,
    variableValues: variables,
    rootValue: {
      comments({ first, where }: typeof variables) {
        const { status: commentStatus } = where ?? {};
        const filteredComments = commentStatus
          ? wpCommentsFixture.filter(
              (comment) => comment.status === commentStatus
            )
          : wpCommentsFixture;
        const comments = filteredComments.slice(0, first);

        return { nodes: comments };
      },
    },
  })) as ExecutionResult<CommentsListResponse>;

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