Skip to content

Commit

Permalink
Merge pull request #797 from cultuurnet/type-authenticated-query-corr…
Browse files Browse the repository at this point in the history
…ectly-user
  • Loading branch information
Anahkiasen authored Sep 7, 2023
2 parents d63ebf4 + 73936c4 commit 63dc168
Show file tree
Hide file tree
Showing 15 changed files with 190 additions and 175 deletions.
16 changes: 4 additions & 12 deletions src/hooks/api/authenticated-query-v2.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextApiRequest } from 'next';
import { useRouter } from 'next/router';
import { GetServerSidePropsContext } from 'next/types';
import { Cookies } from 'react-cookie';
import {
FetchQueryOptions,
Expand All @@ -14,7 +14,6 @@ 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>;
Expand All @@ -33,7 +32,7 @@ type AuthenticatedQueryFunctionContext<TQueryArguments = unknown> =
};

type ServerSideOptions = {
req: NextApiRequest;
req: GetServerSidePropsContext['req'];
queryClient: QueryClient;
};

Expand Down Expand Up @@ -72,7 +71,7 @@ const generateQueryKey = ({
type GetPreparedOptionsArguments<TQueryFnData> = {
options: UseAuthenticatedQueryOptions<TQueryFnData>;
isTokenPresent: boolean;
headers: Headers;
headers: HeadersInit;
};

const getPreparedOptions = <TQueryFnData = unknown>({
Expand Down Expand Up @@ -116,14 +115,7 @@ const prefetchAuthenticatedQuery = async <TQueryFnData = unknown>({
headers,
});

try {
await queryClient.prefetchQuery<TQueryFnData, FetchError>(
queryKey,
queryFn,
);
} catch {}

return await queryClient.getQueryData<TQueryFnData>(queryKey);
return queryClient.fetchQuery<TQueryFnData, FetchError>(queryKey, queryFn);
};

const useAuthenticatedQuery = <TQueryFnData = unknown>(
Expand Down
8 changes: 5 additions & 3 deletions src/hooks/api/authenticated-query.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { isEqual } from 'lodash';
import flatten from 'lodash/flatten';
import type { NextApiRequest } from 'next';
import { useRouter } from 'next/router';
import { GetServerSidePropsContext } from 'next/types';
import { useCallback } from 'react';
import { Cookies } from 'react-cookie';
import {
MutationFunction,
QueryClient,
useMutation,
useQueries,
useQuery,
useQueryClient,
UseQueryResult,
} from 'react-query';
import { useMutation, useQueries, useQuery } from 'react-query';

import { useCookiesWithOptions } from '@/hooks/useCookiesWithOptions';
import type { CalendarSummaryFormat } from '@/utils/createEmbededCalendarSummaries';
Expand All @@ -21,7 +23,7 @@ import { isTokenValid } from '@/utils/isTokenValid';
import { createHeaders, useHeaders } from './useHeaders';

type ServerSideQueryOptions = {
req?: NextApiRequest;
req?: GetServerSidePropsContext['req'];
queryClient?: QueryClient;
};

Expand Down
5 changes: 4 additions & 1 deletion src/hooks/api/useHeaders.js → src/hooks/api/useHeaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import getConfig from 'next/config';

import { useCookiesWithOptions } from '../useCookiesWithOptions';

const createHeaders = (token, extraHeaders) => {
const createHeaders = (
token: string,
extraHeaders: HeadersInit = {},
): HeadersInit => {
const { publicRuntimeConfig } = getConfig();

return {
Expand Down
20 changes: 11 additions & 9 deletions src/hooks/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import jwt_decode from 'jwt-decode';
import getConfig from 'next/config';

import { FetchError, fetchFromApi, isErrorObject } from '@/utils/fetchFromApi';

import { Cookies, useCookiesWithOptions } from '../useCookiesWithOptions';
import { ServerSideQueryOptions } from './authenticated-query';
import {
ServerSideQueryOptions,
useAuthenticatedQuery,
} from './authenticated-query';
prefetchAuthenticatedQuery,
useAuthenticatedQuery as useAuthenticatedQueryV2,
} from './authenticated-query-v2';

type User = {
sub: string;
Expand Down Expand Up @@ -45,7 +45,7 @@ const getUser = async (cookies: Cookies) => {
throw new FetchError(401, 'Unauthorized');
}

const userInfo = jwt_decode(cookies.idToken) as User;
const userInfo = jwt_decode<User>(cookies.idToken);
const decodedAccessToken = jwt_decode(cookies.token) as decodedAccessToken;

if (Date.now() >= decodedAccessToken.exp * 1000) {
Expand All @@ -58,7 +58,7 @@ const getUser = async (cookies: Cookies) => {
const useGetUserQuery = () => {
const { cookies } = useCookiesWithOptions(['idToken']);

return useAuthenticatedQuery({
return useAuthenticatedQueryV2({
queryKey: ['user'],
queryFn: () => getUser(cookies),
});
Expand All @@ -70,7 +70,7 @@ const useGetUserQueryServerSide = (
) => {
const cookies = req.cookies;

return useAuthenticatedQuery({
return prefetchAuthenticatedQuery({
req,
queryClient,
queryKey: ['user'],
Expand All @@ -84,16 +84,18 @@ const getPermissions = async ({ headers }) => {
path: '/user/permissions/',
options: { headers },
});

if (isErrorObject(res)) {
// eslint-disable-next-line no-console
console.error(res);
return;
}

return (await res.json()) as string[];
};

const useGetPermissionsQuery = (configuration = {}) =>
useAuthenticatedQuery({
useAuthenticatedQueryV2({
queryKey: ['user', 'permissions'],
queryFn: getPermissions,
...configuration,
Expand All @@ -117,7 +119,7 @@ const getRoles = async ({ headers }) => {
};

const useGetRolesQuery = (configuration = {}) =>
useAuthenticatedQuery({
useAuthenticatedQueryV2({
queryKey: ['user', 'roles'],
queryFn: getRoles,
...configuration,
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useFeatureFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,5 @@ export {
isFeatureFlagEnabledInCookies,
useFeatureFlag,
};

export type { FeatureFlagName };
Loading

0 comments on commit 63dc168

Please sign in to comment.