@medplum/fhir-router 2.0.22 → 2.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { OperationOutcomeError, badRequest, normalizeOperationOutcome, parseSearchUrl, getReferenceString, resolveId, getStatus, isOk, allOk, LRUCache, forbidden, getResourceTypes, getResourceTypeSchema, isResourceTypeSchema, getElementDefinition, buildTypeName, capitalize, isLowerCase, globalSchema, getSearchParameters, DEFAULT_SEARCH_COUNT, toJsBoolean, evalFhirPathTyped, toTypedValue, Operator, parseSearchRequest, isResourceType, notFound, created, deepClone, matchesSearchRequest, evalFhirPath } from '@medplum/core';
1
+ import { OperationOutcomeError, badRequest, normalizeOperationOutcome, parseSearchUrl, getReferenceString, resolveId, getStatus, isOk, allOk, Operator, parseSearchRequest, getSearchParameters, getResourceTypeSchema, isResourceType, getElementDefinition, buildTypeName, capitalize, getResourceTypes, isResourceTypeSchema, isLowerCase, globalSchema, toJsBoolean, evalFhirPathTyped, toTypedValue, LRUCache, forbidden, DEFAULT_SEARCH_COUNT, notFound, created, deepClone, matchesSearchRequest, evalFhirPath } from '@medplum/core';
2
2
  import DataLoader from 'dataloader';
3
3
  import { applyPatch } from 'rfc6902';
4
4
 
@@ -13373,152 +13373,188 @@ const typeCache = {
13373
13373
  'http://hl7.org/fhirpath/System.String': GraphQLString,
13374
13374
  'http://hl7.org/fhirpath/System.Time': GraphQLString,
13375
13375
  };
13376
- const outputTypeCache = {
13377
- ...typeCache,
13378
- };
13379
- const inputTypeCache = {
13380
- ...typeCache,
13381
- };
13376
+ function parseSearchArgs(resourceType, source, args) {
13377
+ let referenceFilter = undefined;
13378
+ if (source) {
13379
+ // _reference is a required field for reverse lookup searches
13380
+ // The GraphQL parser will validate that it is there.
13381
+ const reference = args['_reference'];
13382
+ delete args['_reference'];
13383
+ referenceFilter = {
13384
+ code: reference,
13385
+ operator: Operator.EQUALS,
13386
+ value: getReferenceString(source),
13387
+ };
13388
+ }
13389
+ // Reverse the transform of dashes to underscores, back to dashes
13390
+ args = Object.fromEntries(Object.entries(args).map(([key, value]) => [graphQLFieldToFhirParam(key), value]));
13391
+ // Parse the search request
13392
+ const searchRequest = parseSearchRequest(resourceType, args);
13393
+ // If a reverse lookup filter was specified,
13394
+ // add it to the search request.
13395
+ if (referenceFilter) {
13396
+ const existingFilters = searchRequest.filters || [];
13397
+ searchRequest.filters = [referenceFilter, ...existingFilters];
13398
+ }
13399
+ return searchRequest;
13400
+ }
13401
+ function graphQLFieldToFhirParam(code) {
13402
+ return code.startsWith('_') ? code : code.replaceAll('_', '-');
13403
+ }
13404
+ function fhirParamToGraphQLField(code) {
13405
+ return code.replaceAll('-', '_');
13406
+ }
13382
13407
  /**
13383
- * Cache of "introspection" query results.
13384
- * Common case is the standard schema query from GraphiQL and Insomnia.
13385
- * The result is big and somewhat computationally expensive.
13408
+ * GraphQL data loader for search requests.
13409
+ * The field name should always end with "List" (i.e., "Patient" search uses "PatientList").
13410
+ * The search args should be FHIR search parameters.
13411
+ * @param source The source/root. This should always be null for our top level readers.
13412
+ * @param args The GraphQL search arguments.
13413
+ * @param ctx The GraphQL context.
13414
+ * @param info The GraphQL resolve info. This includes the schema, and additional field details.
13415
+ * @returns Promise to read the resoures for the query.
13386
13416
  */
13387
- const introspectionResults = new LRUCache();
13417
+ async function resolveBySearch(source, args, ctx, info) {
13418
+ const fieldName = info.fieldName;
13419
+ const resourceType = fieldName.substring(0, fieldName.length - 'List'.length);
13420
+ const searchRequest = parseSearchArgs(resourceType, source, args);
13421
+ const bundle = await ctx.repo.search(searchRequest);
13422
+ return bundle.entry?.map((e) => e.resource);
13423
+ }
13424
+ function buildSearchArgs(resourceType) {
13425
+ const args = {
13426
+ _count: {
13427
+ type: GraphQLInt,
13428
+ description: 'Specify how many elements to return from a repeating list.',
13429
+ },
13430
+ _offset: {
13431
+ type: GraphQLInt,
13432
+ description: 'Specify the offset to start at for a repeating element.',
13433
+ },
13434
+ _sort: {
13435
+ type: GraphQLString,
13436
+ description: 'Specify the sort order by comma-separated list of sort rules in priority order.',
13437
+ },
13438
+ _id: {
13439
+ type: GraphQLString,
13440
+ description: 'Select resources based on the logical id of the resource.',
13441
+ },
13442
+ _lastUpdated: {
13443
+ type: GraphQLString,
13444
+ description: 'Select resources based on the last time they were changed.',
13445
+ },
13446
+ };
13447
+ const searchParams = getSearchParameters(resourceType);
13448
+ if (searchParams) {
13449
+ for (const [code, searchParam] of Object.entries(searchParams)) {
13450
+ // GraphQL does not support dashes in argument names
13451
+ // So convert dashes to underscores
13452
+ args[fhirParamToGraphQLField(code)] = {
13453
+ type: GraphQLString,
13454
+ description: searchParam.description,
13455
+ };
13456
+ }
13457
+ }
13458
+ return args;
13459
+ }
13388
13460
  /**
13389
- * Cached GraphQL schema.
13390
- * This should be initialized at server startup.
13461
+ * Returns the depth of the GraphQL node in a query.
13462
+ * We use "selections" as the representation of depth.
13463
+ * As a rough approximation, it's the number of indentations in a well formatted query.
13464
+ * @param path The GraphQL node path.
13465
+ * @returns The "depth" of the node.
13391
13466
  */
13392
- let rootSchema;
13467
+ function getDepth(path) {
13468
+ return path.filter((p) => p === 'selections').length;
13469
+ }
13393
13470
  /**
13394
- * Handles FHIR GraphQL requests.
13395
- *
13396
- * See: https://www.hl7.org/fhir/graphql.html
13397
- * @param req The request details.
13398
- * @param repo The current user FHIR repository.
13399
- * @param router The router for router options.
13400
- * @returns The response.
13471
+ * Returns true if the field is requested in the GraphQL query.
13472
+ * @param info The GraphQL resolve info. This includes the field name.
13473
+ * @param fieldName The field name to check.
13474
+ * @returns True if the field is requested in the GraphQL query.
13401
13475
  */
13402
- async function graphqlHandler(req, repo, router) {
13403
- const { query, operationName, variables } = req.body;
13404
- if (!query) {
13405
- return [badRequest('Must provide query.')];
13406
- }
13407
- let document;
13408
- try {
13409
- document = parse(query);
13410
- }
13411
- catch (err) {
13412
- return [badRequest('GraphQL syntax error.')];
13413
- }
13414
- const schema = getRootSchema();
13415
- const validationRules = [...specifiedRules, MaxDepthRule];
13416
- const validationErrors = validate(schema, document, validationRules);
13417
- if (validationErrors.length > 0) {
13418
- return [invalidRequest(validationErrors)];
13419
- }
13420
- const introspection = isIntrospectionQuery(query);
13421
- if (introspection && !router.options?.introspectionEnabled) {
13422
- return [forbidden];
13423
- }
13424
- const dataLoader = new DataLoader((keys) => repo.readReferences(keys));
13425
- let result = introspection && introspectionResults.get(query);
13426
- if (!result) {
13427
- result = await execute({
13428
- schema,
13429
- document,
13430
- contextValue: { repo, dataLoader },
13431
- operationName,
13432
- variableValues: variables,
13433
- });
13434
- }
13435
- return [allOk, result];
13476
+ function isFieldRequested(info, fieldName) {
13477
+ return info.fieldNodes.some((fieldNode) => fieldNode.selectionSet?.selections.some((selection) => {
13478
+ return selection.kind === 'Field' && selection.name.value === fieldName;
13479
+ }));
13436
13480
  }
13437
13481
  /**
13438
- * Returns true if the query is a GraphQL introspection query.
13439
- *
13440
- * Introspection queries ask for the schema, which is expensive.
13441
- *
13442
- * See: https://graphql.org/learn/introspection/
13443
- * @param query The GraphQL query.
13444
- * @returns True if the query is an introspection query.
13482
+ * Returns an OperationOutcome for GraphQL errors.
13483
+ * @param errors Array of GraphQL errors.
13484
+ * @returns OperationOutcome with the GraphQL errors as OperationOutcome issues.
13445
13485
  */
13446
- function isIntrospectionQuery(query) {
13447
- return query.includes('query IntrospectionQuery') || query.includes('__schema') || query.includes('__type');
13486
+ function invalidRequest(errors) {
13487
+ return {
13488
+ resourceType: 'OperationOutcome',
13489
+ issue: errors.map((error) => ({
13490
+ severity: 'error',
13491
+ code: 'invalid',
13492
+ details: { text: error.message },
13493
+ })),
13494
+ };
13448
13495
  }
13449
- function getRootSchema() {
13450
- if (!rootSchema) {
13451
- rootSchema = buildRootSchema();
13496
+
13497
+ const inputTypeCache = {
13498
+ ...typeCache,
13499
+ };
13500
+ function getGraphQLInputType(inputType, nameSuffix) {
13501
+ let result = inputTypeCache[inputType];
13502
+ if (!result) {
13503
+ result = buildGraphQLInputType(inputType, nameSuffix);
13504
+ inputTypeCache[inputType] = result;
13452
13505
  }
13453
- return rootSchema;
13506
+ return result;
13454
13507
  }
13455
- function buildRootSchema() {
13456
- // First, create placeholder types
13457
- // We need this first for circular dependencies
13458
- for (const resourceType of getResourceTypes()) {
13459
- outputTypeCache[resourceType] = buildGraphQLOutputType(resourceType);
13460
- }
13461
- // Next, fill in all of the type properties
13508
+ function buildGraphQLInputType(resourceType, nameSuffix) {
13509
+ const schema = getResourceTypeSchema(resourceType);
13510
+ return new GraphQLInputObjectType({
13511
+ name: resourceType + nameSuffix,
13512
+ description: schema.description,
13513
+ fields: () => buildGraphQLInputFields(resourceType, nameSuffix),
13514
+ });
13515
+ }
13516
+ function buildGraphQLInputFields(resourceType, nameSuffix) {
13462
13517
  const fields = {};
13463
- const mutationFields = {};
13464
- for (const resourceType of getResourceTypes()) {
13465
- const graphQLOutputType = getGraphQLOutputType(resourceType);
13466
- // Get resource by ID
13467
- fields[resourceType] = {
13468
- type: graphQLOutputType,
13469
- args: {
13470
- id: {
13471
- type: new GraphQLNonNull(GraphQLID),
13472
- description: resourceType + ' ID',
13473
- },
13474
- },
13475
- resolve: resolveById,
13476
- };
13477
- // Search resource by search parameters
13478
- fields[resourceType + 'List'] = {
13479
- type: new GraphQLList(graphQLOutputType),
13480
- args: buildSearchArgs(resourceType),
13481
- resolve: resolveBySearch,
13482
- };
13483
- // FHIR GraphQL Connection API
13484
- fields[resourceType + 'Connection'] = {
13485
- type: buildConnectionType(resourceType, graphQLOutputType),
13486
- args: buildSearchArgs(resourceType),
13487
- resolve: resolveByConnectionApi,
13488
- };
13489
- // Mutation API
13490
- mutationFields[resourceType + 'Create'] = {
13491
- type: graphQLOutputType,
13492
- args: buildCreateArgs(resourceType),
13493
- resolve: resolveByCreate,
13494
- };
13495
- mutationFields[resourceType + 'Update'] = {
13496
- type: graphQLOutputType,
13497
- args: buildUpdateArgs(resourceType),
13498
- resolve: resolveByUpdate,
13499
- };
13500
- mutationFields[resourceType + 'Delete'] = {
13501
- type: graphQLOutputType,
13502
- args: {
13503
- id: {
13504
- type: new GraphQLNonNull(GraphQLID),
13505
- description: resourceType + ' ID',
13506
- },
13507
- },
13508
- resolve: resolveByDelete,
13518
+ // Add resourceType field for root resource
13519
+ if (isResourceType(resourceType)) {
13520
+ const propertyFieldConfig = {
13521
+ description: 'The type of resource',
13522
+ type: GraphQLString,
13509
13523
  };
13524
+ fields['resourceType'] = propertyFieldConfig;
13510
13525
  }
13511
- return new GraphQLSchema({
13512
- query: new GraphQLObjectType({
13513
- name: 'QueryType',
13514
- fields,
13515
- }),
13516
- mutation: new GraphQLObjectType({
13517
- name: 'MutationType',
13518
- fields: mutationFields,
13519
- }),
13520
- });
13526
+ buildInputPropertyFields(resourceType, fields, nameSuffix);
13527
+ return fields;
13521
13528
  }
13529
+ function buildInputPropertyFields(resourceType, fields, nameSuffix) {
13530
+ const schema = getResourceTypeSchema(resourceType);
13531
+ const properties = schema.properties;
13532
+ for (const key of Object.keys(properties)) {
13533
+ const elementDefinition = getElementDefinition(resourceType, key);
13534
+ for (const type of elementDefinition.type) {
13535
+ buildInputPropertyField(fields, key, elementDefinition, type, nameSuffix);
13536
+ }
13537
+ }
13538
+ }
13539
+ function buildInputPropertyField(fields, key, elementDefinition, elementDefinitionType, nameSuffix) {
13540
+ let typeName = elementDefinitionType.code;
13541
+ if (typeName === 'Element' || typeName === 'BackboneElement') {
13542
+ typeName = buildTypeName(elementDefinition.path?.split('.'));
13543
+ }
13544
+ const fieldConfig = {
13545
+ description: elementDefinition.short,
13546
+ type: getGraphQLInputType(typeName, nameSuffix),
13547
+ };
13548
+ if (elementDefinition.max === '*') {
13549
+ fieldConfig.type = new GraphQLList(getGraphQLInputType(typeName, nameSuffix));
13550
+ }
13551
+ const propertyName = key.replace('[x]', capitalize(elementDefinitionType.code));
13552
+ fields[propertyName] = fieldConfig;
13553
+ }
13554
+
13555
+ const outputTypeCache = {
13556
+ ...typeCache,
13557
+ };
13522
13558
  function getGraphQLOutputType(inputType) {
13523
13559
  let result = outputTypeCache[inputType];
13524
13560
  if (!result) {
@@ -13527,14 +13563,6 @@ function getGraphQLOutputType(inputType) {
13527
13563
  }
13528
13564
  return result;
13529
13565
  }
13530
- function getGraphQLInputType(inputType, nameSuffix) {
13531
- let result = inputTypeCache[inputType];
13532
- if (!result) {
13533
- result = buildGraphQLInputType(inputType, nameSuffix);
13534
- inputTypeCache[inputType] = result;
13535
- }
13536
- return result;
13537
- }
13538
13566
  function buildGraphQLOutputType(resourceType) {
13539
13567
  if (resourceType === 'ResourceList') {
13540
13568
  return new GraphQLUnionType({
@@ -13552,33 +13580,12 @@ function buildGraphQLOutputType(resourceType) {
13552
13580
  fields: () => buildGraphQLOutputFields(resourceType),
13553
13581
  });
13554
13582
  }
13555
- function buildGraphQLInputType(resourceType, nameSuffix) {
13556
- const schema = getResourceTypeSchema(resourceType);
13557
- return new GraphQLInputObjectType({
13558
- name: resourceType + nameSuffix,
13559
- description: schema.description,
13560
- fields: () => buildGraphQLInputFields(resourceType, nameSuffix),
13561
- });
13562
- }
13563
13583
  function buildGraphQLOutputFields(resourceType) {
13564
13584
  const fields = {};
13565
13585
  buildOutputPropertyFields(resourceType, fields);
13566
13586
  buildReverseLookupFields(resourceType, fields);
13567
13587
  return fields;
13568
13588
  }
13569
- function buildGraphQLInputFields(resourceType, nameSuffix) {
13570
- const fields = {};
13571
- // Add resourceType field for root resource
13572
- if (isResourceType(resourceType)) {
13573
- const propertyFieldConfig = {
13574
- description: 'The type of resource',
13575
- type: GraphQLString,
13576
- };
13577
- fields['resourceType'] = propertyFieldConfig;
13578
- }
13579
- buildInputPropertyFields(resourceType, fields, nameSuffix);
13580
- return fields;
13581
- }
13582
13589
  function buildOutputPropertyFields(resourceType, fields) {
13583
13590
  const schema = getResourceTypeSchema(resourceType);
13584
13591
  const properties = schema.properties;
@@ -13602,16 +13609,6 @@ function buildOutputPropertyFields(resourceType, fields) {
13602
13609
  }
13603
13610
  }
13604
13611
  }
13605
- function buildInputPropertyFields(resourceType, fields, nameSuffix) {
13606
- const schema = getResourceTypeSchema(resourceType);
13607
- const properties = schema.properties;
13608
- for (const key of Object.keys(properties)) {
13609
- const elementDefinition = getElementDefinition(resourceType, key);
13610
- for (const type of elementDefinition.type) {
13611
- buildInputPropertyField(fields, key, elementDefinition, type, nameSuffix);
13612
- }
13613
- }
13614
- }
13615
13612
  function buildOutputPropertyField(fields, key, elementDefinition, elementDefinitionType) {
13616
13613
  let typeName = elementDefinitionType.code;
13617
13614
  if (typeName === 'Element' || typeName === 'BackboneElement') {
@@ -13628,21 +13625,6 @@ function buildOutputPropertyField(fields, key, elementDefinition, elementDefinit
13628
13625
  const propertyName = key.replace('[x]', capitalize(elementDefinitionType.code));
13629
13626
  fields[propertyName] = fieldConfig;
13630
13627
  }
13631
- function buildInputPropertyField(fields, key, elementDefinition, elementDefinitionType, nameSuffix) {
13632
- let typeName = elementDefinitionType.code;
13633
- if (typeName === 'Element' || typeName === 'BackboneElement') {
13634
- typeName = buildTypeName(elementDefinition.path?.split('.'));
13635
- }
13636
- const fieldConfig = {
13637
- description: elementDefinition.short,
13638
- type: getGraphQLInputType(typeName, nameSuffix),
13639
- };
13640
- if (elementDefinition.max === '*') {
13641
- fieldConfig.type = new GraphQLList(getGraphQLInputType(typeName, nameSuffix));
13642
- }
13643
- const propertyName = key.replace('[x]', capitalize(elementDefinitionType.code));
13644
- fields[propertyName] = fieldConfig;
13645
- }
13646
13628
  /**
13647
13629
  * Builds field arguments for a list property.
13648
13630
  *
@@ -13772,41 +13754,213 @@ function buildReverseLookupFields(resourceType, fields) {
13772
13754
  }
13773
13755
  }
13774
13756
  }
13775
- function buildSearchArgs(resourceType) {
13776
- const args = {
13777
- _count: {
13778
- type: GraphQLInt,
13779
- description: 'Specify how many elements to return from a repeating list.',
13780
- },
13781
- _offset: {
13782
- type: GraphQLInt,
13783
- description: 'Specify the offset to start at for a repeating element.',
13784
- },
13785
- _sort: {
13786
- type: GraphQLString,
13787
- description: 'Specify the sort order by comma-separated list of sort rules in priority order.',
13788
- },
13789
- _id: {
13790
- type: GraphQLString,
13791
- description: 'Select resources based on the logical id of the resource.',
13792
- },
13793
- _lastUpdated: {
13794
- type: GraphQLString,
13795
- description: 'Select resources based on the last time they were changed.',
13796
- },
13797
- };
13798
- const searchParams = getSearchParameters(resourceType);
13799
- if (searchParams) {
13800
- for (const [code, searchParam] of Object.entries(searchParams)) {
13801
- // GraphQL does not support dashes in argument names
13802
- // So convert dashes to underscores
13803
- args[fhirParamToGraphQLField(code)] = {
13804
- type: GraphQLString,
13805
- description: searchParam.description,
13806
- };
13807
- }
13757
+ function getOutputPropertyType(elementDefinition, typeName) {
13758
+ const graphqlType = getGraphQLOutputType(typeName);
13759
+ if (elementDefinition.max === '*') {
13760
+ return new GraphQLList(graphqlType);
13761
+ }
13762
+ return graphqlType;
13763
+ }
13764
+ /**
13765
+ * GraphQL resolver for fields.
13766
+ * In the common case, this is just a matter of returning the field value from the source object.
13767
+ * If the field is a list and the user specifies list arguments, then we can apply those arguments here.
13768
+ * @param source The source. This is the object that contains the field.
13769
+ * @param args The GraphQL search arguments.
13770
+ * @param _ctx The GraphQL context.
13771
+ * @param info The GraphQL resolve info. This includes the field name.
13772
+ * @returns Promise to read the resoure for the query.
13773
+ */
13774
+ async function resolveField(source, args, _ctx, info) {
13775
+ const fieldValue = source?.[info.fieldName];
13776
+ if (!args || !fieldValue) {
13777
+ return fieldValue;
13778
+ }
13779
+ const { _offset, _count, fhirpath, ...rest } = args;
13780
+ let array = fieldValue;
13781
+ for (const [key, value] of Object.entries(rest)) {
13782
+ array = array.filter((item) => item[key] === value);
13783
+ }
13784
+ if (fhirpath) {
13785
+ array = array.filter((item) => toJsBoolean(evalFhirPathTyped(fhirpath, [toTypedValue(item)])));
13786
+ }
13787
+ if (_offset) {
13788
+ array = array.slice(_offset);
13789
+ }
13790
+ if (_count) {
13791
+ array = array.slice(0, _count);
13792
+ }
13793
+ return array;
13794
+ }
13795
+ /**
13796
+ * GraphQL data loader for Reference requests.
13797
+ * This is a special data loader for following Reference objects.
13798
+ * @param source The source/root. This should always be null for our top level readers.
13799
+ * @param _args The GraphQL search arguments.
13800
+ * @param ctx The GraphQL context.
13801
+ * @returns Promise to read the resoure(s) for the query.
13802
+ */
13803
+ async function resolveByReference(source, _args, ctx) {
13804
+ try {
13805
+ return await ctx.dataLoader.load(source);
13806
+ }
13807
+ catch (err) {
13808
+ throw new OperationOutcomeError(normalizeOperationOutcome(err), err);
13809
+ }
13810
+ }
13811
+ /**
13812
+ * GraphQL type resolver for resources.
13813
+ * When loading a resource via reference, GraphQL needs to know the type of the resource.
13814
+ * @param resource The loaded resource.
13815
+ * @returns The GraphQL type of the resource.
13816
+ */
13817
+ function resolveTypeByReference(resource) {
13818
+ const resourceType = resource?.resourceType;
13819
+ if (!resourceType) {
13820
+ return undefined;
13821
+ }
13822
+ return getGraphQLOutputType(resourceType).name;
13823
+ }
13824
+
13825
+ /**
13826
+ * Cache of "introspection" query results.
13827
+ * Common case is the standard schema query from GraphiQL and Insomnia.
13828
+ * The result is big and somewhat computationally expensive.
13829
+ */
13830
+ const introspectionResults = new LRUCache();
13831
+ /**
13832
+ * Cached GraphQL schema.
13833
+ * This should be initialized at server startup.
13834
+ */
13835
+ let rootSchema;
13836
+ /**
13837
+ * Handles FHIR GraphQL requests.
13838
+ *
13839
+ * See: https://www.hl7.org/fhir/graphql.html
13840
+ * @param req The request details.
13841
+ * @param repo The current user FHIR repository.
13842
+ * @param router The router for router options.
13843
+ * @returns The response.
13844
+ */
13845
+ async function graphqlHandler(req, repo, router) {
13846
+ const { query, operationName, variables } = req.body;
13847
+ if (!query) {
13848
+ return [badRequest('Must provide query.')];
13849
+ }
13850
+ let document;
13851
+ try {
13852
+ document = parse(query);
13853
+ }
13854
+ catch (err) {
13855
+ return [badRequest('GraphQL syntax error.')];
13856
+ }
13857
+ const schema = getRootSchema();
13858
+ const validationRules = [...specifiedRules, MaxDepthRule];
13859
+ const validationErrors = validate(schema, document, validationRules);
13860
+ if (validationErrors.length > 0) {
13861
+ return [invalidRequest(validationErrors)];
13862
+ }
13863
+ const introspection = isIntrospectionQuery(query);
13864
+ if (introspection && !router.options?.introspectionEnabled) {
13865
+ return [forbidden];
13866
+ }
13867
+ const dataLoader = new DataLoader((keys) => repo.readReferences(keys));
13868
+ let result = introspection && introspectionResults.get(query);
13869
+ if (!result) {
13870
+ result = await execute({
13871
+ schema,
13872
+ document,
13873
+ contextValue: { repo, dataLoader },
13874
+ operationName,
13875
+ variableValues: variables,
13876
+ });
13877
+ }
13878
+ return [allOk, result];
13879
+ }
13880
+ /**
13881
+ * Returns true if the query is a GraphQL introspection query.
13882
+ *
13883
+ * Introspection queries ask for the schema, which is expensive.
13884
+ *
13885
+ * See: https://graphql.org/learn/introspection/
13886
+ * @param query The GraphQL query.
13887
+ * @returns True if the query is an introspection query.
13888
+ */
13889
+ function isIntrospectionQuery(query) {
13890
+ return query.includes('query IntrospectionQuery') || query.includes('__schema') || query.includes('__type');
13891
+ }
13892
+ function getRootSchema() {
13893
+ if (!rootSchema) {
13894
+ rootSchema = buildRootSchema();
13895
+ }
13896
+ return rootSchema;
13897
+ }
13898
+ function buildRootSchema() {
13899
+ // First, create placeholder types
13900
+ // We need this first for circular dependencies
13901
+ for (const resourceType of getResourceTypes()) {
13902
+ outputTypeCache[resourceType] = buildGraphQLOutputType(resourceType);
13808
13903
  }
13809
- return args;
13904
+ // Next, fill in all of the type properties
13905
+ const fields = {};
13906
+ const mutationFields = {};
13907
+ for (const resourceType of getResourceTypes()) {
13908
+ const graphQLOutputType = getGraphQLOutputType(resourceType);
13909
+ // Get resource by ID
13910
+ fields[resourceType] = {
13911
+ type: graphQLOutputType,
13912
+ args: {
13913
+ id: {
13914
+ type: new GraphQLNonNull(GraphQLID),
13915
+ description: resourceType + ' ID',
13916
+ },
13917
+ },
13918
+ resolve: resolveById,
13919
+ };
13920
+ // Search resource by search parameters
13921
+ fields[resourceType + 'List'] = {
13922
+ type: new GraphQLList(graphQLOutputType),
13923
+ args: buildSearchArgs(resourceType),
13924
+ resolve: resolveBySearch,
13925
+ };
13926
+ // FHIR GraphQL Connection API
13927
+ fields[resourceType + 'Connection'] = {
13928
+ type: buildConnectionType(resourceType, graphQLOutputType),
13929
+ args: buildSearchArgs(resourceType),
13930
+ resolve: resolveByConnectionApi,
13931
+ };
13932
+ // Mutation API
13933
+ mutationFields[resourceType + 'Create'] = {
13934
+ type: graphQLOutputType,
13935
+ args: buildCreateArgs(resourceType),
13936
+ resolve: resolveByCreate,
13937
+ };
13938
+ mutationFields[resourceType + 'Update'] = {
13939
+ type: graphQLOutputType,
13940
+ args: buildUpdateArgs(resourceType),
13941
+ resolve: resolveByUpdate,
13942
+ };
13943
+ mutationFields[resourceType + 'Delete'] = {
13944
+ type: graphQLOutputType,
13945
+ args: {
13946
+ id: {
13947
+ type: new GraphQLNonNull(GraphQLID),
13948
+ description: resourceType + ' ID',
13949
+ },
13950
+ },
13951
+ resolve: resolveByDelete,
13952
+ };
13953
+ }
13954
+ return new GraphQLSchema({
13955
+ query: new GraphQLObjectType({
13956
+ name: 'QueryType',
13957
+ fields,
13958
+ }),
13959
+ mutation: new GraphQLObjectType({
13960
+ name: 'MutationType',
13961
+ fields: mutationFields,
13962
+ }),
13963
+ });
13810
13964
  }
13811
13965
  function buildCreateArgs(resourceType) {
13812
13966
  const args = {
@@ -13830,13 +13984,6 @@ function buildUpdateArgs(resourceType) {
13830
13984
  };
13831
13985
  return args;
13832
13986
  }
13833
- function getOutputPropertyType(elementDefinition, typeName) {
13834
- const graphqlType = getGraphQLOutputType(typeName);
13835
- if (elementDefinition.max === '*') {
13836
- return new GraphQLList(graphqlType);
13837
- }
13838
- return graphqlType;
13839
- }
13840
13987
  function buildConnectionType(resourceType, resourceGraphQLType) {
13841
13988
  return new GraphQLObjectType({
13842
13989
  name: resourceType + 'Connection',
@@ -13861,23 +14008,6 @@ function buildConnectionType(resourceType, resourceGraphQLType) {
13861
14008
  },
13862
14009
  });
13863
14010
  }
13864
- /**
13865
- * GraphQL data loader for search requests.
13866
- * The field name should always end with "List" (i.e., "Patient" search uses "PatientList").
13867
- * The search args should be FHIR search parameters.
13868
- * @param source The source/root. This should always be null for our top level readers.
13869
- * @param args The GraphQL search arguments.
13870
- * @param ctx The GraphQL context.
13871
- * @param info The GraphQL resolve info. This includes the schema, and additional field details.
13872
- * @returns Promise to read the resoures for the query.
13873
- */
13874
- async function resolveBySearch(source, args, ctx, info) {
13875
- const fieldName = info.fieldName;
13876
- const resourceType = fieldName.substring(0, fieldName.length - 'List'.length);
13877
- const searchRequest = parseSearchArgs(resourceType, source, args);
13878
- const bundle = await ctx.repo.search(searchRequest);
13879
- return bundle.entry?.map((e) => e.resource);
13880
- }
13881
14011
  /**
13882
14012
  * GraphQL data loader for search requests.
13883
14013
  * The field name should always end with "List" (i.e., "Patient" search uses "PatientList").
@@ -13925,66 +14055,6 @@ async function resolveById(_source, args, ctx, info) {
13925
14055
  throw new OperationOutcomeError(normalizeOperationOutcome(err), err);
13926
14056
  }
13927
14057
  }
13928
- /**
13929
- * GraphQL data loader for Reference requests.
13930
- * This is a special data loader for following Reference objects.
13931
- * @param source The source/root. This should always be null for our top level readers.
13932
- * @param _args The GraphQL search arguments.
13933
- * @param ctx The GraphQL context.
13934
- * @returns Promise to read the resoure(s) for the query.
13935
- */
13936
- async function resolveByReference(source, _args, ctx) {
13937
- try {
13938
- return await ctx.dataLoader.load(source);
13939
- }
13940
- catch (err) {
13941
- throw new OperationOutcomeError(normalizeOperationOutcome(err), err);
13942
- }
13943
- }
13944
- /**
13945
- * GraphQL type resolver for resources.
13946
- * When loading a resource via reference, GraphQL needs to know the type of the resource.
13947
- * @param resource The loaded resource.
13948
- * @returns The GraphQL type of the resource.
13949
- */
13950
- function resolveTypeByReference(resource) {
13951
- const resourceType = resource?.resourceType;
13952
- if (!resourceType) {
13953
- return undefined;
13954
- }
13955
- return getGraphQLOutputType(resourceType).name;
13956
- }
13957
- /**
13958
- * GraphQL resolver for fields.
13959
- * In the common case, this is just a matter of returning the field value from the source object.
13960
- * If the field is a list and the user specifies list arguments, then we can apply those arguments here.
13961
- * @param source The source. This is the object that contains the field.
13962
- * @param args The GraphQL search arguments.
13963
- * @param _ctx The GraphQL context.
13964
- * @param info The GraphQL resolve info. This includes the field name.
13965
- * @returns Promise to read the resoure for the query.
13966
- */
13967
- async function resolveField(source, args, _ctx, info) {
13968
- const fieldValue = source?.[info.fieldName];
13969
- if (!args || !fieldValue) {
13970
- return fieldValue;
13971
- }
13972
- const { _offset, _count, fhirpath, ...rest } = args;
13973
- let array = fieldValue;
13974
- for (const [key, value] of Object.entries(rest)) {
13975
- array = array.filter((item) => item[key] === value);
13976
- }
13977
- if (fhirpath) {
13978
- array = array.filter((item) => toJsBoolean(evalFhirPathTyped(fhirpath, [toTypedValue(item)])));
13979
- }
13980
- if (_offset) {
13981
- array = array.slice(_offset);
13982
- }
13983
- if (_count) {
13984
- array = array.slice(0, _count);
13985
- }
13986
- return array;
13987
- }
13988
14058
  /**
13989
14059
  * GraphQL resolver function for create requests.
13990
14060
  * The field name should end with "Create" (i.e., "PatientCreate" for updating a Patient).
@@ -14047,37 +14117,6 @@ async function resolveByDelete(_source, args, ctx, info) {
14047
14117
  const resourceType = fieldName.substring(0, fieldName.length - 'Delete'.length);
14048
14118
  await ctx.repo.deleteResource(resourceType, args.id);
14049
14119
  }
14050
- function parseSearchArgs(resourceType, source, args) {
14051
- let referenceFilter = undefined;
14052
- if (source) {
14053
- // _reference is a required field for reverse lookup searches
14054
- // The GraphQL parser will validate that it is there.
14055
- const reference = args['_reference'];
14056
- delete args['_reference'];
14057
- referenceFilter = {
14058
- code: reference,
14059
- operator: Operator.EQUALS,
14060
- value: getReferenceString(source),
14061
- };
14062
- }
14063
- // Reverse the transform of dashes to underscores, back to dashes
14064
- args = Object.fromEntries(Object.entries(args).map(([key, value]) => [graphQLFieldToFhirParam(key), value]));
14065
- // Parse the search request
14066
- const searchRequest = parseSearchRequest(resourceType, args);
14067
- // If a reverse lookup filter was specified,
14068
- // add it to the search request.
14069
- if (referenceFilter) {
14070
- const existingFilters = searchRequest.filters || [];
14071
- searchRequest.filters = [referenceFilter, ...existingFilters];
14072
- }
14073
- return searchRequest;
14074
- }
14075
- function fhirParamToGraphQLField(code) {
14076
- return code.replaceAll('-', '_');
14077
- }
14078
- function graphQLFieldToFhirParam(code) {
14079
- return code.startsWith('_') ? code : code.replaceAll('_', '-');
14080
- }
14081
14120
  /**
14082
14121
  * Custom GraphQL rule that enforces max depth constraint.
14083
14122
  * @param context The validation context.
@@ -14103,42 +14142,6 @@ const MaxDepthRule = (context) => ({
14103
14142
  }
14104
14143
  },
14105
14144
  });
14106
- /**
14107
- * Returns the depth of the GraphQL node in a query.
14108
- * We use "selections" as the representation of depth.
14109
- * As a rough approximation, it's the number of indentations in a well formatted query.
14110
- * @param path The GraphQL node path.
14111
- * @returns The "depth" of the node.
14112
- */
14113
- function getDepth(path) {
14114
- return path.filter((p) => p === 'selections').length;
14115
- }
14116
- /**
14117
- * Returns true if the field is requested in the GraphQL query.
14118
- * @param info The GraphQL resolve info. This includes the field name.
14119
- * @param fieldName The field name to check.
14120
- * @returns True if the field is requested in the GraphQL query.
14121
- */
14122
- function isFieldRequested(info, fieldName) {
14123
- return info.fieldNodes.some((fieldNode) => fieldNode.selectionSet?.selections.some((selection) => {
14124
- return selection.kind === 'Field' && selection.name.value === fieldName;
14125
- }));
14126
- }
14127
- /**
14128
- * Returns an OperationOutcome for GraphQL errors.
14129
- * @param errors Array of GraphQL errors.
14130
- * @returns OperationOutcome with the GraphQL errors as OperationOutcome issues.
14131
- */
14132
- function invalidRequest(errors) {
14133
- return {
14134
- resourceType: 'OperationOutcome',
14135
- issue: errors.map((error) => ({
14136
- severity: 'error',
14137
- code: 'invalid',
14138
- details: { text: error.message },
14139
- })),
14140
- };
14141
- }
14142
14145
 
14143
14146
  class Router {
14144
14147
  constructor() {