Workspace member (#552)

* fix: clean small back-end issues

* fix: apollo factory causing infinite loop on token renew

* feat: small refactor and add ability to remove workspace member

* fix: test
This commit is contained in:
Jérémy M 2023-07-10 11:25:11 +02:00 committed by GitHub
parent f2c49907a8
commit c529c49ea6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 316 additions and 97 deletions

View File

@ -1112,7 +1112,8 @@ export type EnumPipelineProgressableTypeFilter = {
};
export enum FileFolder {
ProfilePicture = 'ProfilePicture'
ProfilePicture = 'ProfilePicture',
WorkspaceLogo = 'WorkspaceLogo'
}
export type IntNullableFilter = {
@ -1160,6 +1161,7 @@ export type Mutation = {
deleteManyCompany: AffectedRows;
deleteManyPerson: AffectedRows;
deleteManyPipelineProgress: AffectedRows;
deleteWorkspaceMember: WorkspaceMember;
renewToken: AuthTokens;
updateOneCommentThread: CommentThread;
updateOneCompany?: Maybe<Company>;
@ -1232,6 +1234,11 @@ export type MutationDeleteManyPipelineProgressArgs = {
};
export type MutationDeleteWorkspaceMemberArgs = {
where: WorkspaceMemberWhereUniqueInput;
};
export type MutationRenewTokenArgs = {
refreshToken: Scalars['String'];
};
@ -2430,6 +2437,7 @@ export type Query = {
findManyPipelineProgress: Array<PipelineProgress>;
findManyPipelineStage: Array<PipelineStage>;
findManyUser: Array<User>;
findManyWorkspaceMember: Array<WorkspaceMember>;
findUniqueCompany: Company;
findUniquePerson: Person;
};
@ -2510,6 +2518,16 @@ export type QueryFindManyUserArgs = {
};
export type QueryFindManyWorkspaceMemberArgs = {
cursor?: InputMaybe<WorkspaceMemberWhereUniqueInput>;
distinct?: InputMaybe<Array<WorkspaceMemberScalarFieldEnum>>;
orderBy?: InputMaybe<Array<WorkspaceMemberOrderByWithRelationInput>>;
skip?: InputMaybe<Scalars['Int']>;
take?: InputMaybe<Scalars['Int']>;
where?: InputMaybe<WorkspaceMemberWhereInput>;
};
export type QueryFindUniqueCompanyArgs = {
id: Scalars['String'];
};
@ -2930,6 +2948,23 @@ export type WorkspaceMemberCreateWithoutWorkspaceInput = {
user: UserCreateNestedOneWithoutWorkspaceMemberInput;
};
export type WorkspaceMemberOrderByWithRelationInput = {
createdAt?: InputMaybe<SortOrder>;
id?: InputMaybe<SortOrder>;
updatedAt?: InputMaybe<SortOrder>;
user?: InputMaybe<UserOrderByWithRelationInput>;
userId?: InputMaybe<SortOrder>;
};
export enum WorkspaceMemberScalarFieldEnum {
CreatedAt = 'createdAt',
DeletedAt = 'deletedAt',
Id = 'id',
UpdatedAt = 'updatedAt',
UserId = 'userId',
WorkspaceId = 'workspaceId'
}
export type WorkspaceMemberScalarWhereInput = {
AND?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>;
NOT?: InputMaybe<Array<WorkspaceMemberScalarWhereInput>>;
@ -2983,6 +3018,17 @@ export type WorkspaceMemberUpsertWithWhereUniqueWithoutWorkspaceInput = {
where: WorkspaceMemberWhereUniqueInput;
};
export type WorkspaceMemberWhereInput = {
AND?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
NOT?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
OR?: InputMaybe<Array<WorkspaceMemberWhereInput>>;
createdAt?: InputMaybe<DateTimeFilter>;
id?: InputMaybe<StringFilter>;
updatedAt?: InputMaybe<DateTimeFilter>;
user?: InputMaybe<UserRelationFilter>;
userId?: InputMaybe<StringFilter>;
};
export type WorkspaceMemberWhereUniqueInput = {
id?: InputMaybe<Scalars['String']>;
userId?: InputMaybe<Scalars['String']>;
@ -3330,10 +3376,10 @@ export type RemoveProfilePictureMutationVariables = Exact<{
export type RemoveProfilePictureMutation = { __typename?: 'Mutation', updateUser: { __typename?: 'User', id: string } };
export type GetCurrentWorkspaceQueryVariables = Exact<{ [key: string]: never; }>;
export type GetWorkspaceMembersQueryVariables = Exact<{ [key: string]: never; }>;
export type GetCurrentWorkspaceQuery = { __typename?: 'Query', currentWorkspace: { __typename?: 'Workspace', id: string, workspaceMember?: Array<{ __typename?: 'WorkspaceMember', id: string, user: { __typename?: 'User', id: string, email: string, avatarUrl?: string | null, firstName?: string | null, lastName?: string | null } }> | null } };
export type GetWorkspaceMembersQuery = { __typename?: 'Query', workspaceMembers: Array<{ __typename?: 'WorkspaceMember', id: string, user: { __typename?: 'User', id: string, email: string, avatarUrl?: string | null, firstName?: string | null, lastName?: string | null } }> };
export type UpdateWorkspaceMutationVariables = Exact<{
data: WorkspaceUpdateInput;
@ -3354,6 +3400,13 @@ export type RemoveWorkspaceLogoMutationVariables = Exact<{ [key: string]: never;
export type RemoveWorkspaceLogoMutation = { __typename?: 'Mutation', updateWorkspace: { __typename?: 'Workspace', id: string } };
export type RemoveWorkspaceMemberMutationVariables = Exact<{
where: WorkspaceMemberWhereUniqueInput;
}>;
export type RemoveWorkspaceMemberMutation = { __typename?: 'Mutation', deleteWorkspaceMember: { __typename?: 'WorkspaceMember', id: string } };
export const CreateEventDocument = gql`
mutation CreateEvent($type: String!, $data: JSON!) {
@ -5041,50 +5094,47 @@ export function useRemoveProfilePictureMutation(baseOptions?: Apollo.MutationHoo
export type RemoveProfilePictureMutationHookResult = ReturnType<typeof useRemoveProfilePictureMutation>;
export type RemoveProfilePictureMutationResult = Apollo.MutationResult<RemoveProfilePictureMutation>;
export type RemoveProfilePictureMutationOptions = Apollo.BaseMutationOptions<RemoveProfilePictureMutation, RemoveProfilePictureMutationVariables>;
export const GetCurrentWorkspaceDocument = gql`
query GetCurrentWorkspace {
currentWorkspace {
export const GetWorkspaceMembersDocument = gql`
query GetWorkspaceMembers {
workspaceMembers: findManyWorkspaceMember {
id
workspaceMember {
user {
id
user {
id
email
avatarUrl
firstName
lastName
}
email
avatarUrl
firstName
lastName
}
}
}
`;
/**
* __useGetCurrentWorkspaceQuery__
* __useGetWorkspaceMembersQuery__
*
* To run a query within a React component, call `useGetCurrentWorkspaceQuery` and pass it any options that fit your needs.
* When your component renders, `useGetCurrentWorkspaceQuery` returns an object from Apollo Client that contains loading, error, and data properties
* To run a query within a React component, call `useGetWorkspaceMembersQuery` and pass it any options that fit your needs.
* When your component renders, `useGetWorkspaceMembersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetCurrentWorkspaceQuery({
* const { data, loading, error } = useGetWorkspaceMembersQuery({
* variables: {
* },
* });
*/
export function useGetCurrentWorkspaceQuery(baseOptions?: Apollo.QueryHookOptions<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>) {
export function useGetWorkspaceMembersQuery(baseOptions?: Apollo.QueryHookOptions<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>(GetCurrentWorkspaceDocument, options);
return Apollo.useQuery<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>(GetWorkspaceMembersDocument, options);
}
export function useGetCurrentWorkspaceLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>) {
export function useGetWorkspaceMembersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>(GetCurrentWorkspaceDocument, options);
return Apollo.useLazyQuery<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>(GetWorkspaceMembersDocument, options);
}
export type GetCurrentWorkspaceQueryHookResult = ReturnType<typeof useGetCurrentWorkspaceQuery>;
export type GetCurrentWorkspaceLazyQueryHookResult = ReturnType<typeof useGetCurrentWorkspaceLazyQuery>;
export type GetCurrentWorkspaceQueryResult = Apollo.QueryResult<GetCurrentWorkspaceQuery, GetCurrentWorkspaceQueryVariables>;
export type GetWorkspaceMembersQueryHookResult = ReturnType<typeof useGetWorkspaceMembersQuery>;
export type GetWorkspaceMembersLazyQueryHookResult = ReturnType<typeof useGetWorkspaceMembersLazyQuery>;
export type GetWorkspaceMembersQueryResult = Apollo.QueryResult<GetWorkspaceMembersQuery, GetWorkspaceMembersQueryVariables>;
export const UpdateWorkspaceDocument = gql`
mutation UpdateWorkspace($data: WorkspaceUpdateInput!) {
updateWorkspace(data: $data) {
@ -5183,4 +5233,37 @@ export function useRemoveWorkspaceLogoMutation(baseOptions?: Apollo.MutationHook
}
export type RemoveWorkspaceLogoMutationHookResult = ReturnType<typeof useRemoveWorkspaceLogoMutation>;
export type RemoveWorkspaceLogoMutationResult = Apollo.MutationResult<RemoveWorkspaceLogoMutation>;
export type RemoveWorkspaceLogoMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceLogoMutation, RemoveWorkspaceLogoMutationVariables>;
export type RemoveWorkspaceLogoMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceLogoMutation, RemoveWorkspaceLogoMutationVariables>;
export const RemoveWorkspaceMemberDocument = gql`
mutation RemoveWorkspaceMember($where: WorkspaceMemberWhereUniqueInput!) {
deleteWorkspaceMember(where: $where) {
id
}
}
`;
export type RemoveWorkspaceMemberMutationFn = Apollo.MutationFunction<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>;
/**
* __useRemoveWorkspaceMemberMutation__
*
* To run a mutation, you first call `useRemoveWorkspaceMemberMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useRemoveWorkspaceMemberMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [removeWorkspaceMemberMutation, { data, loading, error }] = useRemoveWorkspaceMemberMutation({
* variables: {
* where: // value for 'where'
* },
* });
*/
export function useRemoveWorkspaceMemberMutation(baseOptions?: Apollo.MutationHookOptions<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>(RemoveWorkspaceMemberDocument, options);
}
export type RemoveWorkspaceMemberMutationHookResult = ReturnType<typeof useRemoveWorkspaceMemberMutation>;
export type RemoveWorkspaceMemberMutationResult = Apollo.MutationResult<RemoveWorkspaceMemberMutation>;
export type RemoveWorkspaceMemberMutationOptions = Apollo.BaseMutationOptions<RemoveWorkspaceMemberMutation, RemoveWorkspaceMemberMutationVariables>;

View File

@ -1,4 +1,4 @@
import { useMemo, useRef } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import { InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { useRecoilState } from 'recoil';
@ -38,6 +38,8 @@ export function useApolloFactory() {
fetchPolicy: 'cache-first',
},
},
// We don't want to re-create the client on token change or it will cause infinite loop
initialTokenPair: tokenPair,
onTokenPairChange(tokenPair) {
setTokenPair(tokenPair);
},
@ -46,11 +48,17 @@ export function useApolloFactory() {
},
extraLinks: [],
isDebugMode,
tokenPair,
});
return apolloRef.current.getClient();
}, [setTokenPair, isDebugMode, tokenPair]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setTokenPair, isDebugMode]);
useEffect(() => {
if (apolloRef.current) {
apolloRef.current.updateTokenPair(tokenPair);
}
}, [tokenPair]);
return apolloClient;
}

View File

@ -28,9 +28,9 @@ export interface Options<TCacheShape> extends ApolloClientOptions<TCacheShape> {
onNetworkError?: (err: Error | ServerParseError | ServerError) => void;
onTokenPairChange?: (tokenPair: AuthTokenPair) => void;
onUnauthenticatedError?: () => void;
initialTokenPair: AuthTokenPair | null;
extraLinks?: ApolloLink[];
isDebugMode?: boolean;
tokenPair: AuthTokenPair | null;
}
export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
@ -44,13 +44,13 @@ export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
onNetworkError,
onTokenPairChange,
onUnauthenticatedError,
initialTokenPair,
extraLinks,
isDebugMode,
tokenPair,
...options
} = opts;
this.tokenPair = tokenPair;
this.tokenPair = initialTokenPair;
const buildApolloLink = (): ApolloLink => {
const httpLink = createUploadLink({

View File

@ -15,14 +15,14 @@ type Size = 'medium' | 'small';
type Props = {
icon?: React.ReactNode;
title: string;
title?: string;
fullWidth?: boolean;
variant?: Variant;
size?: Size;
} & React.ComponentProps<'button'>;
const StyledButton = styled.button<
Pick<Props, 'fullWidth' | 'variant' | 'size'>
Pick<Props, 'fullWidth' | 'variant' | 'size' | 'title'>
>`
align-items: center;
background: ${({ theme, variant, disabled }) => {
@ -33,8 +33,10 @@ const StyledButton = styled.button<
} else {
return theme.color.blue;
}
default:
case 'secondary':
return theme.background.primary;
default:
return 'transparent';
}
}};
border: ${({ theme, variant }) => {
@ -93,7 +95,13 @@ const StyledButton = styled.button<
gap: ${({ theme }) => theme.spacing(2)};
height: ${({ size }) => (size === 'small' ? '24px' : '32px')};
justify-content: flex-start;
padding: ${({ theme }) => theme.spacing(2)} ${({ theme }) => theme.spacing(3)};
padding: ${({ theme, title }) => {
if (!title) {
return `${theme.spacing(1)}`;
}
return `${theme.spacing(2)} ${theme.spacing(3)}`;
}};
transition: background 0.1s ease;
@ -143,6 +151,7 @@ export function Button({
fullWidth={fullWidth}
variant={variant}
size={size}
title={title}
{...props}
>
{icon}

View File

@ -6,5 +6,6 @@ export function getImageAbsoluteURIOrBase64(imageUrl?: string | null) {
if (imageUrl?.startsWith('data:')) {
return imageUrl;
}
return `${process.env.REACT_APP_FILES_URL}/${imageUrl}`;
}

View File

@ -12,21 +12,15 @@ const StyledContainer = styled.div`
flex-direction: row;
margin-bottom: ${({ theme }) => theme.spacing(0)};
margin-top: ${({ theme }) => theme.spacing(4)};
padding: ${({ theme }) => theme.spacing(3)};
`;
const AvatarContainer = styled.div`
margin: ${({ theme }) => theme.spacing(3)};
`;
const TextContainer = styled.div`
const Content = styled.div`
display: flex;
flex: 1;
flex-direction: column;
justify-content: center;
`;
const NameAndEmailContainer = styled.div`
display: flex;
flex-direction: column;
margin-left: ${({ theme }) => theme.spacing(3)};
`;
const NameText = styled.span`
@ -41,29 +35,26 @@ type OwnProps = {
workspaceMember: {
user: Pick<User, 'firstName' | 'lastName' | 'avatarUrl' | 'email'>;
};
accessory?: React.ReactNode;
};
export function WorkspaceMemberCard({ workspaceMember }: OwnProps) {
export function WorkspaceMemberCard({ workspaceMember, accessory }: OwnProps) {
return (
<StyledContainer>
<AvatarContainer>
<Avatar
avatarUrl={getImageAbsoluteURIOrBase64(
workspaceMember.user.avatarUrl,
)}
placeholder={workspaceMember.user.firstName || ''}
type="squared"
size={40}
/>
</AvatarContainer>
<TextContainer>
<NameAndEmailContainer>
<NameText>
{workspaceMember.user.firstName} {workspaceMember.user.lastName}{' '}
</NameText>
<EmailText>{workspaceMember.user.email}</EmailText>
</NameAndEmailContainer>
</TextContainer>
<Avatar
avatarUrl={getImageAbsoluteURIOrBase64(workspaceMember.user.avatarUrl)}
placeholder={workspaceMember.user.firstName || ''}
type="squared"
size={40}
/>
<Content>
<NameText>
{workspaceMember.user.firstName} {workspaceMember.user.lastName}{' '}
</NameText>
<EmailText>{workspaceMember.user.email}</EmailText>
</Content>
{accessory}
</StyledContainer>
);
}

View File

@ -1,18 +1,15 @@
import { gql } from '@apollo/client';
export const GET_CURRENT_WORKSPACE = gql`
query GetCurrentWorkspace {
currentWorkspace {
export const GET_WORKSPACE_MEMBERS = gql`
query GetWorkspaceMembers {
workspaceMembers: findManyWorkspaceMember {
id
workspaceMember {
user {
id
user {
id
email
avatarUrl
firstName
lastName
}
email
avatarUrl
firstName
lastName
}
}
}

View File

@ -24,3 +24,11 @@ export const REMOVE_WORKSPACE_LOGO = gql`
}
}
`;
export const REMOVE_WORKSPACE_MEMBER = gql`
mutation RemoveWorkspaceMember($where: WorkspaceMemberWhereUniqueInput!) {
deleteWorkspaceMember(where: $where) {
id
}
}
`;

View File

@ -1,10 +1,17 @@
import styled from '@emotion/styled';
import { useRecoilState } from 'recoil';
import { currentUserState } from '@/auth/states/currentUserState';
import { Button } from '@/ui/components/buttons/Button';
import { MainSectionTitle } from '@/ui/components/section-titles/MainSectionTitle';
import { SubSectionTitle } from '@/ui/components/section-titles/SubSectionTitle';
import { IconTrash } from '@/ui/icons';
import { NoTopBarContainer } from '@/ui/layout/containers/NoTopBarContainer';
import { WorkspaceMemberCard } from '@/workspace/components/WorkspaceMemberCard';
import { useGetCurrentWorkspaceQuery } from '~/generated/graphql';
import {
useGetWorkspaceMembersQuery,
useRemoveWorkspaceMemberMutation,
} from '~/generated/graphql';
const StyledContainer = styled.div`
display: flex;
@ -16,8 +23,52 @@ const StyledContainer = styled.div`
}
`;
const ButtonContainer = styled.div`
align-items: center;
display: flex;
flex-direction: row;
margin-left: ${({ theme }) => theme.spacing(3)};
`;
export function SettingsWorkspaceMembers() {
const { data } = useGetCurrentWorkspaceQuery();
const [currentUser] = useRecoilState(currentUserState);
const { data } = useGetWorkspaceMembersQuery();
const [removeWorkspaceMember] = useRemoveWorkspaceMemberMutation();
const handleRemoveWorkspaceMember = async (userId: string) => {
await removeWorkspaceMember({
variables: {
where: {
userId,
},
},
optimisticResponse: {
__typename: 'Mutation',
deleteWorkspaceMember: {
__typename: 'WorkspaceMember',
id: userId,
},
},
update: (cache, { data: responseData }) => {
if (!responseData) {
return;
}
const normalizedId = cache.identify({
id: responseData.deleteWorkspaceMember.id,
__typename: 'WorkspaceMember',
});
// Evict object from cache
cache.evict({ id: normalizedId });
// Clean up relation to this object
cache.gc();
},
});
};
return (
<NoTopBarContainer>
@ -27,10 +78,22 @@ export function SettingsWorkspaceMembers() {
title="Members"
description="Manage the members of your space here"
/>
{data?.currentWorkspace?.workspaceMember?.map((member) => (
{data?.workspaceMembers?.map((member) => (
<WorkspaceMemberCard
key={member.user.id}
workspaceMember={{ user: member.user }}
accessory={
currentUser?.id !== member.user.id && (
<ButtonContainer>
<Button
onClick={() => handleRemoveWorkspaceMember(member.user.id)}
variant="tertiary"
size="small"
icon={<IconTrash size={16} />}
/>
</ButtonContainer>
)
}
/>
))}
</StyledContainer>

View File

@ -58,7 +58,9 @@ export class AbilityFactory {
can(AbilityAction.Update, 'Workspace', { id: workspace.id });
// Workspace Member
can(AbilityAction.Read, 'WorkspaceMember', { userId: user.id });
can(AbilityAction.Read, 'WorkspaceMember', { workspaceId: workspace.id });
can(AbilityAction.Delete, 'WorkspaceMember', { workspaceId: workspace.id });
cannot(AbilityAction.Delete, 'WorkspaceMember', { userId: user.id });
// Company
can(AbilityAction.Read, 'Company', { workspaceId: workspace.id });

View File

@ -1,12 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { WorkspaceMemberResolver } from './workspace-member.resolver';
import { WorkspaceMemberService } from '../services/workspace-member.service';
import { AbilityFactory } from 'src/ability/ability.factory';
describe('WorkspaceMemberResolver', () => {
let resolver: WorkspaceMemberResolver;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [WorkspaceMemberResolver],
providers: [
WorkspaceMemberResolver,
{
provide: WorkspaceMemberService,
useValue: {},
},
{
provide: AbilityFactory,
useValue: {},
},
],
}).compile();
resolver = module.get<WorkspaceMemberResolver>(WorkspaceMemberResolver);

View File

@ -1,5 +1,62 @@
import { Resolver } from '@nestjs/graphql';
import { Args, Query, Resolver, Mutation } from '@nestjs/graphql';
import { WorkspaceMember } from '../../@generated/workspace-member/workspace-member.model';
import { UseGuards } from '@nestjs/common';
import { AbilityGuard } from 'src/guards/ability.guard';
import { CheckAbilities } from 'src/decorators/check-abilities.decorator';
import {
DeleteWorkspaceMemberAbilityHandler,
ReadWorkspaceMemberAbilityHandler,
} from 'src/ability/handlers/workspace-member.ability-handler';
import { FindManyWorkspaceMemberArgs } from 'src/core/@generated/workspace-member/find-many-workspace-member.args';
import { UserAbility } from 'src/decorators/user-ability.decorator';
import { AppAbility } from 'src/ability/ability.factory';
import {
PrismaSelect,
PrismaSelector,
} from 'src/decorators/prisma-select.decorator';
import { WorkspaceMemberService } from '../services/workspace-member.service';
import { accessibleBy } from '@casl/prisma';
import { DeleteOneWorkspaceMemberArgs } from 'src/core/@generated/workspace-member/delete-one-workspace-member.args';
import { JwtAuthGuard } from 'src/guards/jwt.auth.guard';
@UseGuards(JwtAuthGuard)
@Resolver(() => WorkspaceMember)
export class WorkspaceMemberResolver {}
export class WorkspaceMemberResolver {
constructor(
private readonly workspaceMemberService: WorkspaceMemberService,
) {}
@Query(() => [WorkspaceMember])
@UseGuards(AbilityGuard)
@CheckAbilities(ReadWorkspaceMemberAbilityHandler)
async findManyWorkspaceMember(
@Args() args: FindManyWorkspaceMemberArgs,
@UserAbility() ability: AppAbility,
@PrismaSelector({ modelName: 'WorkspaceMember' })
prismaSelect: PrismaSelect<'WorkspaceMember'>,
): Promise<Partial<WorkspaceMember>[]> {
return this.workspaceMemberService.findMany({
...args,
where: args.where
? {
AND: [args.where, accessibleBy(ability).WorkspaceMember],
}
: accessibleBy(ability).WorkspaceMember,
select: prismaSelect.value,
});
}
@Mutation(() => WorkspaceMember)
@UseGuards(AbilityGuard)
@CheckAbilities(DeleteWorkspaceMemberAbilityHandler)
async deleteWorkspaceMember(
@Args() args: DeleteOneWorkspaceMemberArgs,
@PrismaSelector({ modelName: 'WorkspaceMember' })
prismaSelect: PrismaSelect<'WorkspaceMember'>,
): Promise<Partial<WorkspaceMember>> {
return this.workspaceMemberService.delete({
where: args.where,
select: prismaSelect.value,
});
}
}

View File

@ -50,8 +50,8 @@ export class WorkspaceResolver {
@Query(() => Workspace)
async currentWorkspace(
@AuthWorkspace() workspace: Workspace,
@PrismaSelector({ modelName: 'User' })
prismaSelect: PrismaSelect<'User'>,
@PrismaSelector({ modelName: 'Workspace' })
prismaSelect: PrismaSelect<'Workspace'>,
) {
const selectedWorkspace = await this.workspaceService.findUnique({
where: {

View File

@ -1,12 +0,0 @@
import { CanActivate, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
@Injectable()
export class ShowOneGuard implements CanActivate {
constructor(private prismaService: PrismaService) {}
async canActivate(): Promise<boolean> {
// TODO
return true;
}
}