Skip to content

Commit

Permalink
refactor: simplify RTK Query endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
iamacook committed Oct 11, 2024
1 parent 8e83b0a commit a2696ed
Showing 1 changed file with 16 additions and 32 deletions.
48 changes: 16 additions & 32 deletions src/store/gateway.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,35 @@
import { createApi } from '@reduxjs/toolkit/query/react'
import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react'

import { getTransactionDetails, type TransactionDetails } from '@safe-global/safe-gateway-typescript-sdk'
import type { BaseQueryFn } from '@reduxjs/toolkit/dist/query/baseQueryTypes'
import type { FetchBaseQueryError } from '@reduxjs/toolkit/dist/query/react'
import { asError } from '@/services/exceptions/utils'
import { getDelegates } from '@safe-global/safe-gateway-typescript-sdk'
import type { DelegateResponse } from '@safe-global/safe-gateway-typescript-sdk/dist/types/delegates'

const noopBaseQuery: BaseQueryFn<
unknown, // QueryArg type
unknown, // ResultType
FetchBaseQueryError, // ErrorType
{}, // DefinitionExtraOptions
{} // Meta
> = async () => ({ data: null })
async function buildQueryFn<T>(fn: () => Promise<T>) {
try {
return { data: await fn() }
} catch (error) {
return { error: asError(error) }
}
}

export const gatewayApi = createApi({
reducerPath: 'gatewayApi',
baseQuery: noopBaseQuery,
baseQuery: fakeBaseQuery<Error>(),
endpoints: (builder) => ({
getTransactionDetails: builder.query<TransactionDetails, { chainId: string; txId: string }>({
async queryFn({ chainId, txId }) {
try {
const txDetails = await getTransactionDetails(chainId, txId)
return { data: txDetails }
} catch (error) {
return { error: error as FetchBaseQueryError }
}
queryFn({ chainId, txId }) {
return buildQueryFn(() => getTransactionDetails(chainId, txId))
},
}),
getMultipleTransactionDetails: builder.query<TransactionDetails[], { chainId: string; txIds: string[] }>({
async queryFn({ chainId, txIds }) {
try {
const txDetails = await Promise.all(txIds.map((txId) => getTransactionDetails(chainId, txId)))
return { data: txDetails }
} catch (error) {
return { error: error as FetchBaseQueryError }
}
queryFn({ chainId, txIds }) {
return buildQueryFn(() => Promise.all(txIds.map((txId) => getTransactionDetails(chainId, txId))))
},
}),
getDelegates: builder.query<DelegateResponse, { chainId: string; safeAddress: string }>({
async queryFn({ chainId, safeAddress }) {
try {
const delegates = await getDelegates(chainId, { safe: safeAddress })
return { data: delegates }
} catch (error) {
return { error: error as FetchBaseQueryError }
}
queryFn({ chainId, safeAddress }) {
return buildQueryFn(() => getDelegates(chainId, { safe: safeAddress }))
},
}),
}),
Expand Down

0 comments on commit a2696ed

Please sign in to comment.