Skip to content

Commit

Permalink
UILD-410: fixes for medium and low Sonar issues (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
SKarolFolio authored Nov 18, 2024
1 parent b771ec2 commit e657db7
Show file tree
Hide file tree
Showing 45 changed files with 801 additions and 363 deletions.
6 changes: 3 additions & 3 deletions src/common/helpers/bibframe.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ export const getMappedBFLiteUri = (uri: string | undefined, schema?: Schema, pat
path?.forEach(elem => {
const schemaElem = schema?.get(elem);

if (!schemaElem || !schemaElem.uri) return;
if (!schemaElem?.uri) return;

const mappedUriTyped = mappedUri as BFMapEntry;
const schemaElemUri = schemaElem.uri as string;
const schemaElemUri = schemaElem.uri;
const pathUri = mappedUriTyped?.[schemaElemUri];

if (pathUri) {
Expand Down Expand Up @@ -50,7 +50,7 @@ export const getUris = ({ uri, dataTypeURI, schema, path }: GetUris) => {
}

const uriBFLite = getMappedBFLiteUri(uri, schema, path);
const uriWithSelector = uriBFLite || uri;
const uriWithSelector = uriBFLite ?? uri;

return { uriBFLite, uriWithSelector };
};
Expand Down
4 changes: 2 additions & 2 deletions src/common/helpers/profile.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export const getMappedLookupValue = ({
// Find lookup value in the map
const selectedMappedUri = Object.entries(groupTypeMap.data)?.find(([_, value]) => value.uri === uri)?.[0];

mappedUri = selectedMappedUri || uri;
mappedUri = selectedMappedUri ?? uri;
}

return mappedUri;
Expand Down Expand Up @@ -152,7 +152,7 @@ const traverseSchema = ({
uriBFLite,
label,
basicLabel,
uri: uri || parentUri,
uri: uri ?? parentUri,
type: type as AdvancedFieldType,
nonBFMappedGroup: updatedNonBFMappedGroup,
});
Expand Down
4 changes: 2 additions & 2 deletions src/common/helpers/record.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type IGetAdjustedRecordContents = {
};

export const getRecordId = (record: RecordEntry | null, selectedBlock?: string, previewBlock?: string) => {
const block = selectedBlock || TYPE_URIS.INSTANCE;
const block = selectedBlock ?? TYPE_URIS.INSTANCE;

return previewBlock ? (record?.resource?.[block]?.[previewBlock] as any[])?.[0]?.id : record?.resource?.[block]?.id;
};
Expand Down Expand Up @@ -159,7 +159,7 @@ export const getRecordTitle = (record: RecordEntry) => {

TITLE_CONTAINER_URIS.every(uri => {
const selectedTitleContainer = (
recordContents[block!]?.['http://bibfra.me/vocab/marc/title'] as unknown as Record<string, any>[]
recordContents[block!]?.['http://bibfra.me/vocab/marc/title'] as unknown as Record<string, unknown>[]
)?.find(obj => Object.hasOwn(obj, uri));

if (selectedTitleContainer) {
Expand Down
2 changes: 1 addition & 1 deletion src/common/helpers/schema.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export const getHtmlIdForEntry = ({ path = [] }: Partial<SchemaEntry>, schema: S
const uriSelector = uriBFLite ?? uri;
const id = uriSelector ? uriSelector.split(BF_URI_DELIMITER).at(-1) : bfid?.split(BFID_DELIMITER).at(-1);

return [...acc, `${id}${ENTRY_COUNT_DELIMITER}${cloneIndex || 0}`];
return [...acc, `${id}${ENTRY_COUNT_DELIMITER}${cloneIndex ?? 0}`];
}, [] as string[])
.join(ENTRY_DELIMITER);
};
Expand Down
4 changes: 2 additions & 2 deletions src/common/helpers/search.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export const getTitle = (titles: GenericStructDTO<TitleType>[] | undefined) => {

export const formatItemSearchInstanceListData = (instanceList: InstanceAsSearchResultDTO[]): Row[] => {
return instanceList.map(({ id, titles, identifiers, publications }) => {
// TODO: at the moment, picking the first match/first item in list for display
// at the moment, picking the first match/first item in list for display
// this might change depending on requirements

const selectedPublisher = publications?.find(({ name, date }) => name || date);
const selectedPublisher = publications?.find(({ name, date }) => name ?? date);

return {
__meta: {
Expand Down
2 changes: 1 addition & 1 deletion src/common/helpers/validations.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const validateNonNormalizedLccn = (lccn: string) => {

const preformatted = lccn.replaceAll(/\s+/g, '').split('/')[0];

// TODO: try to have a single regexp rule?
// Refactor: try to have a single regexp rule?
const passes = regexForNonNormalizedLccn.test(preformatted);

// if passes, return string with only digits and letters in it
Expand Down
6 changes: 3 additions & 3 deletions src/common/hooks/useComplexLookup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChangeEvent, useCallback, useContext, useState } from 'react';
import { ChangeEvent, useCallback, useState } from 'react';
import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil';
import {
generateEmptyValueUuid,
Expand All @@ -8,10 +8,10 @@ import {
} from '@common/helpers/complexLookup.helper';
import { __MOCK_URI_CHANGE_WHEN_IMPLEMENTING } from '@common/constants/complexLookup.constants';
import { AdvancedFieldType } from '@common/constants/uiControls.constants';
import { ServicesContext } from '@src/contexts';
import state from '@state';
import { useModalControls } from './useModalControls';
import { useMarcData } from './useMarcData';
import { useServicesContext } from './useServicesContext';

export const useComplexLookup = ({
entry,
Expand All @@ -24,7 +24,7 @@ export const useComplexLookup = ({
lookupConfig: ComplexLookupsConfigEntry;
onChange: (uuid: string, contents: Array<UserValueContents>) => void;
}) => {
const { selectedEntriesService } = useContext(ServicesContext) as Required<ServicesParams>;
const { selectedEntriesService } = useServicesContext() as Required<ServicesParams>;
const [localValue, setLocalValue] = useState<UserValueContents[]>(value || []);
const schema = useRecoilValue(state.config.schema);
const marcPreviewMetadata = useRecoilValue(state.data.marcPreviewMetadata);
Expand Down
11 changes: 5 additions & 6 deletions src/common/hooks/useConfig.hook.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { useContext, useRef } from 'react';
import { useRef } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { v4 as uuidv4 } from 'uuid';
import state from '@state';
import { fetchProfiles } from '@common/api/profiles.api';
import { PROFILE_NAMES } from '@common/constants/bibframe.constants';
import { getPrimaryEntitiesFromRecord, getRecordTitle } from '@common/helpers/record.helper';
import { ServicesContext } from '@src/contexts';
import { useProcessedRecordAndSchema } from './useProcessedRecordAndSchema.hook';
import { useServicesContext } from './useServicesContext';

export type PreviewParams = {
singular?: boolean;
Expand All @@ -20,9 +20,8 @@ type GetProfiles = {
};

export const useConfig = () => {
const { schemaCreatorService, userValuesService, selectedEntriesService } = useContext(
ServicesContext,
) as Required<ServicesParams>;
const { schemaCreatorService, userValuesService, selectedEntriesService } =
useServicesContext() as Required<ServicesParams>;
const [profiles, setProfiles] = useRecoilState(state.config.profiles);
const setSelectedProfile = useSetRecoilState(state.config.selectedProfile);
const setUserValues = useSetRecoilState(state.inputs.userValues);
Expand Down Expand Up @@ -87,7 +86,7 @@ export const useConfig = () => {
return { updatedSchema, initKey };
};

const getProfiles = async ({ record, recordId, previewParams, asClone }: GetProfiles): Promise<any> => {
const getProfiles = async ({ record, recordId, previewParams, asClone }: GetProfiles): Promise<unknown> => {
if (isProcessingProfiles.current && (record || recordId)) return;

try {
Expand Down
18 changes: 13 additions & 5 deletions src/common/hooks/useProcessedRecordAndSchema.hook.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useContext } from 'react';
import { useCallback } from 'react';
import { useSetRecoilState } from 'recoil';
import { useIntl } from 'react-intl';
import { DUPLICATE_RESOURCE_TEMPLATE } from '@common/constants/resourceTemplates.constants';
import {
Expand All @@ -7,9 +8,10 @@ import {
wrapRecordValuesWithCommonContainer,
} from '@common/helpers/record.helper';
import { applyIntlToTemplates } from '@common/helpers/recordFormatting.helper';
import { ServicesContext } from '@src/contexts';
import { UserNotificationFactory } from '@common/services/userNotification';
import { StatusType } from '@common/constants/status.constants';
import state from '@state';
import { useSetRecoilState } from 'recoil';
import { useServicesContext } from './useServicesContext';

type IGetProcessedRecordAndSchema = {
baseSchema: Schema;
Expand All @@ -20,9 +22,10 @@ type IGetProcessedRecordAndSchema = {

export const useProcessedRecordAndSchema = () => {
const setRecord = useSetRecoilState(state.inputs.record);
const setStatusMessages = useSetRecoilState(state.status.commonMessages);
const { formatMessage } = useIntl();
const { userValuesService, schemaWithDuplicatesService, recordNormalizingService, recordToSchemaMappingService } =
useContext(ServicesContext) as Required<ServicesParams>;
useServicesContext() as Required<ServicesParams>;

const getProcessedRecordAndSchema = useCallback(
async ({ baseSchema, record, userValues, asClone = false }: IGetProcessedRecordAndSchema) => {
Expand Down Expand Up @@ -67,8 +70,12 @@ export const useProcessedRecordAndSchema = () => {
updatedUserValues = userValuesService.getAllValues();
}
} catch (error) {
// TODO: display an user error
console.error(error);

setStatusMessages(currentStatus => [
...currentStatus,
UserNotificationFactory.createMessage(StatusType.error, 'ld.errorLoadingResource'),
]);
}

return {
Expand All @@ -83,6 +90,7 @@ export const useProcessedRecordAndSchema = () => {
recordToSchemaMappingService,
schemaWithDuplicatesService,
setRecord,
setStatusMessages,
userValuesService,
],
);
Expand Down
7 changes: 2 additions & 5 deletions src/common/hooks/useProfileSchema.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { useContext } from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { ServicesContext } from '@src/contexts';
import state from '@state';
import { useServicesContext } from './useServicesContext';

export const useProfileSchema = () => {
const { selectedEntriesService, schemaWithDuplicatesService } = useContext(
ServicesContext,
) as Required<ServicesParams>;
const { selectedEntriesService, schemaWithDuplicatesService } = useServicesContext() as Required<ServicesParams>;
const [schema, setSchema] = useRecoilState(state.config.schema);
const setSelectedEntries = useSetRecoilState(state.config.selectedEntries);
const setClonePrototypes = useSetRecoilState(state.config.clonePrototypes);
Expand Down
7 changes: 3 additions & 4 deletions src/common/hooks/useRecordControls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ import {
getRecordId,
getSelectedRecordBlocks,
saveRecordLocally,
getSavedRecord,
} from '@common/helpers/record.helper';
import { UserNotificationFactory } from '@common/services/userNotification';
import { PreviewParams, useConfig } from '@common/hooks/useConfig.hook';
import { getSavedRecord } from '@common/helpers/record.helper';
import { formatRecord } from '@common/helpers/recordFormatting.helper';
import { QueryParams, ROUTES } from '@common/constants/routes.constants';
import { BLOCKS_BFLITE } from '@common/constants/bibframeMapping.constants';
Expand Down Expand Up @@ -120,7 +120,6 @@ export const useRecordControls = () => {
selectedRecordBlocks: updatedSelectedRecordBlocks,
}) as RecordEntry;

// TODO: define a type
const recordId = getRecordId(record, selectedRecordBlocks?.block);
const shouldPostRecord = !recordId || getRecordId(record) === DEFAULT_RECORD_ID || isClone;

Expand All @@ -138,7 +137,7 @@ export const useRecordControls = () => {
UserNotificationFactory.createMessage(StatusType.success, recordId ? 'ld.rdUpdateSuccess' : 'ld.rdSaveSuccess'),
]);

// TODO: isEdited state update is not immediately reflected in the <Prompt />
// isEdited state update is not immediately reflected in the <Prompt />
// blocker component, forcing <Prompt /> to block the navigation call below
// right before isEdited is set to false, disabling <Prompt />
//
Expand All @@ -163,7 +162,7 @@ export const useRecordControls = () => {

if (asRefToNewRecord) {
const blocksBfliteKey = (
searchParams.get(QueryParams.Type) || ResourceType.instance
searchParams.get(QueryParams.Type) ?? ResourceType.instance
)?.toUpperCase() as BibframeEntities;

const selectedBlock = BLOCKS_BFLITE[blocksBfliteKey]?.uri;
Expand Down
8 changes: 4 additions & 4 deletions src/common/hooks/useSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { DEFAULT_PAGES_METADATA } from '@common/constants/api.constants';
import { SearchIdentifiers, SearchSegment } from '@common/constants/search.constants';
import { generateSearchParamsState } from '@common/helpers/search.helper';
import { usePagination } from '@common/hooks/usePagination';
import { useSearchContext } from '@common/hooks/useSearchContext';
import { useFetchSearchData } from '@common/hooks/useFetchSearchData';
import state from '@state';
import { useSearchContext } from './useSearchContext';
import { useFetchSearchData } from './useFetchSearchData';

export const useSearch = () => {
const {
Expand Down Expand Up @@ -49,7 +49,7 @@ export const useSearch = () => {

setFacetsBySegments(prevValue => ({
...prevValue,
[selectedNavigationSegment as string]: {
[selectedNavigationSegment]: {
query,
searchBy,
facets,
Expand Down Expand Up @@ -139,7 +139,7 @@ export const useSearch = () => {
pageMetadataSelectorType: 'prev' | 'next';
}) => {
const isInitialPage = pageNumber === 0;
const selectedQuery = (isInitialPage ? query : pageMetadata?.[pageMetadataSelectorType]) || query;
const selectedQuery = (isInitialPage ? query : pageMetadata?.[pageMetadataSelectorType]) ?? query;
const baseQuerySelector =
isBrowseSearch && !isInitialPage ? baseQuerySelectorType : SearchableIndexQuerySelector.Query;

Expand Down
4 changes: 2 additions & 2 deletions src/common/hooks/useSearchFilterLookupOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ export const useSearchFilterLookupOptions = ({
options = facetValues.reduce((accum, { id, totalRecords }) => {
const sourceElem = sourceData?.find(({ id: sourceDataId }) => sourceDataId === id);
const selectedLabel = hasMappedSourceData ? sourceElem?.name : id;
const label = selectedLabel?.trim() || formatMessage({ id: 'ld.notSpecified' });
const label = selectedLabel?.trim() ?? formatMessage({ id: 'ld.notSpecified' });

// TODO: uncomment when the way to filter the options list is approved
// Uncomment when the way to filter the options list is approved
// if (excludedOptions?.includes(id)) return accum;

accum.push({
Expand Down
17 changes: 14 additions & 3 deletions src/common/hooks/useSearchFiltersData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useEffect } from 'react';
import { useRecoilState, useResetRecoilState, useSetRecoilState } from 'recoil';
import { StatusType } from '@common/constants/status.constants';
import { UserNotificationFactory } from '@common/services/userNotification';
import * as SearchApi from '@common/api/search.api';
import state from '@state';

Expand All @@ -11,6 +13,7 @@ export const useSearchFiltersData = () => {
const resetSelectedFacetsGroups = useResetRecoilState(state.search.selectedFacetsGroups);
const setFacetsData = useSetRecoilState(state.search.facetsData);
const setSourceData = useSetRecoilState(state.search.sourceData);
const setCommonStatus = useSetRecoilState(state.status.commonMessages);

useEffect(() => {
return resetSelectedFacetsGroups();
Expand All @@ -35,8 +38,12 @@ export const useSearchFiltersData = () => {

setSourceData(sourceData);
} catch (error) {
// TODO: handle error and show notification
console.error(error);

setCommonStatus(currentStatus => [
...currentStatus,
UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'),
]);
}
};

Expand All @@ -47,14 +54,18 @@ export const useSearchFiltersData = () => {

try {
const facetsQueryParam = updatedSelectedFacetsGroups.join(',');
// TODO: generate query by selected values
// Generate query by selected values
const query = DEFAULT_SEARCH_FACETS_QUERY;
const response = await SearchApi.getSearchData(url, { facet: facetsQueryParam, query });

setFacetsData(response.facets);
} catch (error) {
// TODO: handle error and show notification
console.error(error);

setCommonStatus(currentStatus => [
...currentStatus,
UserNotificationFactory.createMessage(StatusType.error, 'ld.errorFetching'),
]);
}
};

Expand Down
6 changes: 6 additions & 0 deletions src/common/hooks/useServicesContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useContext } from 'react';
import { ServicesContext } from '@src/contexts';

export const useServicesContext = () => {
return useContext(ServicesContext);
};
7 changes: 3 additions & 4 deletions src/common/hooks/useSimpleLookupData.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { useContext } from 'react';
import { loadSimpleLookup } from '@common/helpers/api.helper';
import { alphabeticSortLabel } from '@common/helpers/common.helper';
import { filterLookupOptionsByMappedValue, formatLookupOptions } from '@common/helpers/lookupOptions.helper';
import { ServicesContext } from '@src/contexts';
import { useServicesContext } from './useServicesContext';

export const useSimpleLookupData = () => {
const { lookupCacheService } = useContext(ServicesContext) as Required<ServicesParams>;
const { lookupCacheService } = useServicesContext() as Required<ServicesParams>;

const getLookupData = lookupCacheService.getAll;

Expand All @@ -17,7 +16,7 @@ export const useSimpleLookupData = () => {

const formattedLookupData = formatLookupOptions(response, uri);
const filteredLookupData = filterLookupOptionsByMappedValue(formattedLookupData, propertyURI);
const sortedLookupData = filteredLookupData?.sort(alphabeticSortLabel);
const sortedLookupData = filteredLookupData?.toSorted(alphabeticSortLabel);

lookupCacheService.save?.(uri, sortedLookupData);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
export const getLabelUri = (blockKey: string, groupKey: string, fieldKey: string) => {
const typedMap = NEW_BF2_TO_BFLITE_MAPPING as BF2BFLiteMap;

return typedMap?.[blockKey]?.[groupKey]?.fields?.[fieldKey]?.label || '';
return typedMap?.[blockKey]?.[groupKey]?.fields?.[fieldKey]?.label ?? '';
};

export const wrapWithContainer = (record: RecordEntry, blockKey: string, key: string, container: string) => {
Expand Down
Loading

0 comments on commit e657db7

Please sign in to comment.