omnivore/packages/web/lib/networking/queries/useGetSubscriptionsQuery.tsx

125 lines
2.6 KiB
TypeScript
Raw Normal View History

2022-04-21 03:10:18 +00:00
import { gql } from 'graphql-request'
import useSWR from 'swr'
2023-09-01 04:39:30 +00:00
import { makeGqlFetcher } from '../networkHelpers'
export type SubscriptionStatus = 'ACTIVE' | 'DELETED' | 'UNSUBSCRIBED'
export enum SubscriptionType {
RSS = 'RSS',
NEWSLETTER = 'NEWSLETTER',
}
export enum FetchContentType {
ALWAYS = 'ALWAYS',
NEVER = 'NEVER',
WHEN_EMPTY = 'WHEN_EMPTY',
}
export type Subscription = {
id: string
name: string
type: SubscriptionType
newsletterEmail?: string
url?: string
2024-02-19 02:57:37 +00:00
icon?: string
description?: string
status: SubscriptionStatus
createdAt: string
updatedAt: string
lastFetchedAt?: string
2024-02-07 05:02:19 +00:00
mostRecentItemDate?: string
failedAt?: string
2024-02-07 05:02:19 +00:00
fetchContentType?: FetchContentType
2022-04-22 08:05:07 +00:00
}
2022-04-21 03:10:18 +00:00
type SubscriptionsQueryResponse = {
error: any
isLoading: boolean
2022-04-21 03:10:18 +00:00
isValidating: boolean
subscriptions: Subscription[]
revalidate: () => void
}
type SubscriptionsResponseData = {
subscriptions: SubscriptionsData
}
type SubscriptionsData = {
subscriptions: unknown
}
export function useGetSubscriptionsQuery(
type: SubscriptionType | undefined = undefined,
sortBy = 'UPDATED_TIME'
): SubscriptionsQueryResponse {
2022-04-21 03:10:18 +00:00
const query = gql`
2023-09-01 04:19:36 +00:00
query GetSubscriptions($type: SubscriptionType, $sort: SortParams) {
subscriptions(type: $type, sort: $sort) {
2022-04-21 03:10:18 +00:00
... on SubscriptionsSuccess {
subscriptions {
id
name
type
2022-04-22 08:05:07 +00:00
newsletterEmail
2022-04-21 03:10:18 +00:00
url
2024-02-19 02:57:37 +00:00
icon
2022-04-21 03:10:18 +00:00
description
status
unsubscribeMailTo
unsubscribeHttpUrl
createdAt
updatedAt
lastFetchedAt
fetchContentType
2024-02-07 05:02:19 +00:00
mostRecentItemDate
failedAt
2022-04-21 03:10:18 +00:00
}
}
... on SubscriptionsError {
errorCodes
}
}
}
`
const variables = {
type,
sort: {
by: sortBy,
},
}
2023-09-07 11:16:02 +00:00
const { data, error, mutate, isValidating } = useSWR(
[query, variables],
makeGqlFetcher(variables)
2023-09-01 04:39:30 +00:00
)
2023-09-01 04:19:36 +00:00
2023-09-01 04:39:30 +00:00
try {
2022-04-21 03:10:18 +00:00
if (data) {
const result = data as SubscriptionsResponseData
const subscriptions = result.subscriptions.subscriptions as Subscription[]
return {
error,
isLoading: !error && !data,
2022-04-21 03:10:18 +00:00
isValidating,
subscriptions,
revalidate: () => {
mutate()
},
}
}
} catch (error) {
console.log('error', error)
}
return {
error,
isLoading: !error && !data,
isValidating: true,
2022-04-21 03:10:18 +00:00
subscriptions: [],
// eslint-disable-next-line @typescript-eslint/no-empty-function
revalidate: () => {},
}
}