-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type authenticated query correctly #393
Draft
simon-debruijn
wants to merge
33
commits into
main
Choose a base branch
from
type-authenticated-query-correctly
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 10 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
c8c7bb9
Add useAuthenticatedQuery
simon-debruijn ad56f49
Add redirect when unauthorized
simon-debruijn 2cac594
Remove unnecessary typing
simon-debruijn f550c18
Sort imports
simon-debruijn 0b55d57
Add server side api call to test example
simon-debruijn 637eecf
Use separate prefetchAuthenticatedQuery function
simon-debruijn 241f589
Rename file to v2
simon-debruijn e8340e0
Change after next build
simon-debruijn 98e3c49
Rename type to GenerateQueryKeyArguments
simon-debruijn 0409ad5
Remove toString
simon-debruijn 814c0a3
Merge branch 'main' into type-authenticated-query-correctly
Anahkiasen 90c2f98
Update useGetUserQuery
Anahkiasen 6532974
Add types to useHeaders
Anahkiasen ca3892d
Update useGetPermissionsQuery
Anahkiasen 62579f2
Update useGetRolesQuery
Anahkiasen 960564d
Pass headers through context instead of meta
Anahkiasen c01e417
Update useGetUserQueryServerSide
Anahkiasen c08fcac
Pass headers through context instead of meta
Anahkiasen 06cd225
Merge branch 'type-authenticated-query-correctly' into type-authentic…
Anahkiasen d63ebf4
Pass queryArguments as part of context
Anahkiasen b27f7bb
Work on failed authentication
Anahkiasen 5cbbdc5
Fix Sidebar not returning valid JSX
Anahkiasen c04d9e8
Fix some TS errors
Anahkiasen b2f3187
Return query state
Anahkiasen 38f474a
Try to revert some changes?
Anahkiasen e21e07f
Try to make authentication work properly
Anahkiasen 8eac43b
Fix optional feature flag property
Anahkiasen 9f578fd
Merge branch 'type-authenticated-query-correctly' into type-authentic…
Anahkiasen 32feb8f
Make return type explicit
Anahkiasen 343ecd1
Linting
Anahkiasen d8a21e1
Better handling of undefined query page
Anahkiasen 73936c4
Correct feature flag type
Anahkiasen 63dc168
Merge pull request #797 from cultuurnet/type-authenticated-query-corr…
Anahkiasen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
import { NextApiRequest } from 'next'; | ||
import { useRouter } from 'next/router'; | ||
import { Cookies } from 'react-cookie'; | ||
import { | ||
FetchQueryOptions, | ||
QueryClient, | ||
QueryFunctionContext, | ||
QueryKey, | ||
useQuery, | ||
UseQueryOptions, | ||
} from 'react-query'; | ||
|
||
import { FetchError } from '@/utils/fetchFromApi'; | ||
import { isTokenValid } from '@/utils/isTokenValid'; | ||
|
||
import { useCookiesWithOptions } from '../useCookiesWithOptions'; | ||
import { Headers } from './types/Headers'; | ||
import { createHeaders, useHeaders } from './useHeaders'; | ||
|
||
type QueryArguments = Record<string, string>; | ||
|
||
type GenerateQueryKeyArguments = { | ||
queryKey: QueryKey; | ||
queryArguments: QueryArguments; | ||
}; | ||
|
||
type GeneratedQueryKey = readonly [QueryKey, QueryArguments]; | ||
|
||
type AuthenticatedQueryFunctionContext = QueryFunctionContext<GeneratedQueryKey> & { | ||
headers: Headers; | ||
}; | ||
|
||
type ServerSideOptions = { | ||
req: NextApiRequest; | ||
queryClient: QueryClient; | ||
}; | ||
|
||
type PrefetchAuthenticatedQueryOptions<TQueryFnData> = { | ||
queryArguments?: QueryArguments; | ||
} & ServerSideOptions & | ||
FetchQueryOptions<TQueryFnData, FetchError, TQueryFnData, QueryKey>; | ||
|
||
type UseAuthenticatedQueryOptions<TQueryFnData> = { | ||
queryArguments?: QueryArguments; | ||
} & UseQueryOptions<TQueryFnData, FetchError, TQueryFnData, QueryKey>; | ||
|
||
const isUnAuthorized = (status: number) => [401, 403].includes(status); | ||
|
||
const generateQueryKey = ({ | ||
queryKey, | ||
queryArguments, | ||
}: GenerateQueryKeyArguments): GeneratedQueryKey => { | ||
if (Object.keys(queryArguments ?? {}).length > 0) { | ||
return [queryKey, queryArguments]; | ||
} | ||
|
||
return [queryKey, {}]; | ||
}; | ||
|
||
type GetPreparedOptionsArguments<TQueryFnData> = { | ||
options: UseAuthenticatedQueryOptions<TQueryFnData>; | ||
isTokenPresent: boolean; | ||
headers: Headers; | ||
}; | ||
|
||
const getPreparedOptions = <TQueryFnData = unknown>({ | ||
options, | ||
isTokenPresent, | ||
headers, | ||
}: GetPreparedOptionsArguments<TQueryFnData>): UseQueryOptions< | ||
TQueryFnData, | ||
FetchError, | ||
TQueryFnData, | ||
GeneratedQueryKey | ||
> => { | ||
const { queryKey, queryArguments, queryFn, ...restOptions } = options; | ||
const generatedQueryKey = generateQueryKey({ | ||
queryKey, | ||
queryArguments, | ||
}); | ||
|
||
const queryFunctionWithHeaders = async ( | ||
context: QueryFunctionContext<GeneratedQueryKey>, | ||
) => { | ||
return await queryFn( | ||
context, | ||
// @ts-expect-error | ||
headers, | ||
); | ||
}; | ||
return { | ||
...restOptions, | ||
queryKey: generatedQueryKey, | ||
queryFn: queryFunctionWithHeaders, | ||
...('enabled' in restOptions && { | ||
enabled: isTokenPresent && !!restOptions.enabled, | ||
}), | ||
}; | ||
}; | ||
|
||
const prefetchAuthenticatedQuery = async <TQueryFnData = unknown>({ | ||
req, | ||
queryClient, | ||
...options | ||
}: PrefetchAuthenticatedQueryOptions<TQueryFnData>) => { | ||
if (typeof window !== 'undefined') { | ||
throw new Error('Only use prefetchAuthenticatedQuery in server-side code'); | ||
} | ||
|
||
const cookies = new Cookies(req?.headers?.cookie); | ||
const headers = createHeaders(cookies.get('token')); | ||
|
||
const { queryKey, queryFn } = getPreparedOptions<TQueryFnData>({ | ||
options, | ||
isTokenPresent: isTokenValid(cookies.get('token')), | ||
headers, | ||
}); | ||
|
||
try { | ||
await queryClient.prefetchQuery<TQueryFnData, FetchError>( | ||
queryKey, | ||
queryFn, | ||
); | ||
} catch {} | ||
|
||
return await queryClient.getQueryData<TQueryFnData>(queryKey); | ||
}; | ||
|
||
const useAuthenticatedQuery = <TQueryFnData = unknown>( | ||
options: UseAuthenticatedQueryOptions<TQueryFnData>, | ||
) => { | ||
const headers = useHeaders(); | ||
const { cookies, removeAuthenticationCookies } = useCookiesWithOptions([ | ||
'token', | ||
]); | ||
const router = useRouter(); | ||
|
||
const preparedOptions = getPreparedOptions({ | ||
options, | ||
isTokenPresent: isTokenValid(cookies.token), | ||
headers, | ||
}); | ||
|
||
const result = useQuery(preparedOptions); | ||
|
||
if ( | ||
isUnAuthorized(result?.error?.status) && | ||
!router.asPath.startsWith('/login') && | ||
router.asPath !== '/[...params]' | ||
) { | ||
removeAuthenticationCookies(); | ||
|
||
router.push('/login'); | ||
|
||
return; | ||
} | ||
|
||
return result; | ||
}; | ||
|
||
export { prefetchAuthenticatedQuery, useAuthenticatedQuery }; | ||
export type { AuthenticatedQueryFunctionContext }; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { useEffect } from 'react'; | ||
import { dehydrate } from 'react-query/hydration'; | ||
|
||
import { | ||
AuthenticatedQueryFunctionContext, | ||
prefetchAuthenticatedQuery, | ||
useAuthenticatedQuery, | ||
} from '@/hooks/api/authenticated-query-v2'; | ||
import { Event } from '@/types/Event'; | ||
import { fetchFromApi, isErrorObject } from '@/utils/fetchFromApi'; | ||
import { getApplicationServerSideProps } from '@/utils/getApplicationServerSideProps'; | ||
|
||
const EVENT_ID = 'a9e9cdce-2e3c-4b17-9c6b-a7eb445252d1'; | ||
|
||
const getEventById = async ({ | ||
queryKey, | ||
headers, | ||
}: AuthenticatedQueryFunctionContext) => { | ||
const [key, { id }] = queryKey; | ||
const res = await fetchFromApi({ | ||
path: `/event/${id}`, | ||
options: { | ||
headers, | ||
}, | ||
}); | ||
if (isErrorObject(res)) { | ||
// eslint-disable-next-line no-console | ||
return console.error(res); | ||
} | ||
return await res.json(); | ||
}; | ||
|
||
const Test = () => { | ||
const query = useAuthenticatedQuery<Event>({ | ||
queryKey: ['events'], | ||
queryFn: getEventById, | ||
queryArguments: { id: EVENT_ID }, | ||
enabled: !!EVENT_ID, | ||
}); | ||
|
||
useEffect(() => { | ||
console.log({ eventOnClient: query.data }); | ||
}, [query.data]); | ||
|
||
return null; | ||
}; | ||
|
||
export const getServerSideProps = getApplicationServerSideProps( | ||
async ({ req, cookies, queryClient }) => { | ||
const eventOnServer = await prefetchAuthenticatedQuery<Event>({ | ||
req, | ||
queryClient, | ||
queryKey: ['events'], | ||
queryFn: getEventById, | ||
queryArguments: { id: EVENT_ID }, | ||
}); | ||
|
||
console.log({ eventOnServer }); | ||
|
||
return { | ||
props: { | ||
dehydratedState: dehydrate(queryClient), | ||
cookies, | ||
}, | ||
}; | ||
}, | ||
); | ||
|
||
export default Test; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we remove this
//@ts-expect-error
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we won't be able to remove this one, because react-query doesn't expect another argument it only known
context
which containsqueryKey
andpageParam