Skip to content

Commit

Permalink
Sort Questionnaire keys for readability. Closes #96
Browse files Browse the repository at this point in the history
  • Loading branch information
ruscoder committed Jan 26, 2025
1 parent b4c1840 commit 5dd5317
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
17 changes: 15 additions & 2 deletions web/src/containers/Main/useMain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';
import { generateMappingService, generateQuestionnaireService } from 'web/src/services/builder';
import { applyMapping as applyMappingService, extract } from 'web/src/services/extract';
import { sortKeys } from 'web/src/utils/sort-keys';

import {
createFHIRResource as createAidboxFHIRResource,
Expand All @@ -29,7 +30,7 @@ import {
success,
} from 'fhir-react/lib/libs/remoteData';
import { WithId, saveFHIRResource } from 'fhir-react/lib/services/fhir';
import { service } from 'fhir-react/lib/services/service';
import { mapSuccess, service } from 'fhir-react/lib/services/service';
import { formatError } from 'fhir-react/lib/utils/error';

import { Mapping } from 'shared/src/contrib/aidbox';
Expand Down Expand Up @@ -100,7 +101,19 @@ export function useMain(questionnaireId: string) {
loadMapping(response.data);
}

return response;
return mapSuccess(response, (q) =>
sortKeys(q, [
'resourceType',
'id',
'status',
'linkId',
'text',
'type',
'*',
'item',
'meta',
]),
);
}, [questionnaireId]);

const [assembledQuestionnaireRD, assembledQuestionnaireRDManager] = useService(async () => {
Expand Down
33 changes: 33 additions & 0 deletions web/src/utils/sort-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
type JSONObject = { [key: string]: any };
type JSONArray = Array<any>;

export function sortKeys<T extends JSONArray | JSONObject>(obj: T, order: string[]): T {
order = order.includes('*') ? order : [...order, '*'];

if (Array.isArray(obj)) {
return obj.map((element) => sortKeys(element, order)) as T;
}

if (typeof obj !== 'object' || obj === null) {
return obj;
}

const keys = Object.keys(obj);

const sortedKeys = order.flatMap((key) => {
if (key === '*') {
return keys.filter((k) => !order.includes(k));
}
return keys.includes(key) ? key : [];
});

const unmatchedKeys = keys.filter((k) => !sortedKeys.includes(k));
const finalKeys = [...sortedKeys, ...unmatchedKeys];

const sortedObj: JSONObject = {};
for (const key of finalKeys) {
sortedObj[key] = sortKeys(obj[key], order);
}

return sortedObj as T;
}

0 comments on commit 5dd5317

Please sign in to comment.