File size: 1,594 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Railcar } from '@automattic/calypso-analytics';
import { useInfiniteQuery } from '@tanstack/react-query';
import { buildQueryString } from '@wordpress/url';
import wpcomRequest from 'wpcom-proxy-request';

export enum FeedSort {
	LastUpdated = 'last_updated',
	Relevance = 'relevance',
}

type ReadFeedSearchQueryProps = {
	query?: string;
	excludeFollowed?: boolean;
	sort?: FeedSort;
};

export type FeedItem = {
	URL?: string;
	blog_ID?: string;
	feed_ID?: string;
	meta: {
		links?: {
			feed?: string;
			site?: string;
		};
	};
	railcar?: Railcar;
	subscribe_URL: string;
	subscribers_count?: number;
	title?: string;
};

type FeedResponse = {
	algorithm: string;
	feeds: FeedItem[];
	next_page: string;
	total: number;
};

const useReadFeedSearchQuery = ( {
	query,
	excludeFollowed = false,
	sort = FeedSort.Relevance,
}: ReadFeedSearchQueryProps ) => {
	return useInfiniteQuery( {
		queryKey: [ 'read', 'feed', 'search', query, excludeFollowed, sort ],
		queryFn: async ( { pageParam: pageParamQueryString } ) => {
			if ( query === undefined ) {
				return;
			}

			const urlQuery = buildQueryString( {
				q: query,
				exclude_followed: excludeFollowed,
				sort,
			} ).concat( pageParamQueryString ? `&${ pageParamQueryString }` : '' );

			return wpcomRequest< FeedResponse >( {
				path: '/read/feed',
				apiVersion: '1.1',
				method: 'GET',
				query: urlQuery,
			} );
		},
		enabled: Boolean( query ),
		initialPageParam: '',
		getNextPageParam: ( lastPage ) => lastPage?.next_page,
		refetchOnWindowFocus: false,
	} );
};

export default useReadFeedSearchQuery;