aboutsummaryrefslogtreecommitdiffstats
path: root/tests/msw/handlers/posts/posts-count.handler.ts
blob: a4425a53116e3e2357c352d45a6ab3424f81f809 (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
import { type ExecutionResult, graphql } from 'graphql';
import { HttpResponse } from 'msw';
import type { PostsCountResponse } from '../../../../src/services/graphql';
import type { GraphQLPostWhere } from '../../../../src/types';
import { wpPostsFixture } from '../../../fixtures';
import { getConnection } from '../../../utils/graphql';
import { wordpressAPI } from '../../instances';
import { schema } from '../../schema';

export const postsCountHandler = wordpressAPI.query<
  PostsCountResponse,
  GraphQLPostWhere
>('PostsCount', async ({ query, variables }) => {
  const pageParams = new URLSearchParams(window.location.search);
  const isError = pageParams.get('error') === 'true';

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

  const { data, errors } = (await graphql({
    schema,
    source: query,
    variableValues: variables,
    rootValue: {
      posts({ authorName, search, title }: typeof variables) {
        const filteredPostsByAuthor = authorName
          ? wpPostsFixture.filter((post) =>
              post.author.node.name.includes(authorName)
            )
          : wpPostsFixture;
        const filteredPostsByTitle = title
          ? filteredPostsByAuthor.filter((post) => post.title.includes(title))
          : filteredPostsByAuthor;
        const filteredPosts = search
          ? filteredPostsByTitle.filter(
              (post) =>
                post.title.includes(search) ||
                post.contentParts.afterMore.includes(search) ||
                post.contentParts.beforeMore.includes(search)
            )
          : filteredPostsByTitle;

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

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