Created
January 6, 2023 00:36
-
-
Save macrael/a72cef92388f6c04fee08022dbe0692b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type QueryLoading = { | |
| status: 'LOADING' | |
| } | |
| type QueryError = { | |
| status: 'ERROR' | |
| error: Error | |
| } | |
| type QuerySuccess<SuccessType> = { | |
| status: 'SUCCESS' | |
| data: SuccessType | |
| } | |
| type ApolloUseQueryResult<SuccessType> = QueryLoading | QueryError | QuerySuccess<SuccessType> | |
| // These are the parts of the useQuery result we want to wrap up, converting data | error | loading => result | |
| interface WrappableApolloQuery { | |
| data: any, | |
| error?: Error, | |
| loading: boolean | |
| } | |
| // Apollo's useQuery returns three independent variables to track loading, error, and data. In our usage | |
| // no two of those variables should never be accessed at the same time. This wrapper replaces them with | |
| // a single variable "result" of ApolloUseQueryResult type. | |
| function wrapApolloResult<ResultType extends | |
| WrappableApolloQuery>(queryResult: ResultType): | |
| Omit<ResultType, 'data' | 'loading' | 'error'> & | |
| { result: ApolloUseQueryResult<NonNullable<ResultType["data"]>> } { | |
| const { loading, error, data } = queryResult | |
| if (loading) { | |
| return { | |
| ...queryResult, | |
| result: { | |
| status: 'LOADING', | |
| } | |
| } | |
| } | |
| if (error) { | |
| return { | |
| ...queryResult, | |
| result: { | |
| status: 'ERROR', | |
| error: error, | |
| } | |
| } | |
| } | |
| if (data) { | |
| return { | |
| ...queryResult, | |
| result: { | |
| status: 'SUCCESS', | |
| data, | |
| } | |
| } | |
| } | |
| return { | |
| ...queryResult, | |
| result: { | |
| status: 'ERROR', | |
| error: new Error('UNEXPECTED APOLLO BEHAVIOR, NO DATA'), | |
| } | |
| } | |
| } | |
| export { | |
| wrapApolloResult, | |
| } | |
| export type { | |
| ApolloUseQueryResult, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment