-
Notifications
You must be signed in to change notification settings - Fork 1
/
postApi.ts
73 lines (70 loc) · 2.62 KB
/
postApi.ts
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
import { api } from '@/api/api';
import { User } from '@/features/auth';
import {
Post,
CreatePostDTO,
UpdatePostDTO,
GetPostDTO,
GetPostsDTO,
PostsResponse,
GetUserPostsDTO,
DeletePostDTO,
DeletePostResponse,
} from '../types';
import { FetchBaseQueryError } from '@reduxjs/toolkit/query';
export const postApi = api.injectEndpoints({
endpoints: (builder) => ({
getPosts: builder.query<PostsResponse, GetPostsDTO>({
query: ({ limit = 10, skip = 0, query = '' }) => ({
url: `posts/search?q=${query}&limit=${limit}&skip=${skip}`,
method: 'GET',
}),
providesTags: (result, _error, _arg) =>
result ? [...result.posts.map(({ id }) => ({ type: 'Post' as const, id })), 'Post'] : ['Post'],
}),
getUserPosts: builder.query<PostsResponse, GetUserPostsDTO>({
query: ({ userId, limit = 10, skip = 0 }) => ({
url: `users/${userId}/posts?limit=${limit}&skip=${skip}`,
method: 'GET',
}),
providesTags: (result, _error, _arg) =>
result ? [...result.posts.map(({ id }) => ({ type: 'Post' as const, id })), 'Post'] : ['Post'],
}),
getPost: builder.query<Post, GetPostDTO>({
async queryFn(arg, _queryApi, _extraOptions, fetchWithBQ) {
// Get post
const postResult = await fetchWithBQ({ url: `posts/${arg.postId}`, method: 'GET' });
if (postResult.error) {
return { error: postResult.error };
}
const post = postResult.data as Post;
// Get user
const userResult = await fetchWithBQ({ url: `users/${post.userId}`, method: 'GET' });
return userResult.data
? { data: { ...post, user: userResult.data as User } as Post }
: { error: userResult.error as FetchBaseQueryError };
},
providesTags: (_result, _error, arg) => [{ type: 'Post', id: arg.postId }],
}),
createPost: builder.mutation<Post, CreatePostDTO>({
query: (post) => ({ url: 'posts/add', method: 'POST', body: post }),
invalidatesTags: ['Post'],
}),
updatePost: builder.mutation<Post, UpdatePostDTO>({
query: (post) => ({ url: `posts/${post.id}`, method: 'PUT', body: post }),
invalidatesTags: (_result, _error, arg) => [{ type: 'Post', id: arg.id }],
}),
deletePost: builder.mutation<DeletePostResponse, DeletePostDTO>({
query: ({ id }) => ({ url: `posts/${id}`, method: 'DELETE' }),
invalidatesTags: (_result, _error, arg) => [{ type: 'Post', id: arg.id }],
}),
}),
});
export const {
useCreatePostMutation,
useUpdatePostMutation,
useGetPostQuery,
useGetPostsQuery,
useGetUserPostsQuery,
useDeletePostMutation,
} = postApi;