@quicore/task-queue-fhir-tools 1.1.0

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.
package/.babelrc ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "presets": [
3
+ ["@babel/env", {
4
+ "targets": {
5
+ "node": "current"
6
+ }
7
+ }]
8
+ ]
9
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 quicore
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @quicore/task-queue-fhir-tools
2
+
3
+ A specialized library for generating MongoDB update queries from FHIR resources. It extends the standard FHIR-to-Mongo mapping with support for **deterministic IDs**, **multi-tenant data segregation (Customer IDs)**, and **Task ID association**.
4
+
5
+ ## Features
6
+
7
+ * **Deterministic ID Generation**: Creates consistent MongoDB `_id` values based on resource content and integration context.
8
+ * **Multi-Tenancy**: Support for tagging resources with `customerId` and optionally segregating data into customer-specific records.
9
+ * **Task Association**: Automatically links FHIR resources to specific Task IDs for workflow tracking.
10
+ * **Bulk Processing**: Efficiently process entire FHIR Bundles into categorized MongoDB `bulkWrite` operations.
11
+ * **Chainable API**: Fluid interface for setting metadata and configuration.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @quicore/task-queue-fhir-tools
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Usage
24
+
25
+ ### 1. Processing a Single Resource
26
+
27
+ Use `TaskFHIRQuery` to generate an update query for an individual FHIR resource.
28
+
29
+ ```javascript
30
+ import { TaskFHIRQuery } from '@quicore/task-queue-fhir-tools';
31
+
32
+ const patientResource = {
33
+ resourceType: "Patient",
34
+ id: "123",
35
+ name: [{ family: "Doe", given: ["John"] }]
36
+ };
37
+
38
+ const queryGenerator = new TaskFHIRQuery(patientResource)
39
+ .setIntegrationId("my-integration-01")
40
+ .setCustomerId("cust_99")
41
+ .setTaskId("task_abc_123");
42
+
43
+ const mongoQueries = queryGenerator.query();
44
+ // Returns an array of updateOne operations
45
+
46
+ ```
47
+
48
+ ### 2. Processing a FHIR Bundle
49
+
50
+ Use `TaskFHIRBundleProcessor` to process a bundle and group queries by `resourceType` for efficient database writes.
51
+
52
+ ```javascript
53
+ import { TaskFHIRBundleProcessor } from '@quicore/task-queue-fhir-tools';
54
+
55
+ const bundle = {
56
+ resourceType: "Bundle",
57
+ entry: [ /* ... FHIR resources ... */ ]
58
+ };
59
+
60
+ const processor = new TaskFHIRBundleProcessor(bundle)
61
+ .setCustomerId(["cust_A", "cust_B"])
62
+ .setTaskId("workflow_456")
63
+ .customerSpecificDataStore(true); // Generates separate records for each customer
64
+
65
+ const queriesByType = processor.query();
66
+
67
+ /* Output format:
68
+ {
69
+ "Patient": [ { updateOne: { ... } }, ... ],
70
+ "Observation": [ { updateOne: { ... } }, ... ]
71
+ }
72
+ */
73
+
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Key Concepts
79
+
80
+ ### Customer Specific Data Storage
81
+
82
+ By default, the processor adds customer IDs to an array (`_sourceCustomerId`) within a single shared record. If you call `.customerSpecificDataStore(true)`, the library will:
83
+
84
+ 1. Generate a unique record for **each** customer ID provided.
85
+ 2. Append the customer ID to the canonical string used for hashing the `_id`.
86
+ 3. Set a flag `_customerSpecificStore: true` in the document.
87
+
88
+ ### Canonical String Construction
89
+
90
+ The deterministic `_id` is derived from a canonical string. If customer segregation is enabled, the format is:
91
+ `{integrationId}::{resourceType}::{resourceId}::{customerId}`
92
+
93
+ ---
94
+
95
+ ## API Reference
96
+
97
+ ### `TaskFHIRQuery`
98
+
99
+ | Method | Description |
100
+ | --- | --- |
101
+ | `setTaskId(string)` | Associates the resource with a specific Task ID. |
102
+ | `setCustomerId(string \| string[])` | Adds one or more customer identifiers. |
103
+ | `customerSpecificDataStore(boolean)` | If true, creates unique records per customer. |
104
+ | `query(upsert = true)` | Finalizes and returns the MongoDB update array. |
105
+
106
+ ### `TaskFHIRBundleProcessor`
107
+
108
+ | Method | Description |
109
+ | --- | --- |
110
+ | `setCustomerId(string \| string[])` | Sets the source customer(s) for all resources in the bundle. |
111
+ | `setTaskId(string)` | Sets the task ID for all resources in the bundle. |
112
+ | `query()` | Returns an object containing arrays of queries keyed by resource type. |
113
+
114
+ ---
115
+
116
+ ## License
117
+
118
+ MIT © quicore
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.TaskFHIRBundleProcessor = void 0;
7
+ var _fhirQueryMongoStore = require("@healthcare-interoperability/fhir-query-mongo-store");
8
+ var _TaskFHIRQuery = require("./TaskFHIRQuery");
9
+ class TaskFHIRBundleProcessor extends _fhirQueryMongoStore.FHIRMongoBundleProcessor {
10
+ /**
11
+ * A flag indicating whether to store data specific to each customer ID.
12
+ * @private
13
+ * @type {boolean}
14
+ */
15
+ customerSpecificData = false;
16
+
17
+ /**
18
+ * The customer ID(s) associated with the resources in the bundle.
19
+ * @private
20
+ * @type {string | string[] | undefined}
21
+ */
22
+ sourceCustomerId;
23
+
24
+ /**
25
+ * The task ID associated with the resources in the bundle.
26
+ * @private
27
+ * @type {string | undefined}
28
+ */
29
+ taskId;
30
+
31
+ /**
32
+ * Creates an instance of TaskFHIRBundleProcessor.
33
+ * @param {object} bundle - The FHIR Bundle resource.
34
+ */
35
+ constructor(bundle) {
36
+ super(bundle);
37
+ this.customerSpecificData = false;
38
+ }
39
+
40
+ /**
41
+ * Enables or disables customer-specific data storage for the bundle.
42
+ * @param {boolean} [enable=true] - Whether to enable customer-specific data storage.
43
+ * @returns {this} The FHIRBundleProcessor instance for chaining.
44
+ */
45
+ customerSpecificDataStore(enable = true) {
46
+ this.customerSpecificData = enable;
47
+ return this;
48
+ }
49
+
50
+ /**
51
+ * Sets the customer ID(s) associated with the resources in the bundle.
52
+ * @param {string | string[]} sourceCustomerId - The customer ID(s).
53
+ * @returns {this} The FHIRBundleProcessor instance for chaining.
54
+ */
55
+ setCustomerId(sourceCustomerId) {
56
+ this.sourceCustomerId = sourceCustomerId;
57
+ return this;
58
+ }
59
+
60
+ /**
61
+ * Sets the task ID associated with the resources in the bundle.
62
+ * @param {string} taskId - The task ID.
63
+ * @returns {this} The FHIRBundleProcessor instance for chaining.
64
+ */
65
+ setTaskId(taskId) {
66
+ this.taskId = taskId;
67
+ return this;
68
+ }
69
+ _getQueryInstance(resource) {
70
+ return new _TaskFHIRQuery.TaskFHIRQuery(resource);
71
+ }
72
+
73
+ /**
74
+ * Prepares a FHIRQuery object for a single resource.
75
+ * @private
76
+ * @param {object} resource - The FHIR resource.
77
+ * @returns {Array<{query: {updateOne: object}, resourceType: string | undefined}>} An array of queries.
78
+ */
79
+ _prepareQuery(resource) {
80
+ const query = this._getQueryInstance(resource);
81
+ if (this.integrationId) query.setIntegrationId(this.integrationId);
82
+ if (query instanceof _TaskFHIRQuery.TaskFHIRQuery) {
83
+ if (this.sourceCustomerId) query.setCustomerId(this.sourceCustomerId);
84
+ if (this.taskId) query.setTaskId(this.taskId);
85
+ if (this.customerSpecificData) query.customerSpecificDataStore(true);
86
+ return query.query();
87
+ }
88
+ }
89
+ }
90
+ exports.TaskFHIRBundleProcessor = TaskFHIRBundleProcessor;
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.TaskFHIRQuery = void 0;
7
+ var _fhirQueryMongoStore = require("@healthcare-interoperability/fhir-query-mongo-store");
8
+ /**
9
+ * Generates a FHIR query for MongoDB with a deterministic ID, with added support for
10
+ * CustomerID specific deduplication and segregation, and Task ID association.
11
+ * Extends {@link FHIRMongoQuery}.
12
+ */
13
+ class TaskFHIRQuery extends _fhirQueryMongoStore.FHIRMongoQuery {
14
+ /**
15
+ * An array of customer IDs associated with this resource. Used for customer-specific data handling.
16
+ * @private
17
+ * @type {string[]}
18
+ */
19
+ customerId = [];
20
+
21
+ /**
22
+ * A flag indicating whether to store data specific to each customer ID.
23
+ * If true, separate queries will be generated for each customer ID.
24
+ * @private
25
+ * @type {boolean}
26
+ */
27
+ customerSpecificData = false;
28
+
29
+ /**
30
+ * The ID of the task associated with this resource.
31
+ * @private
32
+ * @type {string | undefined}
33
+ */
34
+ taskId;
35
+
36
+ /**
37
+ * Creates an instance of TQSFHIRQuery.
38
+ * @param {object} resource - The FHIR resource object.
39
+ */
40
+ constructor(resource) {
41
+ super(resource);
42
+ }
43
+
44
+ /**
45
+ * Sets the task ID associated with the resource.
46
+ * @param {string} taskId - The task ID.
47
+ * @returns {this} The TQSFHIRQuery instance for chaining.
48
+ */
49
+ setTaskId(taskId) {
50
+ this.taskId = taskId;
51
+ return this;
52
+ }
53
+
54
+ /**
55
+ * Sets the customer ID(s) associated with the resource. Accepts a single ID or an array of IDs.
56
+ * @param {string | string[]} customerId - The customer ID(s).
57
+ * @returns {this} The TQSFHIRQuery instance for chaining.
58
+ */
59
+ setCustomerId(customerId) {
60
+ if (!customerId) return this;
61
+ if (Array.isArray(customerId)) {
62
+ this.customerId.push(...customerId);
63
+ } else {
64
+ this.customerId.push(customerId);
65
+ }
66
+ return this;
67
+ }
68
+
69
+ /**
70
+ * Combines components in a canonical string format for hashing.
71
+ * @returns {string} Canonical string.
72
+ */
73
+ createCanonicalString() {
74
+ if (this.components.customerId) {
75
+ return `${this.components.integrationId}::${this.components.resourceType}::${this.components.resourceId}::${this.components.customerId}`;
76
+ }
77
+ return `${this.components.integrationId}::${this.components.resourceType}::${this.components.resourceId}`;
78
+ }
79
+
80
+ /**
81
+ * Enables or disables customer-specific data storage.
82
+ * When enabled, separate records are created for each customer ID.
83
+ * @param {boolean} [enable=true] - Whether to enable customer-specific data storage.
84
+ * @returns {this} The TQSFHIRQuery instance for chaining.
85
+ */
86
+ customerSpecificDataStore(enable = true) {
87
+ this.customerSpecificData = enable;
88
+ return this;
89
+ }
90
+
91
+ /**
92
+ * Builds an array of MongoDB update queries based on the resource and customer-specific settings.
93
+ * If `customerSpecificData` is enabled, it generates a query for each customer ID.
94
+ * @private
95
+ * @returns {Array<{id: string, set: object, setOnInsert: object, inc: object, addToSet: object}>}
96
+ * An array of objects, each containing the data for a MongoDB update operation.
97
+ */
98
+ queryBuilder() {
99
+ const queries = [];
100
+ const baseSetOnInsert = {
101
+ _processFlags: [],
102
+ _searchTags: [],
103
+ _changeLogs: []
104
+ };
105
+
106
+ /**
107
+ * Creates a query object with overrides for set and addToSet.
108
+ * @param {object} base - The base query data from prepareResource.
109
+ * @param {object} [addToSetOverrides={}] - Overrides for the $addToSet operator.
110
+ * @param {object} [setOverrides={}] - Overrides for the $set operator.
111
+ * @returns {{id: string, set: object, setOnInsert: object, inc: object, addToSet: object}}
112
+ */
113
+ const makeQuery = (base, addToSetOverrides = {}, setOverrides = {}) => ({
114
+ id: base.id,
115
+ set: {
116
+ ...base.set,
117
+ ...setOverrides,
118
+ syncedAt: new Date()
119
+ },
120
+ setOnInsert: {
121
+ ...base.setOnInsert,
122
+ ...baseSetOnInsert
123
+ },
124
+ inc: base.inc,
125
+ addToSet: {
126
+ ...(base.addToSet || {}),
127
+ ...addToSetOverrides
128
+ }
129
+ });
130
+ const dedupId = super.generate(); // Generate a common deduplication ID for the base resource
131
+
132
+ if (this.customerSpecificData && this.customerId?.length) {
133
+ for (const cid of this.customerId) {
134
+ this.setComponent('customerId', cid);
135
+ const base = super.prepareResource();
136
+ const addToSet = {
137
+ _sourceCustomerId: cid,
138
+ ...(this.taskId ? {
139
+ sourceTask: this.taskId
140
+ } : {})
141
+ };
142
+ queries.push(makeQuery(base, addToSet, {
143
+ _dedupId: dedupId,
144
+ _customerSpecificStore: true
145
+ }));
146
+ }
147
+ } else {
148
+ const base = super.prepareResource();
149
+ const addToSet = {
150
+ ...(this.customerId?.length ? {
151
+ _sourceCustomerId: {
152
+ $each: this.customerId
153
+ }
154
+ } : {}),
155
+ ...(this.taskId ? {
156
+ sourceTask: this.taskId
157
+ } : {})
158
+ };
159
+ queries.push(makeQuery(base, addToSet, {
160
+ _dedupId: dedupId
161
+ }));
162
+ }
163
+ return queries;
164
+ }
165
+
166
+ /**
167
+ * Generates an array of MongoDB update queries for the FHIR resource, handling customer-specific data if enabled.
168
+ * @param {boolean} [upsert=true] - Whether to perform an upsert operation.
169
+ * @returns {Array<{query: {updateOne: {filter: object, update: object, upsert: boolean}}, resourceType: string | undefined}>}
170
+ * An array of objects, each containing a MongoDB update query and the resource type.
171
+ */
172
+ query(upsert = true) {
173
+ return this.queryBuilder().map(({
174
+ id,
175
+ set,
176
+ setOnInsert,
177
+ inc,
178
+ addToSet
179
+ }) => ({
180
+ query: {
181
+ updateOne: {
182
+ filter: {
183
+ _id: id
184
+ },
185
+ update: {
186
+ $set: set,
187
+ $setOnInsert: setOnInsert,
188
+ $inc: inc,
189
+ $addToSet: addToSet
190
+ },
191
+ upsert
192
+ }
193
+ },
194
+ resourceType: this.resourceType
195
+ }));
196
+ }
197
+ }
198
+ exports.TaskFHIRQuery = TaskFHIRQuery;
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "TaskFHIRBundleProcessor", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _TaskFHIRBundleProcessor.TaskFHIRBundleProcessor;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "TaskFHIRQuery", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _TaskFHIRQuery.TaskFHIRQuery;
16
+ }
17
+ });
18
+ var _TaskFHIRBundleProcessor = require("./TaskFHIRBundleProcessor");
19
+ var _TaskFHIRQuery = require("./TaskFHIRQuery");
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@quicore/task-queue-fhir-tools",
3
+ "version": "1.1.0",
4
+ "description": "Helper tools for FHIR processing using Task Queue Server",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "build": "babel src -d dist"
8
+ },
9
+ "keywords": [
10
+ "fhir",
11
+ "healthcare",
12
+ "quicore",
13
+ "task-queue"
14
+ ],
15
+ "author": "quicore",
16
+ "license": "MIT",
17
+ "dependencies": {
18
+ "@healthcare-interoperability/fhir-query-mongo-store": "^1.0.0",
19
+ "@healthcare-interoperability/fhir-tools": "^1.0.0"
20
+ },
21
+ "devDependencies": {
22
+ "@babel/cli": "^7.27.0",
23
+ "@babel/core": "^7.26.10",
24
+ "@babel/preset-env": "^7.26.9"
25
+ },
26
+ "engines": {
27
+ "node": ">=18.0.0"
28
+ }
29
+ }