aboutsummaryrefslogtreecommitdiffstats
path: root/tests/msw/handlers/topics/topics-count.handler.ts
blob: 7e3dab9a1a384fe16cd075b7027e60b81c46e3e0 (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
import { type ExecutionResult, graphql as executeGraphql } from 'graphql';
import { HttpResponse, graphql } from 'msw';
import type { TopicsCountResponse } from '../../../../src/services/graphql';
import type { GraphQLPostWhere } from '../../../../src/types';
import { wpTopicsFixture } from '../../../fixtures';
import { getConnection } from '../../../utils/graphql';
import { schema } from '../../schema';

export const topicsCountHandler = graphql.query<
  TopicsCountResponse,
  GraphQLPostWhere
>('TopicsCount', async ({ query, variables }) => {
  const pageParams = new URLSearchParams(window.location.search);
  const isError = pageParams.get('error') === 'true';

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

  const { data, errors } = (await executeGraphql({
    schema,
    source: query,
    variableValues: variables,
    rootValue: {
      topics({ search, title }: typeof variables) {
        const filteredTopicsByTitle = title
          ? wpTopicsFixture.filter((topic) => topic.title.includes(title))
          : wpTopicsFixture;
        const filteredTopics = search
          ? filteredTopicsByTitle.filter((topic) =>
              topic.title.includes(search)
            )
          : filteredTopicsByTitle;

        return getConnection({
          after: null,
          data: filteredTopics,
          first: undefined,
        });
      },
    },
  })) as ExecutionResult<TopicsCountResponse>;

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