Use Graphql types in FE and complete mappers removal (#348)

Fix Typescript build issues
This commit is contained in:
Charles Bochet
2023-06-21 10:52:00 -07:00
committed by GitHub
parent b179d1f1f0
commit 8a330b9746
35 changed files with 398 additions and 574 deletions

View File

@ -1,8 +1,16 @@
import { atom } from 'recoil';
import { User } from '@/users/interfaces/user.interface';
import { User, Workspace, WorkspaceMember } from '~/generated/graphql';
export const currentUserState = atom<User | null>({
type CurrentUser = Pick<User, 'id' | 'email' | 'displayName'> & {
workspaceMember?:
| (Pick<WorkspaceMember, 'id'> & {
workspace: Pick<Workspace, 'id' | 'displayName' | 'logo'>;
})
| null;
};
export const currentUserState = atom<CurrentUser | null>({
key: 'currentUserState',
default: null,
});

View File

@ -2,19 +2,24 @@ import { CellCommentChip } from '@/comments/components/CellCommentChip';
import { useOpenCommentRightDrawer } from '@/comments/hooks/useOpenCommentRightDrawer';
import EditableChip from '@/ui/components/editable-cell/types/EditableChip';
import { getLogoUrlFromDomainName } from '@/utils/utils';
import { CommentableType } from '~/generated/graphql';
import { Company } from '../interfaces/company.interface';
import { updateCompany } from '../services';
import {
CommentableType,
GetCompaniesQuery,
useUpdateCompanyMutation,
} from '~/generated/graphql';
import CompanyChip from './CompanyChip';
type OwnProps = {
company: Company;
company: Pick<
GetCompaniesQuery['companies'][0],
'id' | 'name' | 'domainName' | '_commentCount' | 'accountOwner'
>;
};
export function CompanyEditableNameChipCell({ company }: OwnProps) {
const openCommentRightDrawer = useOpenCommentRightDrawer();
const [updateCompany] = useUpdateCompanyMutation();
function handleCommentClick(event: React.MouseEvent<HTMLDivElement>) {
event.preventDefault();
@ -35,8 +40,11 @@ export function CompanyEditableNameChipCell({ company }: OwnProps) {
picture={getLogoUrlFromDomainName(company.domainName)}
changeHandler={(value: string) => {
updateCompany({
...company,
name: value,
variables: {
...company,
name: value,
accountOwnerId: company.accountOwner?.id,
},
});
}}
ChipComponent={CompanyChip}

View File

@ -1,13 +0,0 @@
import { Company as GQLCompany } from '../../../generated/graphql';
import { DeepPartial } from '../../utils/utils';
export type Company = DeepPartial<GQLCompany> & { id: string };
export type GraphqlQueryCompany = Company;
export type GraphqlMutationCompany = Company;
export const mapToCompany = (company: GraphqlQueryCompany): Company => company;
export const mapToGqlCompany = (company: Company): GraphqlMutationCompany =>
company;

View File

@ -1,12 +1,4 @@
import { FetchResult, gql } from '@apollo/client';
import { getOperationName } from '@apollo/client/utilities';
import { apiClient } from '~/apollo';
import { UpdateCompanyMutationVariables } from '../../../generated/graphql';
import { Company, mapToGqlCompany } from '../interfaces/company.interface';
import { GET_COMPANIES } from './select';
import { gql } from '@apollo/client';
export const UPDATE_COMPANY = gql`
mutation UpdateCompany(
@ -80,36 +72,3 @@ export const DELETE_COMPANIES = gql`
}
}
`;
export async function updateCompany(
company: UpdateCompanyMutationVariables,
): Promise<FetchResult<Company>> {
const result = await apiClient.mutate({
mutation: UPDATE_COMPANY,
variables: company,
});
return result;
}
export async function insertCompany(
company: Company,
): Promise<FetchResult<Company>> {
const result = await apiClient.mutate({
mutation: INSERT_COMPANY,
variables: mapToGqlCompany(company),
refetchQueries: [getOperationName(GET_COMPANIES) ?? ''],
});
return result;
}
export async function deleteCompanies(
peopleIds: string[],
): Promise<FetchResult<Company>> {
const result = await apiClient.mutate({
mutation: DELETE_COMPANIES,
variables: { ids: peopleIds },
});
return result;
}

View File

@ -1,23 +1,17 @@
import { SortOrder as Order_By } from '~/generated/graphql';
import { BoolExpType } from '../utils/interfaces/generic.interface';
import {
FilterableFieldsType,
FilterWhereType,
SelectedFilterType,
} from './interfaces/filters/interface';
import { SelectedSortType } from './interfaces/sorts/interface';
export const reduceFiltersToWhere = <
ValueType extends FilterableFieldsType,
WhereTemplateType extends FilterWhereType,
>(
filters: Array<SelectedFilterType<ValueType, WhereTemplateType>>,
): BoolExpType<WhereTemplateType> => {
export const reduceFiltersToWhere = <WhereTemplateType extends FilterWhereType>(
filters: Array<SelectedFilterType<WhereTemplateType>>,
): Record<string, any> => {
const where = filters.reduce((acc, filter) => {
return { ...acc, ...filter.operand.whereTemplate(filter.value) };
}, {} as BoolExpType<WhereTemplateType>);
}, {} as Record<string, any>);
return where;
};

View File

@ -1,80 +1,64 @@
import { ReactNode } from 'react';
import { SearchConfigType } from '@/search/interfaces/interface';
import {
AnyEntity,
BoolExpType,
UnknownType,
} from '@/utils/interfaces/generic.interface';
export type FilterableFieldsType = AnyEntity;
export type FilterWhereRelationType = AnyEntity;
export type FilterWhereType = FilterWhereRelationType | string | UnknownType;
export type FilterableFieldsType = any;
export type FilterWhereRelationType = any;
export type FilterWhereType = FilterWhereRelationType | string | unknown;
export type FilterConfigType<
FilteredType extends FilterableFieldsType,
WhereType extends FilterWhereType = UnknownType,
> = {
export type FilterConfigType<WhereType extends FilterWhereType = unknown> = {
key: string;
label: string;
icon: ReactNode;
type: WhereType extends UnknownType
type: WhereType extends unknown
? 'relation' | 'text' | 'date'
: WhereType extends AnyEntity
: WhereType extends any
? 'relation'
: WhereType extends string
? 'text' | 'date'
: never;
operands: FilterOperandType<FilteredType, WhereType>[];
} & (WhereType extends UnknownType
? { searchConfig?: SearchConfigType<UnknownType> }
: WhereType extends AnyEntity
? { searchConfig: SearchConfigType<WhereType> }
operands: FilterOperandType<WhereType>[];
} & (WhereType extends unknown
? { searchConfig?: SearchConfigType }
: WhereType extends any
? { searchConfig: SearchConfigType }
: WhereType extends string
? object
: never) &
(WhereType extends UnknownType
(WhereType extends unknown
? { selectedValueRender?: (selected: any) => string }
: WhereType extends AnyEntity
: WhereType extends any
? { selectedValueRender: (selected: WhereType) => string }
: WhereType extends string
? object
: never);
export type FilterOperandType<
FilteredType extends FilterableFieldsType,
WhereType extends FilterWhereType = UnknownType,
> = WhereType extends UnknownType
? any
: WhereType extends FilterWhereRelationType
? FilterOperandRelationType<FilteredType, WhereType>
: WhereType extends string
? FilterOperandFieldType<FilteredType>
: never;
export type FilterOperandType<WhereType extends FilterWhereType = unknown> =
WhereType extends unknown
? any
: WhereType extends FilterWhereRelationType
? FilterOperandRelationType<WhereType>
: WhereType extends string
? FilterOperandFieldType
: never;
type FilterOperandRelationType<
FilteredType extends FilterableFieldsType,
WhereType extends FilterWhereType,
> = {
type FilterOperandRelationType<WhereType extends FilterWhereType> = {
label: 'Is' | 'Is not';
id: 'is' | 'is_not';
whereTemplate: (value: WhereType) => BoolExpType<FilteredType>;
whereTemplate: (value: WhereType) => any;
};
type FilterOperandFieldType<FilteredType extends FilterableFieldsType> = {
type FilterOperandFieldType = {
label: 'Contains' | 'Does not contain' | 'Greater than' | 'Less than';
id: 'like' | 'not_like' | 'greater_than' | 'less_than';
whereTemplate: (value: string) => BoolExpType<FilteredType>;
whereTemplate: (value: string) => any;
};
export type SelectedFilterType<
FilteredType extends FilterableFieldsType,
WhereType extends FilterWhereType = UnknownType,
> = {
export type SelectedFilterType<WhereType> = {
key: string;
value: WhereType extends UnknownType ? any : WhereType;
value: WhereType;
displayValue: string;
label: string;
icon: ReactNode;
operand: FilterOperandType<FilteredType, WhereType>;
operand: FilterOperandType<WhereType>;
};

View File

@ -4,14 +4,12 @@ import styled from '@emotion/styled';
import { CellCommentChip } from '@/comments/components/CellCommentChip';
import { useOpenCommentRightDrawer } from '@/comments/hooks/useOpenCommentRightDrawer';
import { EditableDoubleText } from '@/ui/components/editable-cell/types/EditableDoubleText';
import { CommentableType } from '~/generated/graphql';
import { Person } from '../interfaces/person.interface';
import { CommentableType, Person } from '~/generated/graphql';
import { PersonChip } from './PersonChip';
type OwnProps = {
person: Person;
person: Pick<Person, 'id' | 'firstname' | 'lastname' | '_commentCount'>;
onChange: (firstname: string, lastname: string) => void;
};

View File

@ -4,27 +4,25 @@ import { v4 } from 'uuid';
import CompanyChip, {
CompanyChipPropsType,
} from '@/companies/components/CompanyChip';
import {
Company,
mapToCompany,
} from '@/companies/interfaces/company.interface';
import { SearchConfigType } from '@/search/interfaces/interface';
import { SEARCH_COMPANY_QUERY } from '@/search/services/search';
import { EditableRelation } from '@/ui/components/editable-cell/types/EditableRelation';
import { logError } from '@/utils/logs/logError';
import { getLogoUrlFromDomainName } from '@/utils/utils';
import {
Company,
Person,
QueryMode,
useInsertCompanyMutation,
useUpdatePeopleMutation,
} from '~/generated/graphql';
import { mapToGqlPerson, Person } from '../interfaces/person.interface';
import { PeopleCompanyCreateCell } from './PeopleCompanyCreateCell';
export type OwnProps = {
people: Person;
people: Pick<Person, 'id'> & {
company?: Pick<Company, 'id' | 'name'> | null;
};
};
export function PeopleCompanyCell({ people }: OwnProps) {
@ -52,7 +50,7 @@ export function PeopleCompanyCell({ people }: OwnProps) {
await updatePeople({
variables: {
...mapToGqlPerson(people),
...people,
companyId: newCompanyId,
},
});
@ -75,7 +73,7 @@ export function PeopleCompanyCell({ people }: OwnProps) {
onCreate={handleCompanyCreate}
/>
) : (
<EditableRelation<Company, CompanyChipPropsType>
<EditableRelation<any, CompanyChipPropsType>
relation={people.company}
searchPlaceholder="Company"
ChipComponent={CompanyChip}
@ -88,7 +86,7 @@ export function PeopleCompanyCell({ people }: OwnProps) {
onChange={async (relation) => {
await updatePeople({
variables: {
...mapToGqlPerson(people),
...people,
companyId: relation.id,
},
});
@ -101,10 +99,10 @@ export function PeopleCompanyCell({ people }: OwnProps) {
name: { contains: `%${searchInput}%`, mode: QueryMode.Insensitive },
}),
resultMapper: (company) => ({
render: (company) => company.name,
value: mapToCompany(company),
render: (company: any) => company.name,
value: company,
}),
} satisfies SearchConfigType<Company>
} satisfies SearchConfigType
}
onCreate={() => {
setIsCreating(true);

View File

@ -1,12 +0,0 @@
import { Person as GQLPerson } from '../../../generated/graphql';
import { DeepPartial } from '../../utils/utils';
export type Person = DeepPartial<GQLPerson> & { id: GQLPerson['id'] };
export type GraphqlQueryPerson = Person;
export type GraphqlMutationPerson = Person;
export const mapToPerson = (person: GraphqlQueryPerson): Person => person;
export const mapToGqlPerson = (person: Person): GraphqlMutationPerson => person;

View File

@ -1,50 +0,0 @@
import {
GraphqlMutationPerson,
GraphqlQueryPerson,
} from '../../interfaces/person.interface';
import { updatePerson } from '../update';
jest.mock('~/apollo', () => {
const personInterface = jest.requireActual(
'@/people/interfaces/person.interface',
);
return {
apiClient: {
mutate: (arg: {
mutation: unknown;
variables: GraphqlMutationPerson;
}) => {
const gqlPerson = arg.variables as unknown as GraphqlQueryPerson;
return { data: personInterface.mapToPerson(gqlPerson) };
},
},
};
});
it('updates a person', async () => {
const result = await updatePerson({
firstname: 'John',
lastname: 'Doe',
id: '7dfbc3f7-6e5e-4128-957e-8d86808cdf6c',
email: 'john@example.com',
company: {
id: '7dfbc3f7-6e5e-4128-957e-8d86808cdf6b',
name: 'ACME',
domainName: 'example.com',
__typename: 'Company',
},
phone: '+1 (555) 123-4567',
pipes: [
{
id: '7dfbc3f7-6e5e-4128-957e-8d86808cdf6d',
name: 'Customer',
icon: '!',
},
],
createdAt: new Date().toISOString(),
city: 'San Francisco',
__typename: 'Person',
});
expect(result.data).toBeDefined();
result.data && expect(result.data.email).toBe('john@example.com');
});

View File

@ -1,10 +1,4 @@
import { FetchResult, gql } from '@apollo/client';
import { getOperationName } from '@apollo/client/utilities';
import { apiClient } from '../../../apollo';
import { mapToGqlPerson, Person } from '../interfaces/person.interface';
import { GET_PEOPLE } from './select';
import { gql } from '@apollo/client';
export const UPDATE_PERSON = gql`
mutation UpdatePeople(
@ -90,36 +84,3 @@ export const DELETE_PEOPLE = gql`
}
}
`;
export async function updatePerson(
person: Person,
): Promise<FetchResult<Person>> {
const result = await apiClient.mutate({
mutation: UPDATE_PERSON,
variables: person,
});
return result;
}
export async function insertPerson(
person: Person,
): Promise<FetchResult<Person>> {
const result = await apiClient.mutate({
mutation: INSERT_PERSON,
variables: mapToGqlPerson(person),
refetchQueries: [getOperationName(GET_PEOPLE) ?? ''],
});
return result;
}
export async function deletePeople(
peopleIds: string[],
): Promise<FetchResult<Person>> {
const result = await apiClient.mutate({
mutation: DELETE_PEOPLE,
variables: { ids: peopleIds },
});
return result;
}

View File

@ -1,26 +1,7 @@
import { ReactNode } from 'react';
import { DocumentNode } from 'graphql';
import {
AnyEntity,
BoolExpType,
GqlType,
UnknownType,
} from '@/utils/interfaces/generic.interface';
export type SearchConfigType<
SearchType extends AnyEntity | UnknownType = UnknownType,
> = SearchType extends UnknownType
? {
query: DocumentNode;
template: (searchInput: string) => any;
resultMapper: (data: any) => any;
}
: {
query: DocumentNode;
template: (searchInput: string) => BoolExpType<SearchType>;
resultMapper: (data: GqlType<SearchType>) => {
value: SearchType;
render: (value: SearchType) => ReactNode;
};
};
export type SearchConfigType = {
query: DocumentNode;
template: (searchInput: string) => any;
resultMapper: (data: any) => any;
};

View File

@ -2,7 +2,6 @@ import { useMemo, useState } from 'react';
import { gql, useQuery } from '@apollo/client';
import { debounce } from '@/utils/debounce';
import { AnyEntity, UnknownType } from '@/utils/interfaces/generic.interface';
import { SearchConfigType } from '../interfaces/interface';
@ -64,22 +63,21 @@ export const SEARCH_COMPANY_QUERY = gql`
}
`;
export type SearchResultsType<T extends AnyEntity | UnknownType = UnknownType> =
{
results: {
render: (value: T) => string;
value: T;
}[];
loading: boolean;
};
export type SearchResultsType<T> = {
results: {
render: (value: T) => string;
value: T;
}[];
loading: boolean;
};
export const useSearch = <T extends AnyEntity | UnknownType = UnknownType>(): [
export const useSearch = <T>(): [
SearchResultsType<T>,
React.Dispatch<React.SetStateAction<string>>,
React.Dispatch<React.SetStateAction<SearchConfigType<T> | null>>,
React.Dispatch<React.SetStateAction<SearchConfigType | null>>,
string,
] => {
const [searchConfig, setSearchConfig] = useState<SearchConfigType<T> | null>(
const [searchConfig, setSearchConfig] = useState<SearchConfigType | null>(
null,
);
const [searchInput, setSearchInput] = useState<string>('');

View File

@ -8,7 +8,6 @@ import { useSearch } from '@/search/services/search';
import { IconPlus } from '@/ui/icons/index';
import { textInputStyle } from '@/ui/layout/styles/themes';
import { isSomeInputInEditModeState } from '@/ui/tables/states/isSomeInputInEditModeState';
import { AnyEntity } from '@/utils/interfaces/generic.interface';
import { isDefined } from '@/utils/type-guards/isDefined';
import { isNonEmptyString } from '@/utils/type-guards/isNonEmptyString';
@ -86,13 +85,10 @@ const StyledCreateButtonText = styled.div`
color: ${(props) => props.theme.text60};
`;
export type EditableRelationProps<
RelationType extends AnyEntity,
ChipComponentPropsType,
> = {
relation?: RelationType | null;
export type EditableRelationProps<RelationType, ChipComponentPropsType> = {
relation?: any;
searchPlaceholder: string;
searchConfig: SearchConfigType<RelationType>;
searchConfig: SearchConfigType;
onChange: (relation: RelationType) => void;
onChangeSearchInput?: (searchInput: string) => void;
editModeHorizontalAlign?: 'left' | 'right';
@ -105,10 +101,7 @@ export type EditableRelationProps<
};
// TODO: split this component
export function EditableRelation<
RelationType extends AnyEntity,
ChipComponentPropsType,
>({
export function EditableRelation<RelationType, ChipComponentPropsType>({
relation,
searchPlaceholder,
searchConfig,

View File

@ -40,7 +40,8 @@ export const FilterDropdownButton = <TData extends FilterableFieldsType>({
FilterOperandType<TData> | undefined
>(undefined);
const [filterSearchResults, setSearchInput, setFilterSearch] = useSearch();
const [filterSearchResults, setSearchInput, setFilterSearch] =
useSearch<TData>();
const resetState = useCallback(() => {
setIsOperandSelectionUnfolded(false);
@ -79,7 +80,7 @@ export const FilterDropdownButton = <TData extends FilterableFieldsType>({
));
const renderSearchResults = (
filterSearchResults: SearchResultsType,
filterSearchResults: SearchResultsType<TData>,
selectedFilter: FilterConfigType<TData>,
selectedFilterOperand: FilterOperandType<TData>,
) => {
@ -155,7 +156,7 @@ export const FilterDropdownButton = <TData extends FilterableFieldsType>({
displayValue: event.target.value,
icon: selectedFilter.icon,
operand: selectedFilterOperand,
});
} as SelectedFilterType<TData>);
}
}
}}
@ -172,7 +173,7 @@ export const FilterDropdownButton = <TData extends FilterableFieldsType>({
displayValue: humanReadableDate(date),
icon: selectedFilter.icon,
operand: selectedFilterOperand,
});
} as SelectedFilterType<TData>);
}}
customInput={<></>}
customCalendarContainer={styled.div`
@ -200,7 +201,7 @@ export const FilterDropdownButton = <TData extends FilterableFieldsType>({
setIsUnfolded={setIsUnfolded}
resetState={resetState}
>
{selectedFilter
{selectedFilter && selectedFilterOperand
? isOperandSelectionUnfolded
? renderOperandSelection
: renderValueSelection(selectedFilter, selectedFilterOperand)

View File

@ -1,12 +0,0 @@
import { User as GQLUser } from '../../../generated/graphql';
import { DeepPartial } from '../../utils/utils';
export type User = DeepPartial<GQLUser> & { id: string };
export type GraphqlQueryUser = User;
export type GraphqlMutationUser = User;
export const mapToUser = (user: GraphqlQueryUser): User => user;
export const mapToGqlUser = (user: User): GraphqlMutationUser => user;

View File

@ -1,18 +0,0 @@
import { WorkspaceMember as GQLWorkspaceMember } from '../../../generated/graphql';
import { DeepPartial } from '../../utils/utils';
export type WorkspaceMember = DeepPartial<GQLWorkspaceMember> & {
id: GQLWorkspaceMember['id'];
};
export type GraphqlQueryWorkspaceMember = WorkspaceMember;
export type GraphqlMutationWorkspaceMember = WorkspaceMember;
export const mapToWorkspaceMember = (
workspaceMember: GraphqlQueryWorkspaceMember,
): WorkspaceMember => workspaceMember;
export const mapToGqlWorkspaceMember = (
workspaceMember: WorkspaceMember,
): GraphqlMutationWorkspaceMember => workspaceMember;

View File

@ -1,9 +0,0 @@
import { gql } from '@apollo/client';
export const GET_CURRENT_USER = gql`
query getUsers {
findManyUser {
id
}
}
`;

View File

@ -1,37 +0,0 @@
import {
Company,
GraphqlQueryCompany,
} from '@/companies/interfaces/company.interface';
import {
GraphqlQueryPerson,
Person,
} from '@/people/interfaces/person.interface';
import { GraphqlQueryUser, User } from '@/users/interfaces/user.interface';
import {
CompanyWhereInput as Companies_Bool_Exp,
PersonWhereInput as People_Bool_Exp,
UserWhereInput as Users_Bool_Exp,
} from '~/generated/graphql';
export type AnyEntity = {
id: string;
__typename?: string;
} & Record<string, any>;
export type UnknownType = void;
export type GqlType<T> = T extends Company
? GraphqlQueryCompany
: T extends Person
? GraphqlQueryPerson
: T extends User
? GraphqlQueryUser
: never;
export type BoolExpType<T> = T extends Company
? Companies_Bool_Exp
: T extends Person
? People_Bool_Exp
: T extends User
? Users_Bool_Exp
: never;

View File

@ -13,9 +13,3 @@ export const getLogoUrlFromDomainName = (domainName?: string): string => {
export const browserPrefersDarkMode = (): boolean => {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
};
export type DeepPartial<T> = T extends object
? {
[P in keyof T]?: DeepPartial<T[P]>;
}
: T;

View File

@ -1,21 +0,0 @@
import { Workspace as GQLWorkspace } from '../../../generated/graphql';
import { DeepPartial } from '../../utils/utils';
export type Workspace = DeepPartial<GQLWorkspace> & { id: GQLWorkspace['id'] };
export type GraphqlQueryWorkspace = Workspace;
export type GraphqlMutationWorkspace = Workspace;
export const mapToWorkspace = (
workspace: GraphqlQueryWorkspace,
): Workspace => ({
id: workspace.id,
domainName: workspace.domainName,
displayName: workspace.displayName,
logo: workspace.logo,
});
export const mapToGqlWorkspace = (
workspace: Workspace,
): GraphqlMutationWorkspace => workspace;