@cratis/arc 20.60.0 → 20.60.2
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/dist/cjs/queries/HubConnectionKeepAlive.js +24 -4
- package/dist/cjs/queries/HubConnectionKeepAlive.js.map +1 -1
- package/dist/cjs/queries/NullObservableQueryConnection.js +7 -2
- package/dist/cjs/queries/NullObservableQueryConnection.js.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.js +11 -1
- package/dist/cjs/queries/ObservableQueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryFor.js +1 -21
- package/dist/cjs/queries/QueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.js +35 -12
- package/dist/cjs/queries/QueryInstanceCache.js.map +1 -1
- package/dist/cjs/queries/QueryResult.js +30 -0
- package/dist/cjs/queries/QueryResult.js.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.js +38 -10
- package/dist/cjs/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/cjs/queries/index.js +2 -0
- package/dist/cjs/queries/index.js.map +1 -1
- package/dist/cjs/queries/reconcileQueryData.js +84 -0
- package/dist/cjs/queries/reconcileQueryData.js.map +1 -0
- package/dist/esm/queries/HubConnectionKeepAlive.d.ts +5 -3
- package/dist/esm/queries/HubConnectionKeepAlive.d.ts.map +1 -1
- package/dist/esm/queries/HubConnectionKeepAlive.js +24 -4
- package/dist/esm/queries/HubConnectionKeepAlive.js.map +1 -1
- package/dist/esm/queries/NullObservableQueryConnection.d.ts +3 -1
- package/dist/esm/queries/NullObservableQueryConnection.d.ts.map +1 -1
- package/dist/esm/queries/NullObservableQueryConnection.js +7 -2
- package/dist/esm/queries/NullObservableQueryConnection.js.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.d.ts +2 -0
- package/dist/esm/queries/ObservableQueryFor.d.ts.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.js +11 -1
- package/dist/esm/queries/ObservableQueryFor.js.map +1 -1
- package/dist/esm/queries/QueryFor.d.ts.map +1 -1
- package/dist/esm/queries/QueryFor.js +1 -21
- package/dist/esm/queries/QueryFor.js.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.d.ts +1 -0
- package/dist/esm/queries/QueryInstanceCache.d.ts.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.js +35 -12
- package/dist/esm/queries/QueryInstanceCache.js.map +1 -1
- package/dist/esm/queries/QueryResult.d.ts +5 -0
- package/dist/esm/queries/QueryResult.d.ts.map +1 -1
- package/dist/esm/queries/QueryResult.js +30 -0
- package/dist/esm/queries/QueryResult.js.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts +1 -0
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.js +38 -10
- package/dist/esm/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.d.ts +1 -0
- package/dist/esm/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.d.ts +2 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.d.ts.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.js +37 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.js.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.d.ts +2 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.d.ts.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.js +22 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.d.ts +23 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.js +28 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.js +21 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.js +18 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.js +21 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.js.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.d.ts +2 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.d.ts.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.js +32 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.js.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.d.ts +2 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.d.ts.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.js +22 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.js.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.d.ts +2 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.d.ts.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.js +39 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.js.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.d.ts +2 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.d.ts.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.js +28 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.js +36 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.js +20 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.js +15 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.js +20 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.js.map +1 -0
- package/dist/esm/queries/index.d.ts +1 -0
- package/dist/esm/queries/index.d.ts.map +1 -1
- package/dist/esm/queries/index.js +1 -0
- package/dist/esm/queries/index.js.map +1 -1
- package/dist/esm/queries/reconcileQueryData.d.ts +2 -0
- package/dist/esm/queries/reconcileQueryData.d.ts.map +1 -0
- package/dist/esm/queries/reconcileQueryData.js +82 -0
- package/dist/esm/queries/reconcileQueryData.js.map +1 -0
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/queries/HubConnectionKeepAlive.ts +30 -3
- package/queries/NullObservableQueryConnection.ts +5 -2
- package/queries/ObservableQueryFor.ts +15 -1
- package/queries/QueryFor.ts +1 -21
- package/queries/QueryInstanceCache.ts +61 -17
- package/queries/QueryResult.ts +34 -0
- package/queries/ServerSentEventHubConnection.ts +45 -10
- package/queries/WebSocketHubConnection.ts +6 -0
- package/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.ts +50 -0
- package/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.ts +28 -0
- package/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.ts +41 -0
- package/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.ts +30 -0
- package/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.ts +26 -0
- package/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.ts +32 -0
- package/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.ts +43 -0
- package/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.ts +34 -0
- package/queries/for_ServerSentEventHubConnection/when_keep_alive_is_idle/triggers_reconnect.ts +4 -4
- package/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.ts +64 -0
- package/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.ts +50 -0
- package/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.ts +46 -0
- package/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.ts +26 -0
- package/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.ts +22 -0
- package/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.ts +31 -0
- package/queries/index.ts +1 -0
- package/queries/reconcileQueryData.ts +98 -0
|
@@ -20,10 +20,10 @@
|
|
|
20
20
|
* of this class so the keep-alive logic is written once and behaves identically for both
|
|
21
21
|
* transports.
|
|
22
22
|
*/ class HubConnectionKeepAlive {
|
|
23
|
-
_intervalMs;
|
|
24
23
|
_onIdle;
|
|
25
24
|
_lastActivityTime = Date.now();
|
|
26
25
|
_timer;
|
|
26
|
+
_intervalMs;
|
|
27
27
|
_idleThresholdMs;
|
|
28
28
|
/**
|
|
29
29
|
* Initializes a new instance of {@link HubConnectionKeepAlive}.
|
|
@@ -34,10 +34,30 @@
|
|
|
34
34
|
* before the connection is considered idle. Defaults to {@link intervalMs}. Set this
|
|
35
35
|
* higher than {@link intervalMs} when the peer sends keep-alive messages on a similar
|
|
36
36
|
* cadence to account for network latency and timer jitter.
|
|
37
|
-
*/ constructor(
|
|
38
|
-
this._intervalMs = _intervalMs;
|
|
37
|
+
*/ constructor(intervalMs, _onIdle, idleThresholdMs){
|
|
39
38
|
this._onIdle = _onIdle;
|
|
40
|
-
this.
|
|
39
|
+
this._intervalMs = intervalMs;
|
|
40
|
+
this._idleThresholdMs = idleThresholdMs ?? intervalMs;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Gets how long (in milliseconds) without activity before the connection is considered idle.
|
|
44
|
+
*/ get idleThresholdMs() {
|
|
45
|
+
return this._idleThresholdMs;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Change the check interval and idle threshold, restarting the timer when it is already running.
|
|
49
|
+
*
|
|
50
|
+
* Used when the peer advertises its actual keep-alive cadence after connecting, so the client
|
|
51
|
+
* stops relying on an assumed default that may not match the server's configuration.
|
|
52
|
+
* @param {number} intervalMs How often (in milliseconds) to check for idle connections.
|
|
53
|
+
* @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.
|
|
54
|
+
*/ reconfigure(intervalMs, idleThresholdMs) {
|
|
55
|
+
const wasRunning = this._timer !== undefined;
|
|
56
|
+
this._intervalMs = intervalMs;
|
|
57
|
+
this._idleThresholdMs = idleThresholdMs;
|
|
58
|
+
if (wasRunning) {
|
|
59
|
+
this.start();
|
|
60
|
+
}
|
|
41
61
|
}
|
|
42
62
|
/**
|
|
43
63
|
* Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HubConnectionKeepAlive.js","sources":["../../../queries/HubConnectionKeepAlive.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private
|
|
1
|
+
{"version":3,"file":"HubConnectionKeepAlive.js","sources":["../../../queries/HubConnectionKeepAlive.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private _intervalMs: number;\n private _idleThresholdMs: number;\n\n /**\n * Initializes a new instance of {@link HubConnectionKeepAlive}.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {() => void} onIdle Callback invoked when the interval fires and no activity has\n * been recorded within the idle threshold.\n * @param {number} idleThresholdMs Optional. How long (in milliseconds) without activity\n * before the connection is considered idle. Defaults to {@link intervalMs}. Set this\n * higher than {@link intervalMs} when the peer sends keep-alive messages on a similar\n * cadence to account for network latency and timer jitter.\n */\n constructor(\n intervalMs: number,\n private readonly _onIdle: () => void,\n idleThresholdMs?: number,\n ) {\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs ?? intervalMs;\n }\n\n /**\n * Gets how long (in milliseconds) without activity before the connection is considered idle.\n */\n get idleThresholdMs(): number {\n return this._idleThresholdMs;\n }\n\n /**\n * Change the check interval and idle threshold, restarting the timer when it is already running.\n *\n * Used when the peer advertises its actual keep-alive cadence after connecting, so the client\n * stops relying on an assumed default that may not match the server's configuration.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.\n */\n reconfigure(intervalMs: number, idleThresholdMs: number): void {\n const wasRunning = this._timer !== undefined;\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs;\n\n if (wasRunning) {\n this.start();\n }\n }\n\n /**\n * Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.\n */\n start(): void {\n this.stop();\n this._lastActivityTime = Date.now();\n this._timer = setInterval(() => {\n if (Date.now() - this._lastActivityTime >= this._idleThresholdMs) {\n this._onIdle();\n }\n }, this._intervalMs);\n }\n\n /**\n * Stop the keep-alive timer.\n */\n stop(): void {\n if (this._timer !== undefined) {\n clearInterval(this._timer);\n this._timer = undefined;\n }\n }\n\n /**\n * Record that the connection has been active (message sent or received).\n * Resets the idle timer so that a keep-alive is not sent while data is already flowing.\n */\n recordActivity(): void {\n this._lastActivityTime = Date.now();\n }\n}\n"],"names":["HubConnectionKeepAlive","_lastActivityTime","Date","now","_timer","_intervalMs","_idleThresholdMs","intervalMs","idleThresholdMs","_onIdle","reconfigure","wasRunning","undefined","start","stop","setInterval","clearInterval","recordActivity"],"mappings":";;AAAA;AACA;AAEA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,sBAAAA,CAAAA;;IACDC,iBAAAA,GAAoBC,IAAAA,CAAKC,GAAG,EAAA;IAC5BC,MAAAA;IACAC,WAAAA;IACAC,gBAAAA;AAER;;;;;;;;;AASC,QACD,YACIC,UAAkB,EAClB,OAAoC,EACpCC,eAAwB,CAC1B;aAFmBC,OAAAA,GAAAA,OAAAA;QAGjB,IAAI,CAACJ,WAAW,GAAGE,UAAAA;QACnB,IAAI,CAACD,gBAAgB,GAAGE,eAAAA,IAAmBD,UAAAA;AAC/C,IAAA;AAEA;;AAEC,QACD,IAAIC,eAAAA,GAA0B;QAC1B,OAAO,IAAI,CAACF,gBAAgB;AAChC,IAAA;AAEA;;;;;;;AAOC,QACDI,WAAAA,CAAYH,UAAkB,EAAEC,eAAuB,EAAQ;AAC3D,QAAA,MAAMG,UAAAA,GAAa,IAAI,CAACP,MAAM,KAAKQ,SAAAA;QACnC,IAAI,CAACP,WAAW,GAAGE,UAAAA;QACnB,IAAI,CAACD,gBAAgB,GAAGE,eAAAA;AAExB,QAAA,IAAIG,UAAAA,EAAY;AACZ,YAAA,IAAI,CAACE,KAAK,EAAA;AACd,QAAA;AACJ,IAAA;AAEA;;AAEC,QACDA,KAAAA,GAAc;AACV,QAAA,IAAI,CAACC,IAAI,EAAA;AACT,QAAA,IAAI,CAACb,iBAAiB,GAAGC,IAAAA,CAAKC,GAAG,EAAA;QACjC,IAAI,CAACC,MAAM,GAAGW,WAAAA,CAAY,IAAA;YACtB,IAAIb,IAAAA,CAAKC,GAAG,EAAA,GAAK,IAAI,CAACF,iBAAiB,IAAI,IAAI,CAACK,gBAAgB,EAAE;AAC9D,gBAAA,IAAI,CAACG,OAAO,EAAA;AAChB,YAAA;QACJ,CAAA,EAAG,IAAI,CAACJ,WAAW,CAAA;AACvB,IAAA;AAEA;;AAEC,QACDS,IAAAA,GAAa;AACT,QAAA,IAAI,IAAI,CAACV,MAAM,KAAKQ,SAAAA,EAAW;YAC3BI,aAAAA,CAAc,IAAI,CAACZ,MAAM,CAAA;YACzB,IAAI,CAACA,MAAM,GAAGQ,SAAAA;AAClB,QAAA;AACJ,IAAA;AAEA;;;AAGC,QACDK,cAAAA,GAAuB;AACnB,QAAA,IAAI,CAAChB,iBAAiB,GAAGC,IAAAA,CAAKC,GAAG,EAAA;AACrC,IAAA;AACJ;;;;"}
|
|
@@ -8,11 +8,16 @@ var QueryResult = require('./QueryResult.js');
|
|
|
8
8
|
* Represents a {@link IObservableQueryConnection} when for instance one can't establish a connection.
|
|
9
9
|
*/ class NullObservableQueryConnection {
|
|
10
10
|
defaultValue;
|
|
11
|
+
result;
|
|
11
12
|
/**
|
|
12
13
|
* Initializes a new instance of the {@link NullObservableQueryConnection} class.
|
|
13
14
|
* @param {TDataType} defaultValue The default value to serve.
|
|
14
|
-
|
|
15
|
+
* @param {QueryResult<TDataType>} result Optional result to serve instead of an empty one. Supply it when the
|
|
16
|
+
* subscription failed for a reason the subscriber must be able to see — client-side validation in particular,
|
|
17
|
+
* which would otherwise be indistinguishable from a query that simply has no data yet.
|
|
18
|
+
*/ constructor(defaultValue, result){
|
|
15
19
|
this.defaultValue = defaultValue;
|
|
20
|
+
this.result = result;
|
|
16
21
|
}
|
|
17
22
|
/** @inheritdoc */ get lastPingLatency() {
|
|
18
23
|
return 0;
|
|
@@ -21,7 +26,7 @@ var QueryResult = require('./QueryResult.js');
|
|
|
21
26
|
return 0;
|
|
22
27
|
}
|
|
23
28
|
/** @inheritdoc */ connect(dataReceived) {
|
|
24
|
-
dataReceived(QueryResult.QueryResult.empty(this.defaultValue));
|
|
29
|
+
dataReceived(this.result ?? QueryResult.QueryResult.empty(this.defaultValue));
|
|
25
30
|
}
|
|
26
31
|
/** @inheritdoc */ /* eslint-disable @typescript-eslint/no-empty-function */ disconnect() {}
|
|
27
32
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NullObservableQueryConnection.js","sources":["../../../queries/NullObservableQueryConnection.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DataReceived } from './ObservableQueryConnection';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { QueryResult } from './QueryResult';\n\n/**\n * Represents a {@link IObservableQueryConnection} when for instance one can't establish a connection.\n */\n\nexport class NullObservableQueryConnection<TDataType> implements IObservableQueryConnection<TDataType> {\n /**\n * Initializes a new instance of the {@link NullObservableQueryConnection} class.\n * @param {TDataType} defaultValue The default value to serve.\n */\n constructor(readonly defaultValue: TDataType) {\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n connect(dataReceived: DataReceived<TDataType>) {\n dataReceived(QueryResult.empty(this.defaultValue));\n }\n\n /** @inheritdoc */\n /* eslint-disable @typescript-eslint/no-empty-function */\n disconnect() {\n }\n}\n"],"names":["NullObservableQueryConnection","defaultValue","lastPingLatency","averageLatency","connect","dataReceived","QueryResult","empty","disconnect"],"mappings":";;;;AAAA;AACA;AAMA;;AAEC,IAEM,MAAMA,6BAAAA,CAAAA
|
|
1
|
+
{"version":3,"file":"NullObservableQueryConnection.js","sources":["../../../queries/NullObservableQueryConnection.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DataReceived } from './ObservableQueryConnection';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { QueryResult } from './QueryResult';\n\n/**\n * Represents a {@link IObservableQueryConnection} when for instance one can't establish a connection.\n */\n\nexport class NullObservableQueryConnection<TDataType> implements IObservableQueryConnection<TDataType> {\n /**\n * Initializes a new instance of the {@link NullObservableQueryConnection} class.\n * @param {TDataType} defaultValue The default value to serve.\n * @param {QueryResult<TDataType>} result Optional result to serve instead of an empty one. Supply it when the\n * subscription failed for a reason the subscriber must be able to see — client-side validation in particular,\n * which would otherwise be indistinguishable from a query that simply has no data yet.\n */\n constructor(readonly defaultValue: TDataType, readonly result?: QueryResult<TDataType>) {\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n return 0;\n }\n\n /** @inheritdoc */\n connect(dataReceived: DataReceived<TDataType>) {\n dataReceived(this.result ?? QueryResult.empty(this.defaultValue));\n }\n\n /** @inheritdoc */\n /* eslint-disable @typescript-eslint/no-empty-function */\n disconnect() {\n }\n}\n"],"names":["NullObservableQueryConnection","result","defaultValue","lastPingLatency","averageLatency","connect","dataReceived","QueryResult","empty","disconnect"],"mappings":";;;;AAAA;AACA;AAMA;;AAEC,IAEM,MAAMA,6BAAAA,CAAAA;;;AACT;;;;;;AAMC,QACD,YAAY,YAAgC,EAAWC,MAA+B,CAAE;aAAnEC,YAAAA,GAAAA,YAAAA;aAAkCD,MAAAA,GAAAA,MAAAA;AACvD,IAAA;uBAGA,IAAIE,eAAAA,GAA0B;QAC1B,OAAO,CAAA;AACX,IAAA;uBAGA,IAAIC,cAAAA,GAAyB;QACzB,OAAO,CAAA;AACX,IAAA;uBAGAC,OAAAA,CAAQC,YAAqC,EAAE;QAC3CA,YAAAA,CAAa,IAAI,CAACL,MAAM,IAAIM,wBAAYC,KAAK,CAAC,IAAI,CAACN,YAAY,CAAA,CAAA;AACnE,IAAA;AAEA,iFAEAO,UAAAA,GAAa,CACb;AACJ;;;;"}
|
|
@@ -29,6 +29,7 @@ var QueryHttpRequest = require('./QueryHttpRequest.js');
|
|
|
29
29
|
_httpHeadersCallback;
|
|
30
30
|
_httpMethod;
|
|
31
31
|
roles = [];
|
|
32
|
+
validation;
|
|
32
33
|
/** Backend fully-qualified query name used when subscribing via the SSE hub. Overridden in generated proxies. */ queryName;
|
|
33
34
|
sorting;
|
|
34
35
|
paging;
|
|
@@ -70,7 +71,12 @@ var QueryHttpRequest = require('./QueryHttpRequest.js');
|
|
|
70
71
|
if (this._connection) {
|
|
71
72
|
this._connection.disconnect();
|
|
72
73
|
}
|
|
73
|
-
|
|
74
|
+
const clientValidationErrors = this.validation?.validate(args || {}) || [];
|
|
75
|
+
if (clientValidationErrors.length > 0) {
|
|
76
|
+
// Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result
|
|
77
|
+
// on its normal callback path instead of the empty result an unestablished connection would emit.
|
|
78
|
+
this._connection = new NullObservableQueryConnection.NullObservableQueryConnection(this.defaultValue, QueryResult.QueryResult.validationFailed(clientValidationErrors, this));
|
|
79
|
+
} else if (!this.validateArguments(args)) {
|
|
74
80
|
this._connection = new NullObservableQueryConnection.NullObservableQueryConnection(this.defaultValue);
|
|
75
81
|
} else {
|
|
76
82
|
this._connection = ObservableQueryConnectionFactory.createObservableQueryConnection({
|
|
@@ -116,6 +122,10 @@ var QueryHttpRequest = require('./QueryHttpRequest.js');
|
|
|
116
122
|
data: this.defaultValue
|
|
117
123
|
}
|
|
118
124
|
};
|
|
125
|
+
const clientValidationErrors = this.validation?.validate(args || {}) || [];
|
|
126
|
+
if (clientValidationErrors.length > 0) {
|
|
127
|
+
return QueryResult.QueryResult.validationFailed(clientValidationErrors, this);
|
|
128
|
+
}
|
|
119
129
|
if (!this.validateArguments(args)) {
|
|
120
130
|
return new Promise((resolve)=>{
|
|
121
131
|
resolve(noSuccess);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ObservableQueryFor.js","sources":["../../../queries/ObservableQueryFor.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { IObservableQueryFor, OnNextResult } from './IObservableQueryFor';\nimport { ObservableQuerySubscription } from './ObservableQuerySubscription';\nimport { ValidateRequestArguments } from './ValidateRequestArguments';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { NullObservableQueryConnection } from './NullObservableQueryConnection';\nimport { createObservableQueryConnection } from './ObservableQueryConnectionFactory';\nimport { Constructor } from '@cratis/fundamentals';\nimport { JsonSerializer } from '@cratis/fundamentals';\nimport { QueryResult } from './QueryResult';\nimport { Sorting } from './Sorting';\nimport { Paging } from './Paging';\nimport { SortDirection } from './SortDirection';\nimport { Globals } from '../Globals';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { ParameterDescriptor } from '../reflection/ParameterDescriptor';\nimport { ParametersHelper } from '../reflection/ParametersHelper';\nimport { QueryHttpMethod } from './QueryHttpMethod';\nimport { executeQueryHttpRequest } from './QueryHttpRequest';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class ObservableQueryFor<TDataType, TParameters = object> implements IObservableQueryFor<TDataType, TParameters> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _connection?: IObservableQueryConnection<TDataType>;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n\n abstract readonly route: string;\n abstract readonly defaultValue: TDataType;\n readonly roles: string[] = [];\n /** Backend fully-qualified query name used when subscribing via the SSE hub. Overridden in generated proxies. */\n readonly queryName?: string;\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n sorting: Sorting;\n paging: Paging;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(readonly modelType: Constructor, readonly enumerable: boolean) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /**\n * Disposes the query.\n */\n dispose() {\n this._connection?.disconnect();\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n subscribe(callback: OnNextResult<QueryResult<TDataType>>, args?: TParameters): ObservableQuerySubscription<TDataType> {\n if (this._connection) {\n this._connection.disconnect();\n }\n\n if (!this.validateArguments(args)) {\n this._connection = new NullObservableQueryConnection(this.defaultValue);\n } else {\n this._connection = createObservableQueryConnection({\n route: this.route,\n queryName: this.queryName ?? this.constructor.name,\n origin: this._origin,\n apiBasePath: this._apiBasePath,\n microservice: this._microservice,\n args: args as object,\n });\n }\n\n // Descriptor-backed instance properties provide defaults; fresh args passed to subscribe()\n // must take precedence over any stale instance property values. Spread parameterValues\n // first so that the caller-supplied args can override them.\n //\n // In direct mode the route arguments are already embedded in the URL path, so only\n // the unused (non-route) parameters are appended as additional query arguments.\n // In multiplexed mode ALL arguments — including route-derived ones — must be included\n // in the subscribe payload so the server can execute the query correctly.\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const { unusedParameters } = UrlHelpers.replaceRouteParameters(this.route, args as object);\n const connectionQueryArguments: any = {\n ...parameterValues,\n ...(Globals.queryDirectMode ? unusedParameters : (args as object) || {}),\n ...this.buildQueryArguments()\n };\n\n const subscriber = new ObservableQuerySubscription(this._connection);\n this._connection.connect(data => {\n const result: any = data;\n try {\n this.deserializeResult(result);\n callback(result);\n } catch (ex) {\n console.log(ex);\n }\n }, connectionQueryArguments);\n return subscriber;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = { ...QueryResult.noSuccess, ...{ data: this.defaultValue } } as QueryResult<TDataType>;\n\n if (!this.validateArguments(args)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = {\n ...(this._httpHeadersCallback?.() || {}),\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n\n private validateArguments(args?: TParameters): boolean {\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const combinedArgs = { ...(args as object || {}), ...parameterValues };\n return ValidateRequestArguments(this.constructor.name, this.requiredRequestParameters, combinedArgs as object);\n }\n\n private buildQueryArguments(): any {\n const queryArguments: any = {};\n\n if (this.paging && this.paging.pageSize > 0) {\n queryArguments.pageSize = this.paging.pageSize;\n queryArguments.page = this.paging.page;\n }\n\n if (this.sorting.hasSorting) {\n queryArguments.sortBy = this.sorting.field;\n queryArguments.sortDirection = (this.sorting.direction === SortDirection.descending) ? 'desc' : 'asc';\n }\n\n return queryArguments;\n }\n\n private deserializeResult(result: any): void {\n if (this.enumerable) {\n if (Array.isArray(result.data)) {\n result.data = JsonSerializer.deserializeArrayFromInstance(this.modelType, result.data);\n } else {\n result.data = [];\n }\n } else if (result.data) {\n result.data = JsonSerializer.deserializeFromInstance(this.modelType, result.data);\n }\n }\n}\n"],"names":["ObservableQueryFor","_microservice","_apiBasePath","_origin","_connection","_httpHeadersCallback","_httpMethod","roles","queryName","sorting","paging","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","dispose","disconnect","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setHttpMethod","method","subscribe","args","validateArguments","NullObservableQueryConnection","defaultValue","createObservableQueryConnection","route","name","parameterValues","ParametersHelper","collectParameterValues","unusedParameters","UrlHelpers","replaceRouteParameters","connectionQueryArguments","queryDirectMode","buildQueryArguments","subscriber","ObservableQuerySubscription","connect","data","result","deserializeResult","ex","console","log","perform","noSuccess","QueryResult","Promise","resolve","headers","length","microserviceHttpHeader","response","executeQueryHttpRequest","json","combinedArgs","ValidateRequestArguments","requiredRequestParameters","queryArguments","pageSize","page","hasSorting","sortBy","field","sortDirection","direction","SortDirection","descending","Array","isArray","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance"],"mappings":";;;;;;;;;;;;;;;;AAAA;AACA;AAsBA;;;AAKC,IACM,MAAeA,kBAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,WAAAA;IACAC,oBAAAA;IACAC,WAAAA;AAICC,IAAAA,KAAAA,GAAkB,EAAE;sHAE7B,SAASC;IAGTC,OAAAA;IACAC,MAAAA;AAEA;;;;AAIC,QACD,YAAY,SAA+B,EAAWC,UAAmB,CAAE;aAAtDC,SAAAA,GAAAA,SAAAA;aAAiCD,UAAAA,GAAAA,UAAAA;AAClD,QAAA,IAAI,CAACF,OAAO,GAAGI,eAAAA,CAAQC,IAAI;AAC3B,QAAA,IAAI,CAACJ,MAAM,GAAGK,aAAAA,CAAOC,QAAQ;AAC7B,QAAA,IAAI,CAACf,aAAa,GAAGgB,eAAAA,CAAQC,YAAY,IAAI,EAAA;AAC7C,QAAA,IA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HC,MAAAA,CAAOD,IAAI,GAAG,EAAE;AACpB,YAAA;QACJ,CAAA,MAAO,IAAIC,MAAAA,CAAOD,IAAI,EAAE;YACpBC,MAAAA,CAAOD,IAAI,GAAGgC,2BAAAA,CAAeE,uBAAuB,CAAC,IAAI,CAACxE,SAAS,EAAEuC,MAAAA,CAAOD,IAAI,CAAA;AACpF,QAAA;AACJ,IAAA;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"ObservableQueryFor.js","sources":["../../../queries/ObservableQueryFor.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { IObservableQueryFor, OnNextResult } from './IObservableQueryFor';\nimport { ObservableQuerySubscription } from './ObservableQuerySubscription';\nimport { ValidateRequestArguments } from './ValidateRequestArguments';\nimport { QueryValidator } from './QueryValidator';\nimport { IObservableQueryConnection } from './IObservableQueryConnection';\nimport { NullObservableQueryConnection } from './NullObservableQueryConnection';\nimport { createObservableQueryConnection } from './ObservableQueryConnectionFactory';\nimport { Constructor } from '@cratis/fundamentals';\nimport { JsonSerializer } from '@cratis/fundamentals';\nimport { QueryResult } from './QueryResult';\nimport { Sorting } from './Sorting';\nimport { Paging } from './Paging';\nimport { SortDirection } from './SortDirection';\nimport { Globals } from '../Globals';\nimport { UrlHelpers } from '../UrlHelpers';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { ParameterDescriptor } from '../reflection/ParameterDescriptor';\nimport { ParametersHelper } from '../reflection/ParametersHelper';\nimport { QueryHttpMethod } from './QueryHttpMethod';\nimport { executeQueryHttpRequest } from './QueryHttpRequest';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class ObservableQueryFor<TDataType, TParameters = object> implements IObservableQueryFor<TDataType, TParameters> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _connection?: IObservableQueryConnection<TDataType>;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n\n abstract readonly route: string;\n abstract readonly defaultValue: TDataType;\n readonly roles: string[] = [];\n readonly validation?: QueryValidator<any>;\n /** Backend fully-qualified query name used when subscribing via the SSE hub. Overridden in generated proxies. */\n readonly queryName?: string;\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n sorting: Sorting;\n paging: Paging;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(readonly modelType: Constructor, readonly enumerable: boolean) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /**\n * Disposes the query.\n */\n dispose() {\n this._connection?.disconnect();\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n subscribe(callback: OnNextResult<QueryResult<TDataType>>, args?: TParameters): ObservableQuerySubscription<TDataType> {\n if (this._connection) {\n this._connection.disconnect();\n }\n\n const clientValidationErrors = this.validation?.validate(args as object || {}) || [];\n if (clientValidationErrors.length > 0) {\n // Serve the failure through the connection rather than throwing, so a subscriber sees an invalid result\n // on its normal callback path instead of the empty result an unestablished connection would emit.\n this._connection = new NullObservableQueryConnection(\n this.defaultValue,\n QueryResult.validationFailed(clientValidationErrors, this));\n } else if (!this.validateArguments(args)) {\n this._connection = new NullObservableQueryConnection(this.defaultValue);\n } else {\n this._connection = createObservableQueryConnection({\n route: this.route,\n queryName: this.queryName ?? this.constructor.name,\n origin: this._origin,\n apiBasePath: this._apiBasePath,\n microservice: this._microservice,\n args: args as object,\n });\n }\n\n // Descriptor-backed instance properties provide defaults; fresh args passed to subscribe()\n // must take precedence over any stale instance property values. Spread parameterValues\n // first so that the caller-supplied args can override them.\n //\n // In direct mode the route arguments are already embedded in the URL path, so only\n // the unused (non-route) parameters are appended as additional query arguments.\n // In multiplexed mode ALL arguments — including route-derived ones — must be included\n // in the subscribe payload so the server can execute the query correctly.\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const { unusedParameters } = UrlHelpers.replaceRouteParameters(this.route, args as object);\n const connectionQueryArguments: any = {\n ...parameterValues,\n ...(Globals.queryDirectMode ? unusedParameters : (args as object) || {}),\n ...this.buildQueryArguments()\n };\n\n const subscriber = new ObservableQuerySubscription(this._connection);\n this._connection.connect(data => {\n const result: any = data;\n try {\n this.deserializeResult(result);\n callback(result);\n } catch (ex) {\n console.log(ex);\n }\n }, connectionQueryArguments);\n return subscriber;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = { ...QueryResult.noSuccess, ...{ data: this.defaultValue } } as QueryResult<TDataType>;\n\n const clientValidationErrors = this.validation?.validate(args as object || {}) || [];\n if (clientValidationErrors.length > 0) {\n return QueryResult.validationFailed(clientValidationErrors, this);\n }\n\n if (!this.validateArguments(args)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = {\n ...(this._httpHeadersCallback?.() || {}),\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n\n private validateArguments(args?: TParameters): boolean {\n const parameterValues = ParametersHelper.collectParameterValues(this);\n const combinedArgs = { ...(args as object || {}), ...parameterValues };\n return ValidateRequestArguments(this.constructor.name, this.requiredRequestParameters, combinedArgs as object);\n }\n\n private buildQueryArguments(): any {\n const queryArguments: any = {};\n\n if (this.paging && this.paging.pageSize > 0) {\n queryArguments.pageSize = this.paging.pageSize;\n queryArguments.page = this.paging.page;\n }\n\n if (this.sorting.hasSorting) {\n queryArguments.sortBy = this.sorting.field;\n queryArguments.sortDirection = (this.sorting.direction === SortDirection.descending) ? 'desc' : 'asc';\n }\n\n return queryArguments;\n }\n\n private deserializeResult(result: any): void {\n if (this.enumerable) {\n if (Array.isArray(result.data)) {\n result.data = JsonSerializer.deserializeArrayFromInstance(this.modelType, result.data);\n } else {\n result.data = [];\n }\n } else if (result.data) {\n result.data = JsonSerializer.deserializeFromInstance(this.modelType, result.data);\n }\n }\n}\n"],"names":["ObservableQueryFor","_microservice","_apiBasePath","_origin","_connection","_httpHeadersCallback","_httpMethod","roles","validation","queryName","sorting","paging","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","dispose","disconnect","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setHttpMethod","method","subscribe","args","clientValidationErrors","validate","length","NullObservableQueryConnection","defaultValue","QueryResult","validationFailed","validateArguments","createObservableQueryConnection","route","name","parameterValues","ParametersHelper","collectParameterValues","unusedParameters","UrlHelpers","replaceRouteParameters","connectionQueryArguments","queryDirectMode","buildQueryArguments","subscriber","ObservableQuerySubscription","connect","data","result","deserializeResult","ex","console","log","perform","noSuccess","Promise","resolve","headers","microserviceHttpHeader","response","executeQueryHttpRequest","json","combinedArgs","ValidateRequestArguments","requiredRequestParameters","queryArguments","pageSize","page","hasSorting","sortBy","field","sortDirection","direction","SortDirection","descending","Array","isArray","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance"],"mappings":";;;;;;;;;;;;;;;;AAAA;AACA;AAuBA;;;AAKC,IACM,MAAeA,kBAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,WAAAA;IACAC,oBAAAA;IACAC,WAAAA;AAICC,IAAAA,KAAAA,GAAkB,EAAE;IACpBC,UAAAA;sHAET,SAASC;IAGTC,OAAAA;IACAC,MAAAA;AAEA;;;;AAIC,QACD,YAAY,SAA+B,EAAWC,UAAmB,CAAE;aAAtDC,SAAAA,GAAAA,SAAAA;aAAiCD,UAAAA,GAAAA,UAAAA;AAClD,QAAA,IAAI,CAACF,OAAO,GAAGI,eAAAA,CAAQC,IAAI;AAC3B,QAAA,IAAI,CAACJ,MAAM,GAAGK,aAAAA,CAAOC,QAAQ;AAC7B,QAAA,IAAI,CAAChB,aAAa,GAAGiB,eAAAA,CAAQC,YAAY,IAAI,EAAA;AAC7C,QAAA,IAAI,CAACjB,YAAY,GAAGgB,eAAAA,CAAQE,WAAW,IAAI,EAAA;AAC3C,QAAA,IAAI,CAACjB,OAAO,GAAGe,eAAAA,CAAQG,MAAM,IAAI,EAAA;AACjC,QAAA,IAAI,CAAChB,oBAAoB,GAAG,KAAO,EAAC,CAAA;AACxC,IAAA;AAEA;;AAEC,QACDiB,OAAAA,GAAU;QACN,IAAI,CAAClB,WAAW,EAAEmB,UAAAA,EAAAA;AACtB,IAAA;uBAGAC,eAAAA,CAAgBL,YAAoB,EAAE;QAClC,IAAI,CAAClB,aAAa,GAAGkB,YAAAA;AACzB,IAAA;uBAGAM,cAAAA,CAAeL,WAAmB,EAAQ;QACtC,IAAI,CAAClB,YAAY,GAAGkB,WAAAA;AACxB,IAAA;uBAGA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AeC,4BAA4B,CAAC,IAAI,CAAC1E,SAAS,EAAE4C,MAAAA,CAAOD,IAAI,CAAA;YACzF,CAAA,MAAO;gBACHC,MAAAA,CAAOD,IAAI,GAAG,EAAE;AACpB,YAAA;QACJ,CAAA,MAAO,IAAIC,MAAAA,CAAOD,IAAI,EAAE;YACpBC,MAAAA,CAAOD,IAAI,GAAG8B,2BAAAA,CAAeE,uBAAuB,CAAC,IAAI,CAAC3E,SAAS,EAAE4C,MAAAA,CAAOD,IAAI,CAAA;AACpF,QAAA;AACJ,IAAA;AACJ;;;;"}
|
|
@@ -67,27 +67,7 @@ var QueryHttpRequest = require('./QueryHttpRequest.js');
|
|
|
67
67
|
args = args || this.parameters;
|
|
68
68
|
const clientValidationErrors = this.validation?.validate(args || {}) || [];
|
|
69
69
|
if (clientValidationErrors.length > 0) {
|
|
70
|
-
return
|
|
71
|
-
data: this.defaultValue,
|
|
72
|
-
isSuccess: false,
|
|
73
|
-
isAuthorized: true,
|
|
74
|
-
isValid: false,
|
|
75
|
-
hasExceptions: false,
|
|
76
|
-
validationResults: clientValidationErrors.map((_)=>({
|
|
77
|
-
severity: _.severity,
|
|
78
|
-
message: _.message,
|
|
79
|
-
members: _.members,
|
|
80
|
-
state: _.state
|
|
81
|
-
})),
|
|
82
|
-
exceptionMessages: [],
|
|
83
|
-
exceptionStackTrace: '',
|
|
84
|
-
paging: {
|
|
85
|
-
totalItems: 0,
|
|
86
|
-
totalPages: 0,
|
|
87
|
-
page: 0,
|
|
88
|
-
size: 0
|
|
89
|
-
}
|
|
90
|
-
}, this.modelType, this.enumerable);
|
|
70
|
+
return QueryResult.QueryResult.validationFailed(clientValidationErrors, this);
|
|
91
71
|
}
|
|
92
72
|
if (!ValidateRequestArguments.ValidateRequestArguments(this.constructor.name, this.requiredRequestParameters, args)) {
|
|
93
73
|
return new Promise((resolve)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryFor.js","sources":["../../../queries/QueryFor.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { IQueryFor } from './IQueryFor';\nimport { QueryResult } from \"./QueryResult\";\nimport { QueryValidator } from './QueryValidator';\nimport { ValidateRequestArguments } from './ValidateRequestArguments';\nimport { Constructor } from '@cratis/fundamentals';\nimport { Paging } from './Paging';\nimport { Globals } from '../Globals';\nimport { Sorting } from './Sorting';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { ParameterDescriptor } from '../reflection/ParameterDescriptor';\nimport { ParametersHelper } from '../reflection/ParametersHelper';\nimport { QueryHttpMethod } from './QueryHttpMethod';\nimport { executeQueryHttpRequest } from './QueryHttpRequest';\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class QueryFor<TDataType, TParameters = object> implements IQueryFor<TDataType, TParameters> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n abstract readonly route: string;\n /** Backend fully-qualified query name used as cache key. Overridden in generated proxies. */\n readonly queryName?: string;\n /* eslint-disable @typescript-eslint/no-explicit-any */\n readonly validation?: QueryValidator<any>;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n readonly roles: string[] = [];\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n abstract defaultValue: TDataType;\n abortController?: AbortController;\n sorting: Sorting;\n paging: Paging;\n parameters: TParameters | undefined;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(readonly modelType: Constructor, readonly enumerable: boolean) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = { ...QueryResult.noSuccess, ...{ data: this.defaultValue } } as QueryResult<TDataType>;\n\n args = args || this.parameters;\n\n const clientValidationErrors = this.validation?.validate(args as object || {}) || [];\n if (clientValidationErrors.length > 0) {\n return new QueryResult({\n data: this.defaultValue as object,\n isSuccess: false,\n isAuthorized: true,\n isValid: false,\n hasExceptions: false,\n validationResults: clientValidationErrors.map(_ => ({\n severity: _.severity,\n message: _.message,\n members: _.members,\n state: _.state\n })),\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, this.modelType, this.enumerable) as QueryResult<TDataType>;\n }\n\n if (!ValidateRequestArguments(this.constructor.name, this.requiredRequestParameters, args as object)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n if (this.abortController) {\n this.abortController.abort();\n }\n\n this.abortController = new AbortController();\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = {\n ... this._httpHeadersCallback?.(), ...\n {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers,\n signal: this.abortController.signal\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n}\n"],"names":["QueryFor","_microservice","_apiBasePath","_origin","_httpHeadersCallback","_httpMethod","queryName","validation","roles","abortController","sorting","paging","parameters","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setHttpMethod","method","perform","args","noSuccess","QueryResult","data","defaultValue","clientValidationErrors","validate","length","isSuccess","isAuthorized","isValid","hasExceptions","validationResults","map","_","severity","message","members","state","exceptionMessages","exceptionStackTrace","totalItems","totalPages","page","size","ValidateRequestArguments","name","requiredRequestParameters","Promise","resolve","abort","AbortController","parameterValues","ParametersHelper","collectParameterValues","headers","microserviceHttpHeader","response","executeQueryHttpRequest","route","signal","result","json"],"mappings":";;;;;;;;;;AAAA;AACA;AAgBA;;;AAGC,IACM,MAAeA,QAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,oBAAAA;IACAC,WAAAA;kGAGR,SAASC;4DAET,UAASC;AACT,2DACSC,KAAAA,GAAkB,EAAE;IAI7BC,eAAAA;IACAC,OAAAA;IACAC,MAAAA;IACAC,UAAAA;AAEA;;;;AAIC,QACD,YAAY,SAA+B,EAAWC,UAAmB,CAAE;aAAtDC,SAAAA,GAAAA,SAAAA;aAAiCD,UAAAA,GAAAA,UAAAA;AAClD,QAAA,IAAI,CAACH,OAAO,GAAGK,eAAAA,CAAQC,IAAI;AAC3B,QAAA,IAAI,CAACL,MAAM,GAAGM,aAAAA,CAAOC,QAAQ;AAC7B,QAAA,IAAI,CAACjB,aAAa,GAAGkB,eAAAA,CAAQC,YAAY,IAAI,EAAA;AAC7C,QAAA,IAAI,CAAClB,YAAY,GAAGiB,eAAAA,CAAQE,WAAW,IAAI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AAsB,CAAC,GAAG,IAAI,CAAClE,aAAa;AAChE,QAAA;AAEA,QAAA,MAAMmE,WAAW,MAAMC,wCAAAA,CAAwB,IAAI,CAAChE,WAAW,EAAE;YAC7DiE,KAAAA,EAAO,IAAI,CAACA,KAAK;YACjBjD,WAAAA,EAAa,IAAI,CAACnB,YAAY;YAC9BoB,MAAAA,EAAQ,IAAI,CAACnB,OAAO;YACpB4B,IAAAA,EAAOA,QAAmB,EAAC;AAC3BgC,YAAAA,eAAAA;YACApD,MAAAA,EAAQ,IAAI,CAACA,MAAM;YACnBD,OAAAA,EAAS,IAAI,CAACA,OAAO;AACrBwD,YAAAA,OAAAA;AACAK,YAAAA,MAAAA,EAAQ,IAAI,CAAC9D,eAAe,CAAC8D;AACjC,SAAA,CAAA;QAEA,IAAI;YACA,MAAMC,MAAAA,GAAS,MAAMJ,QAAAA,CAASK,IAAI,EAAA;YAClC,OAAO,IAAIxC,wBAAYuC,MAAAA,EAAQ,IAAI,CAAC1D,SAAS,EAAE,IAAI,CAACD,UAAU,CAAA;AAClE,QAAA,CAAA,CAAE,OAAM;YACJ,OAAOmB,SAAAA;AACX,QAAA;AACJ,IAAA;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"QueryFor.js","sources":["../../../queries/QueryFor.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { IQueryFor } from './IQueryFor';\nimport { QueryResult } from \"./QueryResult\";\nimport { QueryValidator } from './QueryValidator';\nimport { ValidateRequestArguments } from './ValidateRequestArguments';\nimport { Constructor } from '@cratis/fundamentals';\nimport { Paging } from './Paging';\nimport { Globals } from '../Globals';\nimport { Sorting } from './Sorting';\nimport { GetHttpHeaders } from '../GetHttpHeaders';\nimport { ParameterDescriptor } from '../reflection/ParameterDescriptor';\nimport { ParametersHelper } from '../reflection/ParametersHelper';\nimport { QueryHttpMethod } from './QueryHttpMethod';\nimport { executeQueryHttpRequest } from './QueryHttpRequest';\n\n/**\n * Represents an implementation of {@link IQueryFor}.\n * @template TDataType Type of data returned by the query.\n */\nexport abstract class QueryFor<TDataType, TParameters = object> implements IQueryFor<TDataType, TParameters> {\n private _microservice: string;\n private _apiBasePath: string;\n private _origin: string;\n private _httpHeadersCallback: GetHttpHeaders;\n private _httpMethod?: QueryHttpMethod;\n abstract readonly route: string;\n /** Backend fully-qualified query name used as cache key. Overridden in generated proxies. */\n readonly queryName?: string;\n /* eslint-disable @typescript-eslint/no-explicit-any */\n readonly validation?: QueryValidator<any>;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n readonly roles: string[] = [];\n abstract readonly parameterDescriptors: ParameterDescriptor[];\n abstract get requiredRequestParameters(): string[];\n abstract defaultValue: TDataType;\n abortController?: AbortController;\n sorting: Sorting;\n paging: Paging;\n parameters: TParameters | undefined;\n\n /**\n * Initializes a new instance of the {@link ObservableQueryFor<,>}} class.\n * @param modelType Type of model, if an enumerable, this is the instance type.\n * @param enumerable Whether or not it is an enumerable.\n */\n constructor(readonly modelType: Constructor, readonly enumerable: boolean) {\n this.sorting = Sorting.none;\n this.paging = Paging.noPaging;\n this._microservice = Globals.microservice ?? '';\n this._apiBasePath = Globals.apiBasePath ?? '';\n this._origin = Globals.origin ?? '';\n this._httpHeadersCallback = () => ({});\n }\n\n /** @inheritdoc */\n setMicroservice(microservice: string) {\n this._microservice = microservice;\n }\n\n /** @inheritdoc */\n setApiBasePath(apiBasePath: string): void {\n this._apiBasePath = apiBasePath;\n }\n\n /** @inheritdoc */\n setOrigin(origin: string): void {\n this._origin = origin;\n }\n\n /** @inheritdoc */\n setHttpHeadersCallback(callback: GetHttpHeaders): void {\n this._httpHeadersCallback = callback;\n }\n\n /** @inheritdoc */\n setHttpMethod(method: QueryHttpMethod): void {\n this._httpMethod = method;\n }\n\n /** @inheritdoc */\n async perform(args?: TParameters): Promise<QueryResult<TDataType>> {\n const noSuccess = { ...QueryResult.noSuccess, ...{ data: this.defaultValue } } as QueryResult<TDataType>;\n\n args = args || this.parameters;\n\n const clientValidationErrors = this.validation?.validate(args as object || {}) || [];\n if (clientValidationErrors.length > 0) {\n return QueryResult.validationFailed(clientValidationErrors, this);\n }\n\n if (!ValidateRequestArguments(this.constructor.name, this.requiredRequestParameters, args as object)) {\n return new Promise<QueryResult<TDataType>>((resolve) => {\n resolve(noSuccess);\n });\n }\n\n if (this.abortController) {\n this.abortController.abort();\n }\n\n this.abortController = new AbortController();\n\n // Collect parameter values from parameterDescriptors that are set\n const parameterValues = ParametersHelper.collectParameterValues(this);\n\n const headers = {\n ... this._httpHeadersCallback?.(), ...\n {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n };\n\n if (this._microservice?.length > 0) {\n headers[Globals.microserviceHttpHeader] = this._microservice;\n }\n\n const response = await executeQueryHttpRequest(this._httpMethod, {\n route: this.route,\n apiBasePath: this._apiBasePath,\n origin: this._origin,\n args: (args as object) ?? {},\n parameterValues,\n paging: this.paging,\n sorting: this.sorting,\n headers,\n signal: this.abortController.signal\n });\n\n try {\n const result = await response.json();\n return new QueryResult(result, this.modelType, this.enumerable);\n } catch {\n return noSuccess;\n }\n }\n}\n"],"names":["QueryFor","_microservice","_apiBasePath","_origin","_httpHeadersCallback","_httpMethod","queryName","validation","roles","abortController","sorting","paging","parameters","enumerable","modelType","Sorting","none","Paging","noPaging","Globals","microservice","apiBasePath","origin","setMicroservice","setApiBasePath","setOrigin","setHttpHeadersCallback","callback","setHttpMethod","method","perform","args","noSuccess","QueryResult","data","defaultValue","clientValidationErrors","validate","length","validationFailed","ValidateRequestArguments","name","requiredRequestParameters","Promise","resolve","abort","AbortController","parameterValues","ParametersHelper","collectParameterValues","headers","microserviceHttpHeader","response","executeQueryHttpRequest","route","signal","result","json"],"mappings":";;;;;;;;;;AAAA;AACA;AAgBA;;;AAGC,IACM,MAAeA,QAAAA,CAAAA;;;IACVC,aAAAA;IACAC,YAAAA;IACAC,OAAAA;IACAC,oBAAAA;IACAC,WAAAA;kGAGR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AK;YACjBjC,WAAAA,EAAa,IAAI,CAACnB,YAAY;YAC9BoB,MAAAA,EAAQ,IAAI,CAACnB,OAAO;YACpB4B,IAAAA,EAAOA,QAAmB,EAAC;AAC3BgB,YAAAA,eAAAA;YACApC,MAAAA,EAAQ,IAAI,CAACA,MAAM;YACnBD,OAAAA,EAAS,IAAI,CAACA,OAAO;AACrBwC,YAAAA,OAAAA;AACAK,YAAAA,MAAAA,EAAQ,IAAI,CAAC9C,eAAe,CAAC8C;AACjC,SAAA,CAAA;QAEA,IAAI;YACA,MAAMC,MAAAA,GAAS,MAAMJ,QAAAA,CAASK,IAAI,EAAA;YAClC,OAAO,IAAIxB,wBAAYuB,MAAAA,EAAQ,IAAI,CAAC1C,SAAS,EAAE,IAAI,CAACD,UAAU,CAAA;AAClE,QAAA,CAAA,CAAE,OAAM;YACJ,OAAOmB,SAAAA;AACX,QAAA;AACJ,IAAA;AACJ;;;;"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var QueryResultWithState = require('./QueryResultWithState.js');
|
|
4
|
+
var reconcileQueryData = require('./reconcileQueryData.js');
|
|
5
|
+
|
|
3
6
|
// Copyright (c) Cratis. All rights reserved.
|
|
4
7
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
5
8
|
/**
|
|
@@ -98,19 +101,39 @@
|
|
|
98
101
|
* @param result The result to store.
|
|
99
102
|
*/ setLastResult(key, result) {
|
|
100
103
|
const entry = this._entries.get(key);
|
|
101
|
-
if (entry) {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
104
|
+
if (!entry) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const previousResult = entry.lastResult;
|
|
108
|
+
// Reconcile the incoming payload against the one already held so items that did not actually
|
|
109
|
+
// change keep their previous references. A full snapshot — which is what the server re-sends
|
|
110
|
+
// whenever a subscription is re-established — otherwise arrives as all-new references and
|
|
111
|
+
// makes every consumer treat every item as changed.
|
|
112
|
+
const reconciled = previousResult !== undefined ? this.withReconciledData(previousResult, result) : result;
|
|
113
|
+
entry.lastResult = reconciled;
|
|
114
|
+
// Reconciliation returns the previous data reference when nothing changed, so identity is
|
|
115
|
+
// enough to detect it. Only `data` and `isSuccess` matter here — the other fields (e.g.
|
|
116
|
+
// changeSet) are ephemeral and do not affect what the user sees.
|
|
117
|
+
if (previousResult !== undefined && previousResult.isSuccess === reconciled.isSuccess && previousResult.data === reconciled.data) {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
for (const listener of entry.listeners){
|
|
121
|
+
listener(reconciled);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Returns the incoming result with its data reconciled against the previous result, or the
|
|
126
|
+
* incoming result unchanged when reconciliation found nothing to carry over.
|
|
127
|
+
* @template TDataType The type of data returned by the query.
|
|
128
|
+
* @param previous The previously held result.
|
|
129
|
+
* @param next The freshly received result.
|
|
130
|
+
* @returns A result whose data preserves references for everything that did not change.
|
|
131
|
+
*/ withReconciledData(previous, next) {
|
|
132
|
+
const reconciledData = reconcileQueryData.reconcileQueryData(previous.data, next.data);
|
|
133
|
+
if (reconciledData === next.data) {
|
|
134
|
+
return next;
|
|
113
135
|
}
|
|
136
|
+
return new QueryResultWithState.QueryResultWithState(reconciledData, next.paging, next.isSuccess, next.isAuthorized, next.isValid, next.validationResults, next.hasExceptions, next.exceptionMessages, next.exceptionStackTrace, next.isPerforming, next.changeSet);
|
|
114
137
|
}
|
|
115
138
|
/**
|
|
116
139
|
* Registers a listener that is invoked whenever the cached result for the given key changes.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { QueryResultWithState } from './QueryResultWithState';\nimport { CacheDiagnostics, CacheEntryDiagnostics } from './ObservableQueryDiagnosticsSnapshot';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (result: QueryResultWithState<TDataType>) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {\n }\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's {@link queryName}\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(key: QueryCacheKey): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as QueryResultWithState<TDataType> | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(key: QueryCacheKey, result: QueryResultWithState<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n const previousResult = entry.lastResult as QueryResultWithState<TDataType> | undefined;\n entry.lastResult = result as QueryResultWithState<unknown>;\n\n // Suppress re-renders when the server re-sends identical data after a reconnect.\n // We only compare `data` and `isSuccess` — other fields (e.g. changeSet) are\n // ephemeral and do not affect what the user sees.\n if (\n previousResult !== undefined &&\n previousResult.isSuccess === result.isSuccess &&\n JSON.stringify(previousResult.data) === JSON.stringify(result.data)\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(result);\n }\n }\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(key: QueryCacheKey, listener: QueryCacheListener<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(key: QueryCacheKey, listener: QueryCacheListener<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","isSuccess","data","listener","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;AAAA;AACA;AA2DA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAC7B,IAAA;AAEA;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,a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;AAC/B,YAAA,MAAMC,YAAYF,UAAAA,IAAc,CAAA,GAAI9C,IAAIiD,SAAS,CAAC,GAAGH,UAAAA,CAAAA,GAAc9C,GAAAA;AAEnE,YAAA,IAAIkD,cAAAA,GAAiB,CAAA;YACrB,IAAI;gBACA,IAAI5C,KAAAA,CAAME,UAAU,KAAKC,SAAAA,EAAW;AAChCyC,oBAAAA,cAAAA,GAAiBjD,KAAKC,SAAS,CAACI,KAAAA,CAAME,UAAU,EAAEb,MAAM;AAC5D,gBAAA;AACJ,YAAA,CAAA,CAAE,OAAM;;AAER,YAAA;AAEA,YAAA,IAAIW,MAAMI,eAAe,GAAG,KAAK,CAACJ,KAAAA,CAAMO,UAAU,EAAE;AAChDgC,gBAAAA,cAAAA,EAAAA;AACJ,YAAA;YAEAD,UAAAA,IAAcM,cAAAA;AACdP,YAAAA,OAAAA,CAAQQ,IAAI,CAAC;AACTnD,gBAAAA,GAAAA;AACAgD,gBAAAA,SAAAA;AACAtC,gBAAAA,eAAAA,EAAiBJ,MAAMI,eAAe;gBACtC0C,aAAAA,EAAe9C,KAAAA,CAAMK,SAAS,CAAC0C,IAAI;AACnCxC,gBAAAA,UAAAA,EAAYP,MAAMO,UAAU;gBAC5ByC,SAAAA,EAAWhD,KAAAA,CAAME,UAAU,KAAKC,SAAAA;AAChCyC,gBAAAA;AACJ,aAAA,CAAA;AACJ,QAAA;QAEA,OAAO;AACHK,YAAAA,OAAAA,EAASV,cAAAA,KAAmB,CAAA;AAC5BW,YAAAA,UAAAA,EAAY,IAAI,CAACtE,QAAQ,CAACmE,IAAI;YAC9BH,cAAAA,EAAgBN,UAAAA;AAChBD,YAAAA;AACJ,SAAA;AACJ,IAAA;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { QueryResultWithState } from './QueryResultWithState';\nimport { CacheDiagnostics, CacheEntryDiagnostics } from './ObservableQueryDiagnosticsSnapshot';\nimport { reconcileQueryData } from './reconcileQueryData';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (result: QueryResultWithState<TDataType>) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {\n }\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's {@link queryName}\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(key: QueryCacheKey): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as QueryResultWithState<TDataType> | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(key: QueryCacheKey, result: QueryResultWithState<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (!entry) {\n return;\n }\n\n const previousResult = entry.lastResult as QueryResultWithState<TDataType> | undefined;\n\n // Reconcile the incoming payload against the one already held so items that did not actually\n // change keep their previous references. A full snapshot — which is what the server re-sends\n // whenever a subscription is re-established — otherwise arrives as all-new references and\n // makes every consumer treat every item as changed.\n const reconciled = previousResult !== undefined\n ? this.withReconciledData(previousResult, result)\n : result;\n\n entry.lastResult = reconciled as QueryResultWithState<unknown>;\n\n // Reconciliation returns the previous data reference when nothing changed, so identity is\n // enough to detect it. Only `data` and `isSuccess` matter here — the other fields (e.g.\n // changeSet) are ephemeral and do not affect what the user sees.\n if (\n previousResult !== undefined &&\n previousResult.isSuccess === reconciled.isSuccess &&\n previousResult.data === reconciled.data\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(reconciled);\n }\n }\n\n /**\n * Returns the incoming result with its data reconciled against the previous result, or the\n * incoming result unchanged when reconciliation found nothing to carry over.\n * @template TDataType The type of data returned by the query.\n * @param previous The previously held result.\n * @param next The freshly received result.\n * @returns A result whose data preserves references for everything that did not change.\n */\n private withReconciledData<TDataType>(\n previous: QueryResultWithState<TDataType>,\n next: QueryResultWithState<TDataType>\n ): QueryResultWithState<TDataType> {\n const reconciledData = reconcileQueryData(previous.data, next.data);\n\n if (reconciledData === next.data) {\n return next;\n }\n\n return new QueryResultWithState<TDataType>(\n reconciledData,\n next.paging,\n next.isSuccess,\n next.isAuthorized,\n next.isValid,\n next.validationResults,\n next.hasExceptions,\n next.exceptionMessages,\n next.exceptionStackTrace,\n next.isPerforming,\n next.changeSet);\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(key: QueryCacheKey, listener: QueryCacheListener<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(key: QueryCacheKey, listener: QueryCacheListener<TDataType>): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","reconciled","withReconciledData","isSuccess","data","listener","previous","next","reconciledData","reconcileQueryData","QueryResultWithState","paging","isAuthorized","isValid","validationResults","hasExceptions","exceptionMessages","exceptionStackTrace","isPerforming","changeSet","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;;;;AAAA;AACA;AA4DA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAC7B,IAAA;AAEA;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,aAAAA,CAAc,EAAE,CAAC;AAC/B,QAAA;QAEA,MAAMK,MAAAA,GAASH,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CACtBK,IAAI,EAAA,CACJC,MAAM,CAA0B,CAACC,WAAAA,EAAaC,GAAAA,GAAAA;AAC3CD,YAAAA,WAAW,CAACC,GAAAA,CAAI,GAAG,IAAiC,CAACA,GAAAA,CAAI;YACzD,OAAOD,WAAAA;AACX,QAAA,CAAA,EAAG,EAAC,CAAA;AAER,QAAA,OAAO,GAAGR,aAAAA,CAAc,EAAE,EAAEU,IAAAA,CAAKC,SAAS,CAACN,MAAAA,CAAAA,CAAAA,CAAS;AACxD,IAAA;AAEA;;;;;;;AAOC,QACDO,WAAAA,CACIH,GAAkB,EAClBI,OAAwB,EACe;A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28,6 +28,36 @@ var PagingInfo = require('./PagingInfo.js');
|
|
|
28
28
|
}
|
|
29
29
|
}, Object, false);
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Creates a {@link QueryResult} representing a query rejected by client-side validation, mirroring
|
|
33
|
+
* {@link CommandResult.validationFailed} so a caller reads a failed query the same way it reads a failed command.
|
|
34
|
+
* @param {ValidationResult[]} validationResults The validation results that caused the failure.
|
|
35
|
+
* @param {object} query The query being rejected, which describes how to shape its own result.
|
|
36
|
+
* @returns {QueryResult<TDataType>} A result that is neither successful nor valid.
|
|
37
|
+
*/ static validationFailed(validationResults, query) {
|
|
38
|
+
const { defaultValue, modelType, enumerable } = query;
|
|
39
|
+
return new QueryResult({
|
|
40
|
+
data: defaultValue,
|
|
41
|
+
isSuccess: false,
|
|
42
|
+
isAuthorized: true,
|
|
43
|
+
isValid: false,
|
|
44
|
+
hasExceptions: false,
|
|
45
|
+
validationResults: validationResults.map((_)=>({
|
|
46
|
+
severity: _.severity,
|
|
47
|
+
message: _.message,
|
|
48
|
+
members: _.members,
|
|
49
|
+
state: _.state
|
|
50
|
+
})),
|
|
51
|
+
exceptionMessages: [],
|
|
52
|
+
exceptionStackTrace: '',
|
|
53
|
+
paging: {
|
|
54
|
+
totalItems: 0,
|
|
55
|
+
totalPages: 0,
|
|
56
|
+
page: 0,
|
|
57
|
+
size: 0
|
|
58
|
+
}
|
|
59
|
+
}, modelType, enumerable);
|
|
60
|
+
}
|
|
31
61
|
static unauthorized() {
|
|
32
62
|
return new QueryResult({
|
|
33
63
|
data: null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryResult.js","sources":["../../../queries/QueryResult.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { IQueryResult } from './IQueryResult';\nimport { PagingInfo } from './PagingInfo';\nimport { ChangeSet } from './ChangeSet';\n\ntype ServerQueryResult = {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n data: any;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n isSuccess: boolean;\n isAuthorized: boolean;\n isValid: boolean;\n hasExceptions: boolean;\n validationResults: ServerValidationResult[];\n exceptionMessages: string[];\n exceptionStackTrace: string;\n paging: ServerPagingInfo;\n changeSet?: ServerChangeSet;\n}\n\ntype ServerChangeSet = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n added: any[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n replaced: any[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n removed: any[];\n}\n\ntype ServerValidationResult = {\n severity: number;\n message: string;\n members: string[];\n state: object;\n}\n\ntype ServerPagingInfo = {\n page: number;\n size: number; \n totalItems: number;\n totalPages: number;\n}\n\n/**\n * Represents the result from executing a {@link IQueryFor}.\n * @template TDataType The data type.\n */\nexport class QueryResult<TDataType = object> implements IQueryResult<TDataType> {\n\n static empty<TDataType>(defaultValue: TDataType): QueryResult<TDataType> {\n return new QueryResult({\n data: defaultValue as object,\n isSuccess: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n\n }, Object, false);\n }\n\n static unauthorized<TDataType>(): QueryResult<TDataType> {\n return new QueryResult({\n data: null as unknown as object,\n isSuccess: false,\n isAuthorized: false,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, Object, false);\n }\n\n static noSuccess: QueryResult = new QueryResult({\n data: {},\n isSuccess: false,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, Object, false);\n\n /**\n * Creates an instance of query result.\n * @param {*} result The raw result from the backend.\n * @param {Constructor} instanceType The type of instance to deserialize.\n * @param {boolean} enumerable Whether or not the result is supposed be an enumerable or not.\n */\n constructor(result: ServerQueryResult, instanceType: Constructor, enumerable: boolean) {\n this.isSuccess = result.isSuccess;\n this.isAuthorized = result.isAuthorized;\n this.isValid = result.isValid;\n this.hasExceptions = result.hasExceptions;\n this.validationResults = result.validationResults.map(_ => new ValidationResult(_.severity, _.message, _.members, _.state));\n this.exceptionMessages = result.exceptionMessages;\n this.exceptionStackTrace = result.exceptionStackTrace;\n this.paging = new PagingInfo();\n this.paging.page = result.paging.page;\n this.paging.size = result.paging.size;\n this.paging.totalItems = result.paging.totalItems;\n this.paging.totalPages = result.paging.totalPages;\n\n if (result.data) {\n let data: object = result.data;\n const isPrimitive = instanceType === String || instanceType === Number || instanceType === Boolean;\n if (enumerable) {\n if (Array.isArray(result.data)) {\n data = isPrimitive\n ? Array.from(result.data)\n : JsonSerializer.deserializeArrayFromInstance(instanceType, data);\n } else {\n data = [];\n }\n } else {\n data = isPrimitive ? data : JsonSerializer.deserializeFromInstance(instanceType, data);\n }\n\n this.data = data as TDataType;\n } else {\n this.data = (enumerable ? [] : null) as TDataType;\n }\n\n if (enumerable && result.changeSet) {\n const isPrimitive = instanceType === String || instanceType === Number || instanceType === Boolean;\n this.changeSet = {\n added: isPrimitive\n ? Array.from(result.changeSet.added ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.added ?? []),\n replaced: isPrimitive\n ? Array.from(result.changeSet.replaced ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.replaced ?? []),\n removed: isPrimitive\n ? Array.from(result.changeSet.removed ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.removed ?? []),\n } as ChangeSet<unknown>;\n }\n }\n\n /** @inheritdoc */\n readonly data: TDataType;\n\n /** @inheritdoc */\n readonly paging: PagingInfo;\n\n /** @inheritdoc */\n readonly isSuccess: boolean;\n\n /** @inheritdoc */\n readonly isAuthorized: boolean;\n\n /** @inheritdoc */\n readonly isValid: boolean;\n\n /** @inheritdoc */\n readonly hasExceptions: boolean;\n\n /** @inheritdoc */\n readonly validationResults: ValidationResult[];\n\n /** @inheritdoc */\n readonly exceptionMessages: string[];\n\n /** @inheritdoc */\n readonly exceptionStackTrace: string;\n\n /**\n * Gets the optional change set describing what changed since the previous update.\n * Set by the server when the delta transfer mode is active.\n * When present, clients can apply the delta to their local state rather than replacing\n * the full dataset.\n */\n readonly changeSet?: ChangeSet<unknown>;\n\n /**\n * Gets whether or not the query has data.\n */\n get hasData(): boolean {\n if (this.data) {\n if (Array.isArray(this.data)) {\n return this.data.length > 0;\n }\n return true;\n }\n return false;\n }\n}\n"],"names":["QueryResult","empty","defaultValue","data","isSuccess","isAuthorized","isValid","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","paging","totalItems","totalPages","page","size","Object","unauthorized","noSuccess","result","instanceType","enumerable","map","_","ValidationResult","severity","message","members","state","PagingInfo","isPrimitive","String","Number","Boolean","Array","isArray","from","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance","changeSet","added","replaced","removed","hasData","length"],"mappings":";;;;;;AAAA;AACA;AA8CA;;;AAGC,IACM,MAAMA,WAAAA,CAAAA;IAET,OAAOC,KAAAA,CAAiBC,YAAuB,EAA0B;AACrE,QAAA,OAAO,IAAIF,WAAAA,CAAY;YACnBG,IAAAA,EAAMD,YAAAA;YACNE,SAAAA,EAAW,IAAA;YACXC,YAAAA,EAAc,IAAA;YACdC,OAAAA,EAAS,IAAA;YACTC,aAAAA,EAAe,KAAA;AACfC,YAAAA,iBAAAA,EAAmB,EAAE;AACrBC,YAAAA,iBAAAA,EAAmB,EAAE;YACrBC,mBAAAA,EAAqB,EAAA;YACrBC,MAAAA,EAAQ;gBACJC,UAAAA,EAAY,CAAA;gBACZC,UAAAA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AAClG,aAAA;AACJ,QAAA;AACJ,IAAA;uBAGA,IAASxC;uBAGT,MAASQ;uBAGT,SAASP;uBAGT,YAASC;uBAGT,OAASC;uBAGT,aAASC;uBAGT,iBAASC;uBAGT,iBAASC;uBAGT,mBAASC;AAET;;;;;AAKC,QACD,SAAS8B;AAET;;AAEC,QACD,IAAII,OAAAA,GAAmB;QACnB,IAAI,IAAI,CAACzC,IAAI,EAAE;AACX,YAAA,IAAI+B,MAAMC,OAAO,CAAC,IAAI,CAAChC,IAAI,CAAA,EAAG;AAC1B,gBAAA,OAAO,IAAI,CAACA,IAAI,CAAC0C,MAAM,GAAG,CAAA;AAC9B,YAAA;YACA,OAAO,IAAA;AACX,QAAA;QACA,OAAO,KAAA;AACX,IAAA;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"QueryResult.js","sources":["../../../queries/QueryResult.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Constructor, JsonSerializer } from '@cratis/fundamentals';\nimport { ValidationResult } from '../validation/ValidationResult';\nimport { IQueryResult } from './IQueryResult';\nimport { PagingInfo } from './PagingInfo';\nimport { ChangeSet } from './ChangeSet';\n\ntype ServerQueryResult = {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n data: any;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n isSuccess: boolean;\n isAuthorized: boolean;\n isValid: boolean;\n hasExceptions: boolean;\n validationResults: ServerValidationResult[];\n exceptionMessages: string[];\n exceptionStackTrace: string;\n paging: ServerPagingInfo;\n changeSet?: ServerChangeSet;\n}\n\ntype ServerChangeSet = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n added: any[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n replaced: any[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n removed: any[];\n}\n\ntype ServerValidationResult = {\n severity: number;\n message: string;\n members: string[];\n state: object;\n}\n\ntype ServerPagingInfo = {\n page: number;\n size: number; \n totalItems: number;\n totalPages: number;\n}\n\n/**\n * Represents the result from executing a {@link IQueryFor}.\n * @template TDataType The data type.\n */\nexport class QueryResult<TDataType = object> implements IQueryResult<TDataType> {\n\n static empty<TDataType>(defaultValue: TDataType): QueryResult<TDataType> {\n return new QueryResult({\n data: defaultValue as object,\n isSuccess: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n\n }, Object, false);\n }\n\n /**\n * Creates a {@link QueryResult} representing a query rejected by client-side validation, mirroring\n * {@link CommandResult.validationFailed} so a caller reads a failed query the same way it reads a failed command.\n * @param {ValidationResult[]} validationResults The validation results that caused the failure.\n * @param {object} query The query being rejected, which describes how to shape its own result.\n * @returns {QueryResult<TDataType>} A result that is neither successful nor valid.\n */\n static validationFailed<TDataType>(\n validationResults: ValidationResult[],\n query: { readonly defaultValue: TDataType; readonly modelType: Constructor; readonly enumerable: boolean }): QueryResult<TDataType> {\n const { defaultValue, modelType, enumerable } = query;\n return new QueryResult({\n data: defaultValue as object,\n isSuccess: false,\n isAuthorized: true,\n isValid: false,\n hasExceptions: false,\n validationResults: validationResults.map(_ => ({\n severity: _.severity,\n message: _.message,\n members: _.members,\n state: _.state\n })),\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, modelType, enumerable) as QueryResult<TDataType>;\n }\n\n static unauthorized<TDataType>(): QueryResult<TDataType> {\n return new QueryResult({\n data: null as unknown as object,\n isSuccess: false,\n isAuthorized: false,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, Object, false);\n }\n\n static noSuccess: QueryResult = new QueryResult({\n data: {},\n isSuccess: false,\n isAuthorized: true,\n isValid: true,\n hasExceptions: false,\n validationResults: [],\n exceptionMessages: [],\n exceptionStackTrace: '',\n paging: {\n totalItems: 0,\n totalPages: 0,\n page: 0,\n size: 0\n }\n }, Object, false);\n\n /**\n * Creates an instance of query result.\n * @param {*} result The raw result from the backend.\n * @param {Constructor} instanceType The type of instance to deserialize.\n * @param {boolean} enumerable Whether or not the result is supposed be an enumerable or not.\n */\n constructor(result: ServerQueryResult, instanceType: Constructor, enumerable: boolean) {\n this.isSuccess = result.isSuccess;\n this.isAuthorized = result.isAuthorized;\n this.isValid = result.isValid;\n this.hasExceptions = result.hasExceptions;\n this.validationResults = result.validationResults.map(_ => new ValidationResult(_.severity, _.message, _.members, _.state));\n this.exceptionMessages = result.exceptionMessages;\n this.exceptionStackTrace = result.exceptionStackTrace;\n this.paging = new PagingInfo();\n this.paging.page = result.paging.page;\n this.paging.size = result.paging.size;\n this.paging.totalItems = result.paging.totalItems;\n this.paging.totalPages = result.paging.totalPages;\n\n if (result.data) {\n let data: object = result.data;\n const isPrimitive = instanceType === String || instanceType === Number || instanceType === Boolean;\n if (enumerable) {\n if (Array.isArray(result.data)) {\n data = isPrimitive\n ? Array.from(result.data)\n : JsonSerializer.deserializeArrayFromInstance(instanceType, data);\n } else {\n data = [];\n }\n } else {\n data = isPrimitive ? data : JsonSerializer.deserializeFromInstance(instanceType, data);\n }\n\n this.data = data as TDataType;\n } else {\n this.data = (enumerable ? [] : null) as TDataType;\n }\n\n if (enumerable && result.changeSet) {\n const isPrimitive = instanceType === String || instanceType === Number || instanceType === Boolean;\n this.changeSet = {\n added: isPrimitive\n ? Array.from(result.changeSet.added ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.added ?? []),\n replaced: isPrimitive\n ? Array.from(result.changeSet.replaced ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.replaced ?? []),\n removed: isPrimitive\n ? Array.from(result.changeSet.removed ?? [])\n : JsonSerializer.deserializeArrayFromInstance(instanceType, result.changeSet.removed ?? []),\n } as ChangeSet<unknown>;\n }\n }\n\n /** @inheritdoc */\n readonly data: TDataType;\n\n /** @inheritdoc */\n readonly paging: PagingInfo;\n\n /** @inheritdoc */\n readonly isSuccess: boolean;\n\n /** @inheritdoc */\n readonly isAuthorized: boolean;\n\n /** @inheritdoc */\n readonly isValid: boolean;\n\n /** @inheritdoc */\n readonly hasExceptions: boolean;\n\n /** @inheritdoc */\n readonly validationResults: ValidationResult[];\n\n /** @inheritdoc */\n readonly exceptionMessages: string[];\n\n /** @inheritdoc */\n readonly exceptionStackTrace: string;\n\n /**\n * Gets the optional change set describing what changed since the previous update.\n * Set by the server when the delta transfer mode is active.\n * When present, clients can apply the delta to their local state rather than replacing\n * the full dataset.\n */\n readonly changeSet?: ChangeSet<unknown>;\n\n /**\n * Gets whether or not the query has data.\n */\n get hasData(): boolean {\n if (this.data) {\n if (Array.isArray(this.data)) {\n return this.data.length > 0;\n }\n return true;\n }\n return false;\n }\n}\n"],"names":["QueryResult","empty","defaultValue","data","isSuccess","isAuthorized","isValid","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","paging","totalItems","totalPages","page","size","Object","validationFailed","query","modelType","enumerable","map","_","severity","message","members","state","unauthorized","noSuccess","result","instanceType","ValidationResult","PagingInfo","isPrimitive","String","Number","Boolean","Array","isArray","from","JsonSerializer","deserializeArrayFromInstance","deserializeFromInstance","changeSet","added","replaced","removed","hasData","length"],"mappings":";;;;;;AAAA;AACA;AA8CA;;;AAGC,IACM,MAAMA,WAAAA,CAAAA;IAET,OAAOC,KAAAA,CAAiBC,YAAuB,EAA0B;AACrE,QAAA,OAAO,IAAIF,WAAAA,CAAY;YACnBG,IAAAA,EAAMD,YAAAA;YACNE,SAAAA,EAAW,IAAA;YACXC,YAAAA,EAAc,IAAA;YACdC,OAAAA,EAAS,IAAA;YACTC,aAAAA,EAAe,KAAA;AACfC,YAAAA,iBAAAA,EAAmB,EAAE;AACrBC,YAAAA,iBAAAA,EAAmB,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