File size: 9,117 Bytes
c2b7eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import type {
  QueryStateSelector,
  UseMutation,
  UseQuery,
} from '@internal/query/react/buildHooks'
import { ANY } from '@internal/tests/utils/helpers'
import type { SerializedError } from '@reduxjs/toolkit'
import type {
  QueryDefinition,
  SubscriptionOptions,
  TypedQueryStateSelector,
} from '@reduxjs/toolkit/query/react'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { useState } from 'react'

let amount = 0
let nextItemId = 0

interface Item {
  id: number
}

const api = createApi({
  baseQuery: (arg: any) => {
    if (arg?.body && 'amount' in arg.body) {
      amount += 1
    }

    if (arg?.body && 'forceError' in arg.body) {
      return {
        error: {
          status: 500,
          data: null,
        },
      }
    }

    if (arg?.body && 'listItems' in arg.body) {
      const items: Item[] = []
      for (let i = 0; i < 3; i++) {
        const item = { id: nextItemId++ }
        items.push(item)
      }
      return { data: items }
    }

    return {
      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
    }
  },
  endpoints: (build) => ({
    getUser: build.query<{ name: string }, number>({
      query: () => ({
        body: { name: 'Timmy' },
      }),
    }),
    getUserAndForceError: build.query<{ name: string }, number>({
      query: () => ({
        body: {
          forceError: true,
        },
      }),
    }),
    getIncrementedAmount: build.query<{ amount: number }, void>({
      query: () => ({
        url: '',
        body: {
          amount,
        },
      }),
    }),
    updateUser: build.mutation<{ name: string }, { name: string }>({
      query: (update) => ({ body: update }),
    }),
    getError: build.query({
      query: () => '/error',
    }),
    listItems: build.query<Item[], { pageNumber: number }>({
      serializeQueryArgs: ({ endpointName }) => {
        return endpointName
      },
      query: ({ pageNumber }) => ({
        url: `items?limit=1&offset=${pageNumber}`,
        body: {
          listItems: true,
        },
      }),
      merge: (currentCache, newItems) => {
        currentCache.push(...newItems)
      },
      forceRefetch: () => {
        return true
      },
    }),
  }),
})

describe('type tests', () => {
  test('useLazyQuery hook callback returns various properties to handle the result', () => {
    function User() {
      const [getUser] = api.endpoints.getUser.useLazyQuery()
      const [{ successMsg, errMsg, isAborted }, setValues] = useState({
        successMsg: '',
        errMsg: '',
        isAborted: false,
      })

      const handleClick = (abort: boolean) => async () => {
        const res = getUser(1)

        // no-op simply for clearer type assertions
        res.then((result) => {
          if (result.isSuccess) {
            expectTypeOf(result).toMatchTypeOf<{
              data: {
                name: string
              }
            }>()
          }

          if (result.isError) {
            expectTypeOf(result).toMatchTypeOf<{
              error: { status: number; data: unknown } | SerializedError
            }>()
          }
        })

        expectTypeOf(res.arg).toBeNumber()

        expectTypeOf(res.requestId).toBeString()

        expectTypeOf(res.abort).toEqualTypeOf<() => void>()

        expectTypeOf(res.unsubscribe).toEqualTypeOf<() => void>()

        expectTypeOf(res.updateSubscriptionOptions).toEqualTypeOf<
          (options: SubscriptionOptions) => void
        >()

        expectTypeOf(res.refetch).toMatchTypeOf<() => void>()

        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
      }

      return (
        <div>
          <button onClick={handleClick(false)}>Fetch User successfully</button>
          <button onClick={handleClick(true)}>Fetch User and abort</button>
          <div>{successMsg}</div>
          <div>{errMsg}</div>
          <div>{isAborted ? 'Request was aborted' : ''}</div>
        </div>
      )
    }
  })

  test('useMutation hook callback returns various properties to handle the result', async () => {
    function User() {
      const [updateUser] = api.endpoints.updateUser.useMutation()
      const [successMsg, setSuccessMsg] = useState('')
      const [errMsg, setErrMsg] = useState('')
      const [isAborted, setIsAborted] = useState(false)

      const handleClick = async () => {
        const res = updateUser({ name: 'Banana' })

        expectTypeOf(res).resolves.toMatchTypeOf<
          | {
              error: { status: number; data: unknown } | SerializedError
            }
          | {
              data: {
                name: string
              }
            }
        >()

        expectTypeOf(res.arg).toMatchTypeOf<{
          endpointName: string
          originalArgs: { name: string }
          track?: boolean
        }>()

        expectTypeOf(res.requestId).toBeString()

        expectTypeOf(res.abort).toEqualTypeOf<() => void>()

        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()

        expectTypeOf(res.reset).toEqualTypeOf<() => void>()
      }

      return (
        <div>
          <button onClick={handleClick}>Update User and abort</button>
          <div>{successMsg}</div>
          <div>{errMsg}</div>
          <div>{isAborted ? 'Request was aborted' : ''}</div>
        </div>
      )
    }
  })

  test('top level named hooks', () => {
    interface Post {
      id: number
      name: string
      fetched_at: string
    }

    type PostsResponse = Post[]

    const api = createApi({
      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
      tagTypes: ['Posts'],
      endpoints: (build) => ({
        getPosts: build.query<PostsResponse, void>({
          query: () => ({ url: 'posts' }),
          providesTags: (result) =>
            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
        }),
        updatePost: build.mutation<Post, Partial<Post>>({
          query: ({ id, ...body }) => ({
            url: `post/${id}`,
            method: 'PUT',
            body,
          }),
          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
        }),
        addPost: build.mutation<Post, Partial<Post>>({
          query: (body) => ({
            url: `post`,
            method: 'POST',
            body,
          }),
          invalidatesTags: ['Posts'],
        }),
      }),
    })

    expectTypeOf(api.useGetPostsQuery).toEqualTypeOf(
      api.endpoints.getPosts.useQuery,
    )

    expectTypeOf(api.useUpdatePostMutation).toEqualTypeOf(
      api.endpoints.updatePost.useMutation,
    )

    expectTypeOf(api.useAddPostMutation).toEqualTypeOf(
      api.endpoints.addPost.useMutation,
    )
  })

  test('UseQuery type can be used to recreate the hook type', () => {
    const fakeQuery = ANY as UseQuery<
      typeof api.endpoints.getUser.Types.QueryDefinition
    >

    expectTypeOf(fakeQuery).toEqualTypeOf(api.endpoints.getUser.useQuery)
  })

  test('UseMutation type can be used to recreate the hook type', () => {
    const fakeMutation = ANY as UseMutation<
      typeof api.endpoints.updateUser.Types.MutationDefinition
    >

    expectTypeOf(fakeMutation).toEqualTypeOf(
      api.endpoints.updateUser.useMutation,
    )
  })

  test('TypedQueryStateSelector creates a pre-typed version of QueryStateSelector', () => {
    type Post = {
      id: number
      title: string
    }

    type PostsApiResponse = {
      posts: Post[]
      total: number
      skip: number
      limit: number
    }

    type QueryArgument = number | undefined

    type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>

    type SelectedResult = Pick<PostsApiResponse, 'posts'>

    const postsApiSlice = createApi({
      baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
      reducerPath: 'postsApi',
      tagTypes: ['Posts'],
      endpoints: (build) => ({
        getPosts: build.query<PostsApiResponse, QueryArgument>({
          query: (limit = 5) => `?limit=${limit}&select=title`,
        }),
      }),
    })

    const { useGetPostsQuery } = postsApiSlice

    function PostById({ id }: { id: number }) {
      const { post } = useGetPostsQuery(undefined, {
        selectFromResult: (state) => ({
          post: state.data?.posts.find((post) => post.id === id),
        }),
      })

      expectTypeOf(post).toEqualTypeOf<Post | undefined>()

      return <li>{post?.title}</li>
    }

    const EMPTY_ARRAY: Post[] = []

    const typedSelectFromResult: TypedQueryStateSelector<
      PostsApiResponse,
      QueryArgument,
      BaseQueryFunction,
      SelectedResult
    > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })

    function PostsList() {
      const { posts } = useGetPostsQuery(undefined, {
        selectFromResult: typedSelectFromResult,
      })

      expectTypeOf(posts).toEqualTypeOf<Post[]>()

      return (
        <div>
          <ul>
            {posts.map((post) => (
              <PostById key={post.id} id={post.id} />
            ))}
          </ul>
        </div>
      )
    }
  })
})