2024-07-15 11:04:47 +03:00

54 lines
1.4 KiB
TypeScript

import { getUser } from '@/api/user/query';
import { adminRoles, defaultRoles, unlimitedRoles } from '@/config/users';
import * as CRMTypes from '@/graphql/crm.types';
import type { ApolloClient, NormalizedCache } from '@apollo/client';
import type { QueryClient } from '@tanstack/react-query';
import { sift } from 'radash';
type GetUserTypeProps = {
cookie: string;
};
type UserType = {
admin: boolean;
default: boolean;
unlimited: boolean;
};
type MakeGetUserTypeProps = {
apolloClient: ApolloClient<NormalizedCache>;
queryClient: QueryClient;
};
export function makeGetUserType({ apolloClient, queryClient }: MakeGetUserTypeProps) {
return async function ({ cookie }: GetUserTypeProps): Promise<UserType> {
const user = await queryClient.fetchQuery(['user'], ({ signal }) =>
getUser({
headers: {
cookie,
},
signal,
})
);
const {
data: { systemusers },
} = await apolloClient.query({
fetchPolicy: 'network-only',
query: CRMTypes.GetSystemUserDocument,
variables: {
domainname: user.domainName,
},
});
const systemuser = systemusers?.[0];
const roles = systemuser?.roles ? sift(systemuser?.roles)?.map((x) => x?.name) : [];
return {
admin: adminRoles.some((x) => roles?.includes(x)),
default: defaultRoles.some((x) => roles?.includes(x)),
unlimited: unlimitedRoles.some((x) => roles?.includes(x)),
};
};
}