@skedulo/pulse-solution-services 0.0.15 → 0.0.16

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +106 -5
  3. package/dist/clients/artifact-client.js +1 -1
  4. package/dist/clients/availability-api-client.js +1 -1
  5. package/dist/clients/base-client.js +1 -1
  6. package/dist/clients/config-features-client.js +1 -1
  7. package/dist/clients/config-template-client.js +1 -1
  8. package/dist/clients/config-var-client.js +1 -1
  9. package/dist/clients/files-api-client.js +1 -1
  10. package/dist/clients/geo-api-client.js +1 -1
  11. package/dist/clients/graphql-client.js +1 -1
  12. package/dist/clients/metadata-client.js +1 -1
  13. package/dist/clients/mobile-notification-client.js +1 -1
  14. package/dist/clients/org-preference-client.js +1 -1
  15. package/dist/clients/vocabulary-client.js +1 -1
  16. package/dist/index.d.ts +96 -35
  17. package/dist/logging/decorators/log-method.js +1 -1
  18. package/dist/monitoring/decorators/monitor-call.js +1 -1
  19. package/dist/monitoring/monitoring-manager.js +1 -1
  20. package/dist/services/cache/cache-service.js +1 -1
  21. package/dist/services/cache/storage/config-var-cache-storage.js +1 -1
  22. package/dist/services/cache/storage/in-memory-cache-storage.js +1 -1
  23. package/dist/services/geoservice.js +1 -1
  24. package/dist/services/graph-batch/graph-batch.js +1 -1
  25. package/dist/services/graph-batch/unique-graph-batch.js +1 -1
  26. package/dist/services/graphql/graphql-batch-builder.d.ts +138 -0
  27. package/dist/services/graphql/graphql-batch-builder.js +1 -0
  28. package/dist/services/graphql/graphql-query-batch.d.ts +10 -0
  29. package/dist/services/graphql/graphql-query-batch.js +1 -0
  30. package/dist/services/graphql/graphql-query-builder.d.ts +11 -3
  31. package/dist/services/graphql/graphql-query-builder.js +1 -1
  32. package/dist/services/graphql/graphql-service.d.ts +78 -25
  33. package/dist/services/graphql/graphql-service.js +1 -1
  34. package/dist/services/graphql/queries.d.ts +13 -19
  35. package/dist/services/graphql/queries.js +1 -1
  36. package/dist/services/lock-service.js +1 -1
  37. package/dist/services/metadata-service.js +1 -1
  38. package/dist/services/resource-availability/builder/data-service.js +1 -1
  39. package/dist/services/resource-availability/builder/resource-availability-service.js +1 -1
  40. package/dist/services/resource-availability/builder/resource-builder.js +1 -1
  41. package/package.json +2 -2
  42. package/yarn.lock +642 -517
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MonitorCall=MonitorCall;const monitoring_registry_1=require("../monitoring-registry");function MonitorCall(r){return function(t,n,o){const e=o.value;return o.value=async function(...o){const i=r||`${t.constructor.name}.${n}`;return(0,monitoring_registry_1.getGlobalMonitorManager)().measure(i,(async()=>e.apply(this,o)))},o}}
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,n,r,o){return new(r||(r=Promise))((function(e,i){function a(t){try{c(o.next(t))}catch(t){i(t)}}function u(t){try{c(o.throw(t))}catch(t){i(t)}}function c(t){var n;t.done?e(t.value):(n=t.value,n instanceof r?n:new r((function(t){t(n)}))).then(a,u)}c((o=o.apply(t,n||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MonitorCall=MonitorCall;const monitoring_registry_1=require("../monitoring-registry");function MonitorCall(t){return function(n,r,o){const e=o.value;return o.value=function(...o){return __awaiter(this,void 0,void 0,(function*(){const i=t||`${n.constructor.name}.${r}`;return(0,monitoring_registry_1.getGlobalMonitorManager)().measure(i,(()=>__awaiter(this,void 0,void 0,(function*(){return e.apply(this,o)}))))}))},o}}
@@ -1 +1 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MonitoringManager=void 0;const logger_1=__importDefault(require("../logging/logger"));class MonitoringManager{constructor(t={}){this.totalCalls=0,this.methodCallCounts={},this.methodExecutionTimes={},this.concurrentRequests=0,this.peakConcurrentRequests=0,this.startTime=Date.now(),this.violations={},this.thresholds=t}async measure(t,e){this.incrementTotalCallsCount(),this.incrementMethodCount(t),this.trackConcurrentRequest(1,t);const s=Date.now();let o;try{o=await e()}finally{this.trackConcurrentRequest(-1,t)}const i=Date.now()-s;return this.trackExecutionTime(t,i),this.checkMethodDuration(t,i),o}trackConcurrentRequest(t,e){this.concurrentRequests+=t,this.peakConcurrentRequests=Math.max(this.peakConcurrentRequests,this.concurrentRequests),this.thresholds.maxConcurrentRequests&&this.peakConcurrentRequests>this.thresholds.maxConcurrentRequests&&this.handleViolation("maxConcurrentRequests",`Method ${e} max concurrent requests exceeded: ${this.peakConcurrentRequests} (Allowed: ${this.thresholds.maxConcurrentRequests})`)}getExecutionMetrics(){return{totalCalls:this.totalCalls,totalExecutionTimeMs:Date.now()-this.startTime,peakConcurrentRequests:this.peakConcurrentRequests,methodCallCounts:Object.assign({},this.methodCallCounts),methodExecutionTimes:Object.assign({},this.methodExecutionTimes),violations:Object.values(this.violations)}}incrementTotalCallsCount(){this.totalCalls++,this.thresholds.totalCalls&&this.totalCalls>this.thresholds.totalCalls&&this.handleViolation("totalCalls",`Total calls limit exceeded: ${this.totalCalls} (Allowed: ${this.thresholds.totalCalls})`)}incrementMethodCount(t){var e;this.methodCallCounts[t]=(null!==(e=this.methodCallCounts[t])&&void 0!==e?e:0)+1;const s=`methodCallLimit:${t}`,o=this.thresholds.maxMethodCalls;o&&this.methodCallCounts[t]>o&&this.handleViolation(s,`Method [${t}] call limit exceeded: ${this.methodCallCounts[t]} (Allowed: ${o})`)}trackExecutionTime(t,e){this.methodExecutionTimes[t]||(this.methodExecutionTimes[t]={totalTime:0,count:0,min:Number.MAX_VALUE,max:0});const s=this.methodExecutionTimes[t];s.totalTime+=e,s.count+=1,s.min=Math.min(s.min,e),s.max=Math.max(s.max,e)}checkMethodDuration(t,e){const s=this.thresholds.maxMethodExecutionTimeMs,o=`methodDurationLimit:${t}`;s&&e>s&&this.handleViolation(o,`Method [${t}] exceeded duration limit: ${e}ms (Allowed: ${s}ms)`)}handleViolation(t,e){if(this.violations[t]=e,this.thresholds.throwOnViolation)throw new Error(e);logger_1.default.warn(`[Violation] ${e}`)}}exports.MonitoringManager=MonitoringManager;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,o,s){return new(o||(o=Promise))((function(i,n){function a(t){try{r(s.next(t))}catch(t){n(t)}}function l(t){try{r(s.throw(t))}catch(t){n(t)}}function r(t){var e;t.done?i(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(a,l)}r((s=s.apply(t,e||[])).next())}))},__importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MonitoringManager=void 0;const logger_1=__importDefault(require("../logging/logger"));class MonitoringManager{constructor(t={}){this.totalCalls=0,this.methodCallCounts={},this.methodExecutionTimes={},this.concurrentRequests=0,this.peakConcurrentRequests=0,this.startTime=Date.now(),this.violations={},this.thresholds=t}measure(t,e){return __awaiter(this,void 0,void 0,(function*(){this.incrementTotalCallsCount(),this.incrementMethodCount(t),this.trackConcurrentRequest(1,t);const o=Date.now();let s;try{s=yield e()}finally{this.trackConcurrentRequest(-1,t)}const i=Date.now()-o;return this.trackExecutionTime(t,i),this.checkMethodDuration(t,i),s}))}trackConcurrentRequest(t,e){this.concurrentRequests+=t,this.peakConcurrentRequests=Math.max(this.peakConcurrentRequests,this.concurrentRequests),this.thresholds.maxConcurrentRequests&&this.peakConcurrentRequests>this.thresholds.maxConcurrentRequests&&this.handleViolation("maxConcurrentRequests",`Method ${e} max concurrent requests exceeded: ${this.peakConcurrentRequests} (Allowed: ${this.thresholds.maxConcurrentRequests})`)}getExecutionMetrics(){return{totalCalls:this.totalCalls,totalExecutionTimeMs:Date.now()-this.startTime,peakConcurrentRequests:this.peakConcurrentRequests,methodCallCounts:Object.assign({},this.methodCallCounts),methodExecutionTimes:Object.assign({},this.methodExecutionTimes),violations:Object.values(this.violations)}}incrementTotalCallsCount(){this.totalCalls++,this.thresholds.totalCalls&&this.totalCalls>this.thresholds.totalCalls&&this.handleViolation("totalCalls",`Total calls limit exceeded: ${this.totalCalls} (Allowed: ${this.thresholds.totalCalls})`)}incrementMethodCount(t){var e;this.methodCallCounts[t]=(null!==(e=this.methodCallCounts[t])&&void 0!==e?e:0)+1;const o=`methodCallLimit:${t}`,s=this.thresholds.maxMethodCalls;s&&this.methodCallCounts[t]>s&&this.handleViolation(o,`Method [${t}] call limit exceeded: ${this.methodCallCounts[t]} (Allowed: ${s})`)}trackExecutionTime(t,e){this.methodExecutionTimes[t]||(this.methodExecutionTimes[t]={totalTime:0,count:0,min:Number.MAX_VALUE,max:0});const o=this.methodExecutionTimes[t];o.totalTime+=e,o.count+=1,o.min=Math.min(o.min,e),o.max=Math.max(o.max,e)}checkMethodDuration(t,e){const o=this.thresholds.maxMethodExecutionTimeMs,s=`methodDurationLimit:${t}`;o&&e>o&&this.handleViolation(s,`Method [${t}] exceeded duration limit: ${e}ms (Allowed: ${o}ms)`)}handleViolation(t,e){if(this.violations[t]=e,this.thresholds.throwOnViolation)throw new Error(e);logger_1.default.warn(`[Violation] ${e}`)}}exports.MonitoringManager=MonitoringManager;
@@ -1 +1 @@
1
- "use strict";var __decorate=this&&this.__decorate||function(e,t,a,r){var i,n=arguments.length,s=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,a):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,a,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(n<3?i(s):n>3?i(t,a,s):i(t,a))||s);return n>3&&s&&Object.defineProperty(t,a,s),s},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CacheService=void 0;const logging_1=require("../../logging"),logger_1=__importDefault(require("../../logging/logger")),KEY_PREFIX="Z_CACHE_",DEFAULT_TTL=36e5;class CacheService{constructor(e){this.storage=e}setSecondaryCache(e){this.secondaryCache=e}async get(e,t){e=this.addPrefix(e);const a=await this.storage.get(e);if(a)try{const t=JSON.parse(a);return t.expiresAt&&Date.now()>t.expiresAt?(await this.delete(e),null):this.deserialize(t)}catch(e){return logger_1.default.error("Cache deserialization failed:",e),null}if((null==t?void 0:t.useSecondaryCache)&&this.secondaryCache){const a=await this.secondaryCache.get(e,t);return null!==a&&await this.set(e,a,{ttl:null==t?void 0:t.ttl}),a}return null}async set(e,t,a){var r;e=this.addPrefix(e);const i={type:t instanceof Date?"date":typeof t,value:t,expiresAt:Date.now()+(null!==(r=null==a?void 0:a.ttl)&&void 0!==r?r:36e5)},n=JSON.stringify(i);await this.storage.set(e,n),(null==a?void 0:a.useSecondaryCache)&&this.secondaryCache&&await this.secondaryCache.set(e,t,a)}async delete(e){e=this.addPrefix(e),await this.storage.delete(e)}async clear(){await this.storage.clear()}addPrefix(e){return e.startsWith("Z_CACHE_")?e:"Z_CACHE_"+e}deserialize(e){switch(e.type){case"number":return Number(e.value);case"boolean":return Boolean(e.value);case"object":return e.value;case"date":case"datetime":const t=new Date(e.value);return isNaN(t.getTime())?(logger_1.default.error(`Invalid ${e.type} string:`,e.value),null):t;default:return String(e.value)}}}exports.CacheService=CacheService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object]),__metadata("design:returntype",Promise)],CacheService.prototype,"get",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object,Object]),__metadata("design:returntype",Promise)],CacheService.prototype,"set",null);
1
+ "use strict";var __decorate=this&&this.__decorate||function(e,t,r,a){var i,n=arguments.length,o=n<3?t:null===a?a=Object.getOwnPropertyDescriptor(t,r):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,a);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},__awaiter=this&&this.__awaiter||function(e,t,r,a){return new(r||(r=Promise))((function(i,n){function o(e){try{c(a.next(e))}catch(e){n(e)}}function s(e){try{c(a.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,s)}c((a=a.apply(e,t||[])).next())}))},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CacheService=void 0;const logging_1=require("../../logging"),logger_1=__importDefault(require("../../logging/logger")),KEY_PREFIX="Z_CACHE_",DEFAULT_TTL=36e5;class CacheService{constructor(e){this.storage=e}setSecondaryCache(e){this.secondaryCache=e}get(e,t){return __awaiter(this,void 0,void 0,(function*(){e=this.addPrefix(e);const r=yield this.storage.get(e);if(r)try{const t=JSON.parse(r);return t.expiresAt&&Date.now()>t.expiresAt?(yield this.delete(e),null):this.deserialize(t)}catch(e){return logger_1.default.error("Cache deserialization failed:",e),null}if((null==t?void 0:t.useSecondaryCache)&&this.secondaryCache){const r=yield this.secondaryCache.get(e,t);return null!==r&&(yield this.set(e,r,{ttl:null==t?void 0:t.ttl})),r}return null}))}set(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var a;e=this.addPrefix(e);const i={type:t instanceof Date?"date":typeof t,value:t,expiresAt:Date.now()+(null!==(a=null==r?void 0:r.ttl)&&void 0!==a?a:36e5)},n=JSON.stringify(i);yield this.storage.set(e,n),(null==r?void 0:r.useSecondaryCache)&&this.secondaryCache&&(yield this.secondaryCache.set(e,t,r))}))}delete(e){return __awaiter(this,void 0,void 0,(function*(){e=this.addPrefix(e),yield this.storage.delete(e)}))}clear(){return __awaiter(this,void 0,void 0,(function*(){yield this.storage.clear()}))}addPrefix(e){return e.startsWith("Z_CACHE_")?e:"Z_CACHE_"+e}deserialize(e){switch(e.type){case"number":return Number(e.value);case"boolean":return Boolean(e.value);case"object":return e.value;case"date":case"datetime":const t=new Date(e.value);return isNaN(t.getTime())?(logger_1.default.error(`Invalid ${e.type} string:`,e.value),null):t;default:return String(e.value)}}}exports.CacheService=CacheService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object]),__metadata("design:returntype",Promise)],CacheService.prototype,"get",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object,Object]),__metadata("design:returntype",Promise)],CacheService.prototype,"set",null);
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConfigVarCacheStorage=void 0;const config_var_constants_1=require("../../../constants/config-var-constants");class ConfigVarCacheStorage{constructor(e){this.configVarClient=e}async set(e,t){try{await this.configVarClient.create({key:e,value:t,configType:config_var_constants_1.ConfigVariableType.PLAIN_TEXT})}catch(a){await this.configVarClient.update({key:e,value:t,configType:config_var_constants_1.ConfigVariableType.PLAIN_TEXT})}}async get(e){var t;try{const t=await this.configVarClient.get(e);if(t)return t.value}catch(e){if(null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.includes("not_found"))return null;throw e}return null}async delete(e){await this.configVarClient.delete(e)}async clear(){throw new Error("Clear operation is not supported by ConfigVarCacheStorage")}}exports.ConfigVarCacheStorage=ConfigVarCacheStorage;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))((function(o,r){function a(t){try{s(i.next(t))}catch(t){r(t)}}function c(t){try{s(i.throw(t))}catch(t){r(t)}}function s(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,c)}s((i=i.apply(t,e||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConfigVarCacheStorage=void 0;const config_var_constants_1=require("../../../constants/config-var-constants");class ConfigVarCacheStorage{constructor(t){this.configVarClient=t}set(t,e){return __awaiter(this,void 0,void 0,(function*(){try{yield this.configVarClient.create({key:t,value:e,configType:config_var_constants_1.ConfigVariableType.PLAIN_TEXT})}catch(n){yield this.configVarClient.update({key:t,value:e,configType:config_var_constants_1.ConfigVariableType.PLAIN_TEXT})}}))}get(t){return __awaiter(this,void 0,void 0,(function*(){var e;try{const e=yield this.configVarClient.get(t);if(e)return e.value}catch(t){if(null===(e=null==t?void 0:t.message)||void 0===e?void 0:e.includes("not_found"))return null;throw t}return null}))}delete(t){return __awaiter(this,void 0,void 0,(function*(){yield this.configVarClient.delete(t)}))}clear(){return __awaiter(this,void 0,void 0,(function*(){throw new Error("Clear operation is not supported by ConfigVarCacheStorage")}))}}exports.ConfigVarCacheStorage=ConfigVarCacheStorage;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InMemoryCacheStorage=void 0;class InMemoryCacheStorage{constructor(){this.cache=new Map}async set(e,c){this.cache.set(e,c)}async get(e){const c=this.cache.get(e);return c||null}async delete(e){this.cache.delete(e)}async clear(){this.cache.clear()}}exports.InMemoryCacheStorage=InMemoryCacheStorage;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{s(r.next(e))}catch(e){o(e)}}function c(e){try{s(r.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,c)}s((r=r.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.InMemoryCacheStorage=void 0;class InMemoryCacheStorage{constructor(){this.cache=new Map}set(e,t){return __awaiter(this,void 0,void 0,(function*(){this.cache.set(e,t)}))}get(e){return __awaiter(this,void 0,void 0,(function*(){const t=this.cache.get(e);return t||null}))}delete(e){return __awaiter(this,void 0,void 0,(function*(){this.cache.delete(e)}))}clear(){return __awaiter(this,void 0,void 0,(function*(){this.cache.clear()}))}}exports.InMemoryCacheStorage=InMemoryCacheStorage;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GeoService=void 0;const uuid_1=require("uuid");class GeoService{constructor(e){this.sessionId="",this.geoAPIClient=e,this.sessionId=this.generateNewSessionId()}async getDistanceMatrix(e,t){const s=e.map((e=>({lat:parseFloat(this.stripTrailingZeros(e.lat)),lng:parseFloat(this.stripTrailingZeros(e.lng))}))),i=t.map((e=>({lat:parseFloat(this.stripTrailingZeros(e.lat)),lng:parseFloat(this.stripTrailingZeros(e.lng))}))),r=await this.geoAPIClient.getDistanceMatrix({origins:s,destinations:i});if(!r||!r.matrix||0===r.matrix.length)throw new Error("Failed to retrieve distance matrix data");const n=new Map;for(let o=0;o<e.length;o++)for(let e=0;e<t.length;e++){const t=this.createKey(s[o],i[e]),a=r.matrix[o][e];n.set(t,a)}return n}async getAddressSuggestions(e,t=1){const s=e.sessionId||this.sessionId;e.sessionId||(e.sessionId=this.sessionId);const i=await this.geoAPIClient.autocompleteAddress(e);if(0===i.predictions.length)return null;const r=i.predictions.slice(0,t);return Promise.all(r.map((e=>this.geoAPIClient.getPlaceDetails({placeId:e.placeId,sessionId:s}))))}async getTimezone(e){return(await this.geoAPIClient.getTimezone(e)).timeZoneId}generateNewSessionId(){return(0,uuid_1.v4)()}stripTrailingZeros(e){return parseFloat(e.toFixed(8)).toString()}createKey(e,t){return`${this.stripTrailingZeros(e.lat)},${this.stripTrailingZeros(e.lng)}-${this.stripTrailingZeros(t.lat)},${this.stripTrailingZeros(t.lng)}`}}exports.GeoService=GeoService;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GeoService=void 0;const uuid_1=require("uuid");class GeoService{constructor(e){this.sessionId="",this.geoAPIClient=e,this.sessionId=this.generateNewSessionId()}getDistanceMatrix(e,t){return __awaiter(this,void 0,void 0,(function*(){const i=e.map((e=>({lat:parseFloat(this.stripTrailingZeros(e.lat)),lng:parseFloat(this.stripTrailingZeros(e.lng))}))),s=t.map((e=>({lat:parseFloat(this.stripTrailingZeros(e.lat)),lng:parseFloat(this.stripTrailingZeros(e.lng))}))),r=yield this.geoAPIClient.getDistanceMatrix({origins:i,destinations:s});if(!r||!r.matrix||0===r.matrix.length)throw new Error("Failed to retrieve distance matrix data");const n=new Map;for(let o=0;o<e.length;o++)for(let e=0;e<t.length;e++){const t=this.createKey(i[o],s[e]),a=r.matrix[o][e];n.set(t,a)}return n}))}getAddressSuggestions(e){return __awaiter(this,arguments,void 0,(function*(e,t=1){const i=e.sessionId||this.sessionId;e.sessionId||(e.sessionId=this.sessionId);const s=yield this.geoAPIClient.autocompleteAddress(e);if(0===s.predictions.length)return null;const r=s.predictions.slice(0,t);return Promise.all(r.map((e=>this.geoAPIClient.getPlaceDetails({placeId:e.placeId,sessionId:i}))))}))}getTimezone(e){return __awaiter(this,void 0,void 0,(function*(){return(yield this.geoAPIClient.getTimezone(e)).timeZoneId}))}generateNewSessionId(){return(0,uuid_1.v4)()}stripTrailingZeros(e){return parseFloat(e.toFixed(8)).toString()}createKey(e,t){return`${this.stripTrailingZeros(e.lat)},${this.stripTrailingZeros(e.lng)}-${this.stripTrailingZeros(t.lat)},${this.stripTrailingZeros(t.lng)}`}}exports.GeoService=GeoService;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphBatch=void 0;const graph_batch_config_1=require("./configs/graph-batch-config"),pagination_strategy_1=require("./pagination-strategy");class GraphBatch{constructor(t,e){this.startTime=new Date,this.context=t,this.config=(0,graph_batch_config_1.initializeConfig)(e),this.startTime=new Date}async run(){var t,e;if(this.queryBuilder=await this.start(),!this.queryBuilder)throw new Error("Query builder was not defined in start().");this.queryBuilder.withLimit(this.config.batchSize);let i=0,s=!0;for(;s&&!this.isMaxBatchesReached(i)&&(this.queryResult=await this.fetchNextPage(),this.queryResult.records&&0!==this.queryResult.records.length);)await this.execute(this.queryResult.records),i++,this.config.delaySeconds&&!this.isMaxBatchesReached(i)&&await this.delay(1e3*this.config.delaySeconds),s=null!==(e=null===(t=this.queryResult.pageInfo)||void 0===t?void 0:t.hasNextPage)&&void 0!==e&&e;await this.finish()}async finish(){this.context.logger.info("Batch process completed.")}async fetchNextPage(){var t,e,i;switch(this.config.strategy){case pagination_strategy_1.PaginationStrategy.OFFSET:this.queryResult&&(null===(t=this.queryBuilder)||void 0===t||t.withOffset(this.queryResult.endOffset+1));break;case pagination_strategy_1.PaginationStrategy.CURSOR:this.queryResult&&(null===(e=this.queryBuilder)||void 0===e||e.withCursor(this.queryResult.endCursor));break;case pagination_strategy_1.PaginationStrategy.NONE:default:null===(i=this.queryBuilder)||void 0===i||i.withFilter(`LastModifiedDate < ${this.startTime.toISOString()}`)}return this.queryBuilder.execute()}isMaxBatchesReached(t){return!!this.config.maxBatches&&t>=this.config.maxBatches}async delay(t){return new Promise((e=>setTimeout(e,t)))}}exports.GraphBatch=GraphBatch;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))((function(a,s){function n(t){try{o(r.next(t))}catch(t){s(t)}}function h(t){try{o(r.throw(t))}catch(t){s(t)}}function o(t){var e;t.done?a(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,h)}o((r=r.apply(t,e||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphBatch=void 0;const graph_batch_config_1=require("./configs/graph-batch-config"),pagination_strategy_1=require("./pagination-strategy");class GraphBatch{constructor(t,e){this.startTime=new Date,this.context=t,this.config=(0,graph_batch_config_1.initializeConfig)(e),this.startTime=new Date}run(){return __awaiter(this,void 0,void 0,(function*(){var t,e;if(this.queryBuilder=yield this.start(),!this.queryBuilder)throw new Error("Query builder was not defined in start().");this.queryBuilder.withLimit(this.config.batchSize);let i=0,r=!0;for(;r&&!this.isMaxBatchesReached(i)&&(this.queryResult=yield this.fetchNextPage(),this.queryResult.records&&0!==this.queryResult.records.length);)yield this.execute(this.queryResult.records),i++,this.config.delaySeconds&&!this.isMaxBatchesReached(i)&&(yield this.delay(1e3*this.config.delaySeconds)),r=null!==(e=null===(t=this.queryResult.pageInfo)||void 0===t?void 0:t.hasNextPage)&&void 0!==e&&e;yield this.finish()}))}finish(){return __awaiter(this,void 0,void 0,(function*(){this.context.logger.info("Batch process completed.")}))}fetchNextPage(){return __awaiter(this,void 0,void 0,(function*(){var t,e,i;switch(this.config.strategy){case pagination_strategy_1.PaginationStrategy.OFFSET:this.queryResult&&(null===(t=this.queryBuilder)||void 0===t||t.withOffset(this.queryResult.endOffset+1));break;case pagination_strategy_1.PaginationStrategy.CURSOR:this.queryResult&&(null===(e=this.queryBuilder)||void 0===e||e.withCursor(this.queryResult.endCursor));break;case pagination_strategy_1.PaginationStrategy.NONE:default:null===(i=this.queryBuilder)||void 0===i||i.withFilter(`LastModifiedDate < ${this.startTime.toISOString()}`)}return this.queryBuilder.execute()}))}isMaxBatchesReached(t){return!!this.config.maxBatches&&t>=this.config.maxBatches}delay(t){return __awaiter(this,void 0,void 0,(function*(){return new Promise((e=>setTimeout(e,t)))}))}}exports.GraphBatch=GraphBatch;
@@ -1 +1 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.UniqueGraphBatch=void 0;const logger_1=__importDefault(require("../../logging/logger")),graph_batch_1=require("./graph-batch");class UniqueGraphBatch extends graph_batch_1.GraphBatch{constructor(e,t){super(e,t),this.name=(null==t?void 0:t.name)||this.constructor.name,this.name=this.name.toUpperCase().replace(/[^A-Z0-9]/g,"_"),this.lockTtl=(null==t?void 0:t.lockTtl)||96e4}async run(){const e={name:this.name,ttl:this.lockTtl,description:`Lock for batch process: ${this.name}`};try{if(!await this.context.lockService.acquireLock(e))return void logger_1.default.error(`A batch with name '${this.name}' is already running.`);await super.run()}catch(e){logger_1.default.error(`Error running batch with name '${this.name}': ${e.message}`)}finally{await this.context.lockService.releaseLock(this.name)}}async start(){throw new Error("Subclasses must implement the 'start' method.")}async execute(e){throw new Error("Subclasses must implement the 'execute' method.")}async finish(){await super.finish()}}exports.UniqueGraphBatch=UniqueGraphBatch;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,r,i){return new(r||(r=Promise))((function(n,a){function o(t){try{s(i.next(t))}catch(t){a(t)}}function c(t){try{s(i.throw(t))}catch(t){a(t)}}function s(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,c)}s((i=i.apply(t,e||[])).next())}))},__importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.UniqueGraphBatch=void 0;const logger_1=__importDefault(require("../../logging/logger")),graph_batch_1=require("./graph-batch");class UniqueGraphBatch extends graph_batch_1.GraphBatch{constructor(t,e){super(t,e),this.name=(null==e?void 0:e.name)||this.constructor.name,this.name=this.name.toUpperCase().replace(/[^A-Z0-9]/g,"_"),this.lockTtl=(null==e?void 0:e.lockTtl)||96e4}run(){const t=Object.create(null,{run:{get:()=>super.run}});return __awaiter(this,void 0,void 0,(function*(){const e={name:this.name,ttl:this.lockTtl,description:`Lock for batch process: ${this.name}`};try{if(!(yield this.context.lockService.acquireLock(e)))return void logger_1.default.error(`A batch with name '${this.name}' is already running.`);yield t.run.call(this)}catch(t){logger_1.default.error(`Error running batch with name '${this.name}': ${t.message}`)}finally{yield this.context.lockService.releaseLock(this.name)}}))}start(){return __awaiter(this,void 0,void 0,(function*(){throw new Error("Subclasses must implement the 'start' method.")}))}execute(t){return __awaiter(this,void 0,void 0,(function*(){throw new Error("Subclasses must implement the 'execute' method.")}))}finish(){const t=Object.create(null,{finish:{get:()=>super.finish}});return __awaiter(this,void 0,void 0,(function*(){yield t.finish.call(this)}))}}exports.UniqueGraphBatch=UniqueGraphBatch;
@@ -0,0 +1,138 @@
1
+ import { GraphQLService } from "./graphql-service";
2
+ import { GraphqlQueryParams, QueryResult, MutationResult } from "../../interfaces/graphql";
3
+ /**
4
+ * A utility class for building GraphQL queries or mutations dynamically.
5
+ */
6
+ export declare class GraphQLQueryBuilder {
7
+ private objectName;
8
+ operationName: string;
9
+ private operationType;
10
+ private fields;
11
+ private filters;
12
+ private input;
13
+ private first?;
14
+ private offset?;
15
+ private orderBy?;
16
+ private after?;
17
+ private parentQueries;
18
+ private childQueries;
19
+ private isParent;
20
+ private graphqlService;
21
+ private queryParams;
22
+ /**
23
+ * Creates an instance of GraphQLQueryBuilder.
24
+ * @param queryParams - The parameters for the query or mutation.
25
+ * @param isParent - Indicates if this is a parent query.
26
+ */
27
+ constructor(queryParams: GraphqlQueryParams, isParent?: boolean);
28
+ /**
29
+ * Sets the GraphQL service to use for executing the operation.
30
+ * @param graphqlService - The GraphQL service instance.
31
+ * @returns The query builder instance for chaining.
32
+ */
33
+ setGraphqlService(graphqlService: GraphQLService): this;
34
+ /**
35
+ * Specifies the fields to be retrieved. Prevents duplicates.
36
+ * @param fields - Array of field names to include.
37
+ * @returns The query builder instance for chaining.
38
+ */
39
+ withFields(fields: string[]): this;
40
+ /**
41
+ * Adds a filter condition to the query.
42
+ * @param condition - The filter condition string.
43
+ * @returns The query builder instance for chaining.
44
+ * @throws Error if applied to a mutation or parent query.
45
+ */
46
+ withFilter(condition: string): this;
47
+ /**
48
+ * Sets the input object for a mutation.
49
+ * @param input - The mutation input object.
50
+ * @returns The query builder instance for chaining.
51
+ * @throws Error if applied to a query.
52
+ */
53
+ withInput(input: Record<string, any>): this;
54
+ /**
55
+ * Sets a limit on the number of records to retrieve.
56
+ * @param first - The maximum number of records.
57
+ * @returns The query builder instance for chaining.
58
+ * @throws Error if applied to a mutation or parent query.
59
+ */
60
+ withLimit(first: number): this;
61
+ /**
62
+ * Sets an offset for pagination.
63
+ * @param offset - The number of records to skip.
64
+ * @returns The query builder instance for chaining.
65
+ * @throws Error if applied to a mutation or parent query.
66
+ */
67
+ withOffset(offset: number): this;
68
+ /**
69
+ * Sets the order in which records should be retrieved.
70
+ * @param orderBy - The field to order by.
71
+ * @returns The query builder instance for chaining.
72
+ * @throws Error if applied to a mutation or parent query.
73
+ */
74
+ withOrderBy(orderBy: string): this;
75
+ /**
76
+ * Applies cursor-based pagination.
77
+ * @param after - The cursor to paginate after.
78
+ * @returns The query builder instance for chaining.
79
+ * @throws Error if applied to a mutation or parent query.
80
+ */
81
+ withCursor(after: string): this;
82
+ /**
83
+ * Creates a parent query.
84
+ * @param objectName - The name of the parent object.
85
+ * @returns The parent query builder instance.
86
+ */
87
+ withParentQuery(objectName: string): GraphQLQueryBuilder;
88
+ /**
89
+ * Creates a child query.
90
+ * @param objectName - The name of the child object.
91
+ * @returns The child query builder instance.
92
+ */
93
+ withChildQuery(objectName: string): GraphQLQueryBuilder;
94
+ /**
95
+ * Recursively builds the GraphQL query fields, handling nested queries.
96
+ * @returns The formatted fields string.
97
+ */
98
+ private formatQueryFields;
99
+ /**
100
+ * Builds the GraphQL operation parameters.
101
+ * @returns The structured query or mutation parameters.
102
+ */
103
+ build(): GraphqlQueryParams;
104
+ /**
105
+ * Executes the query or mutation.
106
+ * @returns A promise resolving to the operation result.
107
+ * @throws Error if no GraphQL service is set.
108
+ */
109
+ execute(): Promise<QueryResult | MutationResult>;
110
+ /**
111
+ * Generates a string representation of the GraphQL operation for debugging.
112
+ * @returns The formatted operation string.
113
+ */
114
+ toString(): string;
115
+ }
116
+ /**
117
+ * A utility class for building and executing a batch of GraphQL queries and mutations.
118
+ */
119
+ export declare class GraphQLBatchBuilder {
120
+ private operations;
121
+ /**
122
+ * Adds a query or mutation to the batch.
123
+ * @param builder - The GraphQLQueryBuilder instance for the query or mutation.
124
+ * @returns The batch builder instance for chaining.
125
+ */
126
+ add(builder: GraphQLQueryBuilder): this;
127
+ /**
128
+ * Executes the batch of queries and mutations.
129
+ * @returns A promise resolving to an array of query or mutation results.
130
+ * @throws Error if no operations are added or if GraphQL service is missing.
131
+ */
132
+ execute(): Promise<(QueryResult | MutationResult)[]>;
133
+ /**
134
+ * Generates a string representation of the batch for debugging.
135
+ * @returns A string containing all operations in the batch.
136
+ */
137
+ toString(): string;
138
+ }
@@ -0,0 +1 @@
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,r,i){return new(r||(r=Promise))((function(o,s){function n(t){try{h(i.next(t))}catch(t){s(t)}}function a(t){try{h(i.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(n,a)}h((i=i.apply(t,e||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLBatchBuilder=exports.GraphQLQueryBuilder=void 0;const graphql_1=require("../../interfaces/graphql");class GraphQLQueryBuilder{constructor(t,e=!1){if(this.fields=new Set(["UID"]),this.filters=[],this.input=null,this.parentQueries={},this.childQueries={},this.graphqlService=null,!t.objectName||!t.operationName)throw new Error("objectName and operationName are required.");this.queryParams=t,this.objectName=t.objectName.charAt(0).toLowerCase()+t.objectName.slice(1),this.operationName=t.operationName,this.operationType=t.operationType||"query",this.isParent=e}setGraphqlService(t){return this.graphqlService=t,this}withFields(t){return t.forEach((t=>this.fields.add(t))),this}withFilter(t){if("mutation"===this.operationType)throw new Error("Cannot apply filters to a mutation.");if(this.isParent)throw new Error(`Cannot apply filters to parent query for object: ${this.objectName}`);return this.filters.push(t),this}withInput(t){if("query"===this.operationType)throw new Error("Cannot apply input to a query.");if(!t||0===Object.keys(t).length)throw new Error("Mutation input cannot be empty.");return this.input=t,this}withLimit(t){if("mutation"===this.operationType)throw new Error("Cannot apply limit to a mutation.");if(this.isParent)throw new Error(`Cannot apply limit to parent query for object: ${this.objectName}`);return this.first=t,this}withOffset(t){if("mutation"===this.operationType)throw new Error("Cannot apply offset to a mutation.");if(this.isParent)throw new Error(`Cannot apply offset to parent query for object: ${this.objectName}`);return this.offset=t,this}withOrderBy(t){if("mutation"===this.operationType)throw new Error("Cannot apply orderBy to a mutation.");if(this.isParent)throw new Error(`Cannot apply orderBy to parent query for object: ${this.objectName}`);return this.orderBy=t,this}withCursor(t){if("mutation"===this.operationType)throw new Error("Cannot apply cursor to a mutation.");if(this.isParent)throw new Error(`Cannot apply cursor to parent query for object: ${this.objectName}`);return this.after=t,this}withParentQuery(t){const e=new GraphQLQueryBuilder({objectName:t,operationName:this.operationName,operationType:this.operationType},!0);return this.parentQueries[t]=e,e}withChildQuery(t){const e=new GraphQLQueryBuilder({objectName:t,operationName:this.operationName,operationType:this.operationType});return this.childQueries[t]=e,e}formatQueryFields(){const t=[...this.fields];for(const[e,r]of Object.entries(this.parentQueries))t.push(`${e} { ${r.formatQueryFields()} }`);for(const[e,r]of Object.entries(this.childQueries)){const i=r.build(),o=i.filter?`(filter: "${i.filter}")`:"";t.push(`${e} ${o} { ${i.fields||"UID"} }`)}return t.filter(Boolean).join(", ")}build(){const t={objectName:this.objectName,operationName:this.operationName,operationType:this.operationType,fields:this.formatQueryFields(),readOnly:this.queryParams.readOnly};return"query"===this.operationType?(t.filter=this.filters.length>0?this.filters.join(" AND "):void 0,t.first=this.first,t.offset=this.offset,t.orderBy=this.orderBy,t.after=this.after):t.input=this.input||void 0,t}execute(){var t;if(!this.graphqlService)throw new Error(`No GraphQL service set for ${this.operationType} execution on ${this.objectName}.`);const e=this.build();if("mutation"===this.operationType){const r={objectName:this.objectName,operationName:this.operationName,operation:(null===(t=this.input)||void 0===t?void 0:t.operation)||graphql_1.GraphqlOperations.UPDATE,records:this.input?[this.input]:[],fields:e.fields?e.fields.split(", "):["UID"]};return this.graphqlService.mutate(r)}return this.graphqlService.query(e)}toString(){const t=[];"query"===this.operationType?(this.first&&t.push(`first: ${this.first}`),this.offset&&t.push(`offset: ${this.offset}`),this.orderBy&&t.push(`orderBy: "${this.orderBy}"`),this.after&&t.push(`after: "${this.after}"`),this.filters.length&&t.push(`filter: "${this.filters.join(" AND ")}"`)):this.input&&t.push(`input: ${JSON.stringify(this.input)}`);const e=t.length?`(${t.join(", ")})`:"";return`${this.operationType} ${this.operationName} { ${this.objectName}${e} { ${this.formatQueryFields()} } }`}}exports.GraphQLQueryBuilder=GraphQLQueryBuilder;class GraphQLBatchBuilder{constructor(){this.operations=[]}add(t){return this.operations.push(t),this}execute(){return __awaiter(this,void 0,void 0,(function*(){if(!this.operations.length)return[];const t=this.operations[0].graphqlService;if(!t)throw new Error("No GraphQL service set for batch execution.");if(this.operations.some((e=>e.graphqlService!==t)))throw new Error("All operations must use the same GraphQL service.");const e=this.operations.map((t=>t.build()));return t.executeBatch(e)}))}toString(){return this.operations.map((t=>t.toString())).join("\n")}}exports.GraphQLBatchBuilder=GraphQLBatchBuilder;
@@ -0,0 +1,10 @@
1
+ import { QueryResult } from "../../interfaces";
2
+ import { GraphQLQueryBuilder } from "./graphql-query-builder";
3
+ export declare class GraphQLQueryBatch {
4
+ /**
5
+ * Executes a batch of queries.
6
+ * @param {GraphQLQueryBuilder[]} builders - Array of query builders.
7
+ * @returns {Promise<QueryResult[]>} - Array of query results.
8
+ */
9
+ execute(builders: GraphQLQueryBuilder[]): Promise<QueryResult[]>;
10
+ }
@@ -0,0 +1 @@
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(a,c){function i(t){try{u(n.next(t))}catch(t){c(t)}}function o(t){try{u(n.throw(t))}catch(t){c(t)}}function u(t){var e;t.done?a(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(i,o)}u((n=n.apply(t,e||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLQueryBatch=void 0;class GraphQLQueryBatch{execute(t){return __awaiter(this,void 0,void 0,(function*(){if(!t.length)return[];const e=t[0].graphqlService;if(!e)throw new Error("No GraphQL service set for batch execution.");const r=t.map((t=>t.build()));return e.queryBatch(r)}))}}exports.GraphQLQueryBatch=GraphQLQueryBatch;
@@ -19,7 +19,7 @@ export declare class GraphQLQueryBuilder {
19
19
  private queryParams;
20
20
  /**
21
21
  * Creates an instance of GraphQLQueryBuilder.
22
- * @param {string} graphqlQueryParams - The necessary parameters for the query.
22
+ * @param {GraphqlQueryParams} queryParams - The parameters for the query.
23
23
  * @param {boolean} [isParent=false] - Indicates if this query is a parent query.
24
24
  */
25
25
  constructor(queryParams: GraphqlQueryParams, isParent?: boolean);
@@ -64,13 +64,21 @@ export declare class GraphQLQueryBuilder {
64
64
  */
65
65
  private formatQueryFields;
66
66
  /**
67
- * Builds the GraphQL query parameters in a more structured format.
67
+ * Builds the GraphQL query parameters in a structured format.
68
68
  */
69
69
  build(): GraphqlQueryParams;
70
70
  /**
71
- * Executes the query using the GraphQL service, with improved error handling.
71
+ * Executes the query using the GraphQL service.
72
72
  */
73
73
  execute(): Promise<QueryResult>;
74
+ /**
75
+ * Executes all queries for the configured object, fetching records from the specified page range, up to a maximum of 20 pages.
76
+ * @param {number} [fromPage=1] - The starting page number (1-based, defaults to 1).
77
+ * @param {number} [toPage=20] - The ending page number (defaults to 20, capped at 20).
78
+ * @returns {Promise<QueryResult>} - A query result containing all records in the page range and pagination info.
79
+ * @throws {Error} - If the query execution fails, no GraphQL service is set, or invalid page parameters are provided.
80
+ */
81
+ executeAll(fromPage?: number, toPage?: number): Promise<QueryResult>;
74
82
  /**
75
83
  * Generates a string representation of the GraphQL query for debugging.
76
84
  */
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLQueryBuilder=void 0;class GraphQLQueryBuilder{constructor(e,r=!1){this.fields=new Set(["UID"]),this.filters=[],this.parentQueries={},this.childQueries={},this.graphqlService=null,this.queryParams=e,this.objectName=e.objectName.charAt(0).toLowerCase()+e.objectName.slice(1),this.operationName=e.operationName,this.isParent=r}setGraphqlService(e){this.graphqlService=e}withFields(e){return e.forEach((e=>this.fields.add(e))),this}withFilter(e){if(this.isParent)throw new Error("Cannot apply filters to a parent query.");return this.filters.push(e),this}withLimit(e){if(this.isParent)throw new Error("Cannot apply limit to a parent query.");return this.first=e,this}withOffset(e){if(this.isParent)throw new Error("Cannot apply offset to a parent query.");return this.offset=e,this}withOrderBy(e){if(this.isParent)throw new Error("Cannot apply orderBy to a parent query.");return this.orderBy=e,this}withCursor(e){if(this.isParent)throw new Error("Cannot apply cursor to a parent query.");return this.after=e,this}withParentQuery(e){const r=new GraphQLQueryBuilder({objectName:e,operationName:this.operationName},!0);return this.parentQueries[e]=r,r}withChildQuery(e){const r=new GraphQLQueryBuilder({objectName:e,operationName:this.operationName});return this.childQueries[e]=r,r}formatQueryFields(){const e=Object.entries(this.parentQueries).map((([e,r])=>`${e} { ${r.formatQueryFields()} }`)).join(", "),r=Object.entries(this.childQueries).map((([e,r])=>{const t=r.build();return`${e} ${t.filter?`(filter: "${t.filter}")`:""} { ${t.fields} }`})).join(", ");return[...this.fields,e,r].filter(Boolean).join(", ")}build(){return{objectName:this.objectName,operationName:this.operationName,fields:this.formatQueryFields(),filter:this.filters.length>0?this.filters.join(" AND "):void 0,first:this.first,offset:this.offset,orderBy:this.orderBy,after:this.after}}execute(){if(!this.graphqlService)return Promise.reject(new Error("No GraphQL service set for query execution."));const e=this.build();return e.readOnly=this.queryParams.readOnly,this.graphqlService.query(e)}toString(){return`{ ${this.objectName} { ${this.formatQueryFields()} } }`}}exports.GraphQLQueryBuilder=GraphQLQueryBuilder;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(s,a){function o(e){try{h(i.next(e))}catch(e){a(e)}}function n(e){try{h(i.throw(e))}catch(e){a(e)}}function h(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,n)}h((i=i.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLQueryBuilder=void 0;class GraphQLQueryBuilder{constructor(e,t=!1){this.fields=new Set(["UID"]),this.filters=[],this.parentQueries={},this.childQueries={},this.graphqlService=null,this.queryParams=e,this.objectName=e.objectName.charAt(0).toLowerCase()+e.objectName.slice(1),this.operationName=e.operationName,this.isParent=t}setGraphqlService(e){this.graphqlService=e}withFields(e){return e.forEach((e=>this.fields.add(e))),this}withFilter(e){if(this.isParent)throw new Error("Cannot apply filters to a parent query.");return this.filters.push(e),this}withLimit(e){if(this.isParent)throw new Error("Cannot apply limit to a parent query.");return this.first=e,this}withOffset(e){if(this.isParent)throw new Error("Cannot apply offset to a parent query.");return this.offset=e,this}withOrderBy(e){if(this.isParent)throw new Error("Cannot apply orderBy to a parent query.");return this.orderBy=e,this}withCursor(e){if(this.isParent)throw new Error("Cannot apply cursor to a parent query.");return this.after=e,this}withParentQuery(e){const t=new GraphQLQueryBuilder({objectName:e,operationName:this.operationName},!0);return this.parentQueries[e]=t,t}withChildQuery(e){const t=new GraphQLQueryBuilder({objectName:e,operationName:this.operationName});return this.childQueries[e]=t,t}formatQueryFields(){const e=Object.entries(this.parentQueries).map((([e,t])=>`${e} { ${t.formatQueryFields()} }`)).join(", "),t=Object.entries(this.childQueries).map((([e,t])=>{const r=t.build();return`${e} ${r.filter?`(filter: "${r.filter}")`:""} { ${r.fields||"UID"} }`})).join(", ");return[...this.fields,e,t].filter(Boolean).join(", ")}build(){return{objectName:this.objectName,operationName:this.operationName,fields:this.formatQueryFields(),filter:this.filters.length>0?this.filters.join(" AND "):void 0,first:this.first,offset:this.offset,orderBy:this.orderBy,after:this.after,readOnly:this.queryParams.readOnly}}execute(){if(!this.graphqlService)return Promise.reject(new Error("No GraphQL service set for query execution."));const e=this.build();return e.readOnly=this.queryParams.readOnly,this.graphqlService.query(e)}executeAll(){return __awaiter(this,arguments,void 0,(function*(e=1,t=20){if(!this.graphqlService)throw new Error("No GraphQL service set for query execution.");if(e<1)throw new Error("fromPage must be at least 1.");if(t<e)throw new Error("toPage must be greater than or equal to fromPage.");const r=Math.min(t,20),i=this.build(),s=yield this.graphqlService.query(i),a=s.totalCount;if(0===a)return{records:[],totalCount:0,pageInfo:{hasNextPage:!1},endCursor:"",endOffset:0};const o=this.first||200,n=Math.ceil(a/o),h=Math.min(r,n);if(0===Math.max(0,h-e+1))return{records:[],totalCount:a,pageInfo:{hasNextPage:h<n},endCursor:"",endOffset:(e-1)*o};const u=[];for(let t=e-1;t<h;t++){const e=new GraphQLQueryBuilder({objectName:this.objectName,operationName:this.operationName,readOnly:this.queryParams.readOnly});e.setGraphqlService(this.graphqlService),e.fields=new Set(this.fields),e.filters=[...this.filters],e.first=o,e.offset=t*o,e.orderBy=this.orderBy,e.after=this.after,u.push(e)}const l=yield this.graphqlService.queryBatch(u),f=l.flatMap((e=>e.records)),c=l[l.length-1];return{records:f,totalCount:s.totalCount,pageInfo:c.pageInfo,endCursor:c.endCursor,endOffset:c.endOffset}}))}toString(){return`{ ${this.objectName} { ${this.formatQueryFields()} } }`}}exports.GraphQLQueryBuilder=GraphQLQueryBuilder;
@@ -1,53 +1,106 @@
1
1
  import { GraphQLClient } from "../../clients/graphql-client";
2
- import { GraphqlMurationParams, GraphqlQueryParams, MutationResult, QueryResult } from "../../interfaces/graphql";
2
+ import { GraphqlMutationParams, GraphqlQueryParams, MutationResult, QueryResult } from "../../interfaces/graphql";
3
+ import { GraphQLQueryBuilder } from "./graphql-query-builder";
3
4
  /**
4
- * A service class for handling GraphQL operations.
5
+ * Service for executing GraphQL queries and mutations.
5
6
  */
6
7
  export declare class GraphQLService {
7
8
  private client;
8
9
  /**
9
- * Creates an instance of GraphQLService.
10
- * @param {GraphQLClient} client - The GraphQL client to use for queries and mutations.
10
+ * Constructor to initialize the GraphQL client.
11
+ * @param {GraphQLClient} client - The GraphQL client instance.
11
12
  */
12
13
  constructor(client: GraphQLClient);
13
14
  /**
14
- * Executes a GraphQL query to fetch records.
15
- * @param {GraphqlQueryParams} params - The query parameters.
16
- * @returns {Promise<QueryResult>} - The query result including records, total count, page info, and cursors.
15
+ * Executes a GraphQL query.
16
+ * @param {GraphqlQueryParams} params - The parameters for the GraphQL query.
17
+ * @returns {Promise<QueryResult>} - The query result containing records and pagination info.
18
+ * @throws {Error} - If the query execution fails.
17
19
  */
18
20
  query(params: GraphqlQueryParams): Promise<QueryResult>;
19
21
  /**
20
- * Performs a mutation operation on the GraphQL API.
21
- * @param {string} objectName - The name of the object.
22
- * @param {HasId[]} records - The records to delete.
23
- * @returns {Promise<any>} - The response from the delete operation.
22
+ * Executes a batch of queries.
23
+ * @param {GraphQLQueryBuilder[]} builders - Array of query builders.
24
+ * @returns {Promise<QueryResult[]>} - Array of query results.
24
25
  */
25
- mutate(params: GraphqlMurationParams): Promise<any>;
26
+ queryBatch(builders: GraphQLQueryBuilder[]): Promise<QueryResult[]>;
26
27
  /**
27
- * Deletes records from the GraphQL API.
28
+ * Executes a batch of GraphQL queries.
29
+ * @param {GraphqlQueryParams[]} paramsArray - An array of query parameters.
30
+ * @returns {Promise<QueryResult[]>} - An array of query results.
31
+ * @throws {Error} - If the batch execution fails.
28
32
  */
29
- delete(params: GraphqlMurationParams): Promise<any>;
33
+ private executeBatchQueries;
30
34
  /**
31
- * Updates records in the GraphQL API.
35
+ * Executes a GraphQL mutation.
36
+ * @param {GraphqlMutationParams} params - The parameters for the GraphQL mutation.
37
+ * @returns {Promise<MutationResult>} - The mutation result containing affected UIDs.
38
+ * @throws {Error} - If the mutation execution fails or the operation is invalid.
32
39
  */
33
- update(params: GraphqlMurationParams): Promise<any>;
40
+ mutate(params: GraphqlMutationParams): Promise<MutationResult>;
34
41
  /**
35
- * Inserts records into the GraphQL API.
42
+ * Executes a batch of GraphQL mutations.
43
+ * @param {GraphqlMutationParams[]} paramsArray - An array of mutation parameters.
44
+ * @returns {Promise<MutationResult[]>} - An array of mutation results.
45
+ * @throws {Error} - If the batch execution fails or if any mutation has empty records.
36
46
  */
37
- insert(params: GraphqlMurationParams): Promise<any>;
47
+ mutateBatch(paramsArray: GraphqlMutationParams[]): Promise<MutationResult[]>;
38
48
  /**
39
- * Extracts job UIDs from a GraphQL mutation response.
40
- * @param {MutationResult} response - The response object.
41
- * @returns {string[]} - An array of job UIDs.
49
+ * Deletes objects using a GraphQL mutation.
50
+ * @param {GraphqlMutationParams} params - The parameters for the delete mutation.
51
+ * @returns {Promise<MutationResult>} - The mutation result containing deleted UIDs.
52
+ * @throws {Error} - If the delete operation fails.
42
53
  */
43
- extractJobUIDs(response: MutationResult): string[];
54
+ delete(params: GraphqlMutationParams): Promise<MutationResult>;
44
55
  /**
45
- * Formats the object name to follow GraphQL naming conventions.
46
- * @param {string} objectName - The object name to format.
47
- * @returns {string} - The formatted object name.
56
+ * Updates objects using a GraphQL mutation.
57
+ * @param {GraphqlMutationParams} params - The parameters for the update mutation.
58
+ * @returns {Promise<MutationResult>} - The mutation result containing updated UIDs.
59
+ * @throws {Error} - If the update operation fails.
60
+ */
61
+ update(params: GraphqlMutationParams): Promise<MutationResult>;
62
+ /**
63
+ * Inserts objects using a GraphQL mutation.
64
+ * @param {GraphqlMutationParams} params - The parameters for the insert mutation.
65
+ * @returns {Promise<MutationResult>} - The mutation result containing inserted UIDs.
66
+ * @throws {Error} - If the insert operation fails.
67
+ */
68
+ insert(params: GraphqlMutationParams): Promise<MutationResult>;
69
+ /**
70
+ * Upserts objects using a GraphQL mutation.
71
+ * @param {GraphqlMutationParams} params - The parameters for the upsert mutation, including keyField.
72
+ * @returns {Promise<MutationResult>} - The mutation result containing upserted UIDs.
73
+ * @throws {Error} - If the upsert operation fails.
74
+ */
75
+ upsert(params: GraphqlMutationParams): Promise<MutationResult>;
76
+ /**
77
+ * Extracts UIDs from a mutation response.
78
+ * @param {MutationResult} response - The mutation response containing the schema.
79
+ * @returns {string[]} - An array of UIDs extracted from the response.
80
+ */
81
+ extractUIDs(response: MutationResult): string[];
82
+ /**
83
+ * Converts object name to GraphQL query name format.
84
+ * @param {string} objectName - The object name to convert.
85
+ * @returns {string} - The formatted query name.
48
86
  */
49
87
  private getQueryName;
88
+ /**
89
+ * Generates headers for GraphQL queries.
90
+ * @param {GraphqlQueryParams} params - The query parameters containing operationName and readOnly flag.
91
+ * @returns {Record<string, string>} - The headers for the query request.
92
+ */
50
93
  private getQueryHeaders;
94
+ /**
95
+ * Generates headers for GraphQL mutations.
96
+ * @param {GraphqlMutationParams} params - The mutation parameters containing operationName and optional flags.
97
+ * @returns {Record<string, string>} - The headers for the mutation request.
98
+ */
51
99
  private getMutationHeaders;
100
+ /**
101
+ * Generates operation header for GraphQL requests.
102
+ * @param {string} operationName - The name of the GraphQL operation.
103
+ * @returns {Record<string, string>} - The operation header.
104
+ */
52
105
  private getOperationHeader;
53
106
  }
@@ -1 +1 @@
1
- "use strict";var __decorate=this&&this.__decorate||function(e,t,a,r){var o,n=arguments.length,s=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,a):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,a,r);else for(var i=e.length-1;i>=0;i--)(o=e[i])&&(s=(n<3?o(s):n>3?o(t,a,s):o(t,a))||s);return n>3&&s&&Object.defineProperty(t,a,s),s},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLService=void 0;const constants_1=require("../../constants"),request_header_constants_1=require("../../core/request-header-constants"),logging_1=require("../../logging"),queries_1=require("./queries");class GraphQLService{constructor(e){this.client=e}async query(e){var t,a,r,o,n,s,i,d,_,c,u,l;e.objectName=this.getQueryName(e.objectName);const p=(0,queries_1.FETCH_RECORDS_QUERY)(e),g=this.getQueryHeaders(e),h=await this.client.execute(p,g),m={records:(null===(a=null===(t=null==h?void 0:h.data)||void 0===t?void 0:t[e.objectName])||void 0===a?void 0:a.edges.map((e=>e.node)))||[],totalCount:(null===(o=null===(r=null==h?void 0:h.data)||void 0===r?void 0:r[e.objectName])||void 0===o?void 0:o.totalCount)||0,pageInfo:(null===(s=null===(n=null==h?void 0:h.data)||void 0===n?void 0:n[e.objectName])||void 0===s?void 0:s.pageInfo)||{}};if(m.records.length>0){const t=(null===(_=null===(d=null===(i=null==h?void 0:h.data)||void 0===i?void 0:i[e.objectName])||void 0===d?void 0:d.edges)||void 0===_?void 0:_.map((e=>e.offset)))||[],a=(null===(l=null===(u=null===(c=null==h?void 0:h.data)||void 0===c?void 0:c[e.objectName])||void 0===u?void 0:u.edges)||void 0===l?void 0:l.map((e=>e.cursor)))||[];m.endOffset=t[t.length-1],m.endCursor=a[a.length-1]}return m}async mutate(e){if(!e.records||0===e.records.length)return Promise.resolve({message:"No records to process"});let t="";switch(e.operation){case constants_1.GraphqlOperations.DELETE:t=(0,queries_1.DELETE_OBJECTS_MUTATION)(e);break;case constants_1.GraphqlOperations.UPDATE:case constants_1.GraphqlOperations.INSERT:t=(0,queries_1.UPSERT_OBJECTS_MUTATION)(e);break;default:throw new Error(`Invalid operation: ${e.operation}`)}const a=this.getMutationHeaders(e);return await this.client.execute(t,a)}async delete(e){return e.operation=constants_1.GraphqlOperations.DELETE,this.mutate(e)}async update(e){return e.operation=constants_1.GraphqlOperations.UPDATE,this.mutate(e)}async insert(e){return e.operation=constants_1.GraphqlOperations.INSERT,this.mutate(e)}extractJobUIDs(e){var t;return(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.schema)?Object.values(e.data.schema):[]}getQueryName(e){return e.charAt(0).toLowerCase()+e.slice(1)}getQueryHeaders(e){const t=this.getOperationHeader(e.operationName);return e.readOnly&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_READ_ONLY]="true"),t}getMutationHeaders(e){const t=this.getOperationHeader(e.operationName);return e.bulkOperation&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_BULK_OPERATION]="true"),e.suppressChangeEvents&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_SUPPRESS_CHANGE_EVENTS]="true"),t}getOperationHeader(e){return{[request_header_constants_1.REQUEST_HEADERS.X_GRAPHQL_OPERATION]:e}}}exports.GraphQLService=GraphQLService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"query",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"mutate",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"delete",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"update",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"insert",null);
1
+ "use strict";var __decorate=this&&this.__decorate||function(e,t,a,r){var o,n=arguments.length,i=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,a):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,a,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(n<3?o(i):n>3?o(t,a,i):o(t,a))||i);return n>3&&i&&Object.defineProperty(t,a,i),i},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},__awaiter=this&&this.__awaiter||function(e,t,a,r){return new(a||(a=Promise))((function(o,n){function i(e){try{d(r.next(e))}catch(e){n(e)}}function s(e){try{d(r.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(i,s)}d((r=r.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLService=void 0;const constants_1=require("../../constants"),request_header_constants_1=require("../../core/request-header-constants"),logging_1=require("../../logging"),queries_1=require("./queries");class GraphQLService{constructor(e){this.client=e}query(e){return __awaiter(this,void 0,void 0,(function*(){var t,a,r,o,n,i,s,d,u,c,_,l;e.objectName=this.getQueryName(e.objectName);const p=(0,queries_1.FETCH_RECORDS_QUERY)(e),h=this.getQueryHeaders(e),v=yield this.client.execute(p,h),g={records:(null===(a=null===(t=null==v?void 0:v.data)||void 0===t?void 0:t[e.objectName])||void 0===a?void 0:a.edges.map((e=>e.node)))||[],totalCount:(null===(o=null===(r=null==v?void 0:v.data)||void 0===r?void 0:r[e.objectName])||void 0===o?void 0:o.totalCount)||0,pageInfo:(null===(i=null===(n=null==v?void 0:v.data)||void 0===n?void 0:n[e.objectName])||void 0===i?void 0:i.pageInfo)||{}};if(g.records.length>0){const t=(null===(u=null===(d=null===(s=null==v?void 0:v.data)||void 0===s?void 0:s[e.objectName])||void 0===d?void 0:d.edges)||void 0===u?void 0:u.map((e=>e.offset)))||[],a=(null===(l=null===(_=null===(c=null==v?void 0:v.data)||void 0===c?void 0:c[e.objectName])||void 0===_?void 0:_.edges)||void 0===l?void 0:l.map((e=>e.cursor)))||[];g.endOffset=t[t.length-1],g.endCursor=a[a.length-1]}return g}))}queryBatch(e){return __awaiter(this,void 0,void 0,(function*(){if(!e.length)return[];const t=e.map((e=>e.build()));return this.executeBatchQueries(t)}))}executeBatchQueries(e){return __awaiter(this,void 0,void 0,(function*(){if(!e.length)return[];const t=e.map((e=>{const t=Object.assign(Object.assign({},e),{objectName:this.getQueryName(e.objectName)});return(0,queries_1.FETCH_RECORDS_QUERY)(t)})),a=this.getQueryHeaders(e[0]);return(yield this.client.executeBatch(t,a)).map(((t,a)=>{var r,o,n,i,s,d,u,c,_,l,p,h;const v=e[a],g={records:(null===(o=null===(r=null==t?void 0:t.data)||void 0===r?void 0:r[v.objectName])||void 0===o?void 0:o.edges.map((e=>e.node)))||[],totalCount:(null===(i=null===(n=null==t?void 0:t.data)||void 0===n?void 0:n[v.objectName])||void 0===i?void 0:i.totalCount)||0,pageInfo:(null===(d=null===(s=null==t?void 0:t.data)||void 0===s?void 0:s[v.objectName])||void 0===d?void 0:d.pageInfo)||{}};if(g.records.length>0){const e=(null===(_=null===(c=null===(u=null==t?void 0:t.data)||void 0===u?void 0:u[v.objectName])||void 0===c?void 0:c.edges)||void 0===_?void 0:_.map((e=>e.offset)))||[],a=(null===(h=null===(p=null===(l=null==t?void 0:t.data)||void 0===l?void 0:l[v.objectName])||void 0===p?void 0:p.edges)||void 0===h?void 0:h.map((e=>e.cursor)))||[];g.endOffset=e[e.length-1],g.endCursor=a[a.length-1]}return g}))}))}mutate(e){return __awaiter(this,void 0,void 0,(function*(){if(!e.records||0===e.records.length)return Promise.resolve({data:{schema:{}}});let t="";switch(e.operation){case constants_1.GraphqlOperations.DELETE:t=(0,queries_1.DELETE_OBJECTS_MUTATION)(e);break;case constants_1.GraphqlOperations.INSERT:case constants_1.GraphqlOperations.UPDATE:case constants_1.GraphqlOperations.UPSERT:t=(0,queries_1.MUTATE_OBJECTS_MUTATION)(e);break;default:throw new Error(`Invalid operation: ${e.operation}`)}const a=this.getMutationHeaders(e);return yield this.client.execute(t,a)}))}mutateBatch(e){return __awaiter(this,void 0,void 0,(function*(){if(!e.length)return[];e.forEach(((e,t)=>{if(!e.records||0===e.records.length)throw new Error(`Mutation at index ${t} has empty or null records for operation '${e.operationName}'`)}));const t=e.map((e=>{switch(e.operation){case constants_1.GraphqlOperations.DELETE:return(0,queries_1.DELETE_OBJECTS_MUTATION)(e);case constants_1.GraphqlOperations.INSERT:case constants_1.GraphqlOperations.UPDATE:case constants_1.GraphqlOperations.UPSERT:return(0,queries_1.MUTATE_OBJECTS_MUTATION)(e);default:throw new Error(`Invalid operation: ${e.operation}`)}})),a=this.getMutationHeaders(e[0]);return yield this.client.executeBatch(t,a)}))}delete(e){return __awaiter(this,void 0,void 0,(function*(){return e.operation=constants_1.GraphqlOperations.DELETE,this.mutate(e)}))}update(e){return __awaiter(this,void 0,void 0,(function*(){return e.operation=constants_1.GraphqlOperations.UPDATE,this.mutate(e)}))}insert(e){return __awaiter(this,void 0,void 0,(function*(){return e.operation=constants_1.GraphqlOperations.INSERT,this.mutate(e)}))}upsert(e){return __awaiter(this,void 0,void 0,(function*(){return e.operation=constants_1.GraphqlOperations.UPSERT,this.mutate(e)}))}extractUIDs(e){var t;return(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.schema)?Object.values(e.data.schema):[]}getQueryName(e){return e.charAt(0).toLowerCase()+e.slice(1)}getQueryHeaders(e){const t=this.getOperationHeader(e.operationName);return e.readOnly&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_READ_ONLY]="true"),t}getMutationHeaders(e){const t=this.getOperationHeader(e.operationName);return e.bulkOperation&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_BULK_OPERATION]="true"),e.suppressChangeEvents&&(t[request_header_constants_1.REQUEST_HEADERS.X_SKEDULO_SUPPRESS_CHANGE_EVENTS]="true"),t}getOperationHeader(e){return{[request_header_constants_1.REQUEST_HEADERS.X_GRAPHQL_OPERATION]:e}}}exports.GraphQLService=GraphQLService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"query",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Array]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"queryBatch",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"mutate",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Array]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"mutateBatch",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"delete",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"update",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"insert",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],GraphQLService.prototype,"upsert",null);
@@ -1,26 +1,20 @@
1
- import { GraphqlMurationParams, GraphqlQueryParams } from "../../interfaces/graphql";
1
+ import { GraphqlMutationParams, GraphqlQueryParams } from "../../interfaces/graphql";
2
2
  /**
3
- * Constructs a GraphQL query for fetching records with specified parameters.
4
- *
5
- * @param params - The query parameters including object name, filter, pagination, ordering, and fields.
6
- * @returns The constructed GraphQL query string.
3
+ * Constructs a GraphQL query to fetch records for a given object.
4
+ * @param {GraphqlQueryParams} params - The parameters for the GraphQL query.
5
+ * @returns {string} - The constructed GraphQL query string.
7
6
  */
8
7
  export declare const FETCH_RECORDS_QUERY: ({ objectName, operationName, filter, first, offset, after, orderBy, fields, }: GraphqlQueryParams) => string;
9
8
  /**
10
- * Constructs a GraphQL mutation for deleting multiple objects.
11
- *
12
- * @param objectName - The name of the object to delete.
13
- * @param operationName - The graphql operation name.
14
- * @param records - The records to be deleted.
15
- * @returns The constructed GraphQL mutation string.
9
+ * Constructs a GraphQL mutation to delete objects.
10
+ * @param {GraphqlMutationParams} params - The parameters for the GraphQL mutation.
11
+ * @returns {string} - The constructed GraphQL mutation string.
16
12
  */
17
- export declare const DELETE_OBJECTS_MUTATION: ({ objectName, operationName, records }: GraphqlMurationParams) => string;
13
+ export declare const DELETE_OBJECTS_MUTATION: ({ objectName, operationName, records }: GraphqlMutationParams) => string;
18
14
  /**
19
- * Constructs a GraphQL mutation for upserting (inserting/updating) multiple objects.
20
- *
21
- * @param objectName - The name of the object to upsert.
22
- * @param records - The records to be upserted.
23
- * @param operation - The operation type ("insert" or "update").
24
- * @returns The constructed GraphQL mutation string.
15
+ * Constructs a GraphQL mutation to insert, update, or upsert objects.
16
+ * @param {GraphqlMutationParams} params - The parameters for the GraphQL mutation.
17
+ * @returns {string} - The constructed GraphQL mutation string.
18
+ * @throws {Error} - If the operation type is invalid.
25
19
  */
26
- export declare const UPSERT_OBJECTS_MUTATION: ({ objectName, operationName, records, operation }: GraphqlMurationParams) => string;
20
+ export declare const MUTATE_OBJECTS_MUTATION: ({ objectName, operationName, records, operation, keyField, }: GraphqlMutationParams) => string;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UPSERT_OBJECTS_MUTATION=exports.DELETE_OBJECTS_MUTATION=exports.FETCH_RECORDS_QUERY=void 0;const FETCH_RECORDS_QUERY=({objectName:e,operationName:n,filter:t,first:o=200,offset:E=0,after:T,orderBy:r,fields:s})=>`\n query ${n} {\n ${e}(${[t?`filter: "${t}"`:"",T?`after: "${T}"`:"",`first: ${o}`,E?`offset: ${E}`:"",r?`orderBy: "${r}"`:""].filter((e=>e)).join(", ")}) {\n totalCount\n pageInfo{\n hasNextPage\n }\n edges {\n cursor\n offset\n node {\n ${s||"UID"}\n }\n }\n }\n }\n `;exports.FETCH_RECORDS_QUERY=FETCH_RECORDS_QUERY;const DELETE_OBJECTS_MUTATION=({objectName:e,operationName:n,records:t})=>`\n mutation ${n} {\n schema {\n ${t.map(((n,t)=>`alias${t+1}:delete${e}(UID: "${n.UID}")`)).join("\n ")}\n }\n }`;exports.DELETE_OBJECTS_MUTATION=DELETE_OBJECTS_MUTATION;const UPSERT_OBJECTS_MUTATION=({objectName:e,operationName:n,records:t,operation:o})=>`\n mutation ${n} {\n schema {\n ${t.map(((n,t)=>`\n alias${t+1}:${o}${e}(input: {\n ${Object.entries(n).map((([e,n])=>`${e}: ${"string"==typeof n?`"${n}"`:n}`)).join(", ")}\n }) \n `)).join("\n ")}\n }\n }`;exports.UPSERT_OBJECTS_MUTATION=UPSERT_OBJECTS_MUTATION;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MUTATE_OBJECTS_MUTATION=exports.DELETE_OBJECTS_MUTATION=exports.FETCH_RECORDS_QUERY=void 0;const FETCH_RECORDS_QUERY=({objectName:e,operationName:n,filter:t,first:o=200,offset:r=0,after:T,orderBy:E,fields:s})=>`\n query ${n} {\n ${e}(${[t?`filter: "${t}"`:"",T?`after: "${T}"`:"",`first: ${o}`,r?`offset: ${r}`:"",E?`orderBy: "${E}"`:""].filter((e=>e)).join(", ")}) {\n totalCount\n pageInfo{\n hasNextPage\n }\n edges {\n cursor\n offset\n node {\n ${s||"UID"}\n }\n }\n }\n }\n `;exports.FETCH_RECORDS_QUERY=FETCH_RECORDS_QUERY;const DELETE_OBJECTS_MUTATION=({objectName:e,operationName:n,records:t})=>`\n mutation ${n} {\n schema {\n ${t.map(((n,t)=>`alias${t+1}:delete${e}(UID: "${n.UID}")`)).join("\n ")}\n }\n }`;exports.DELETE_OBJECTS_MUTATION=DELETE_OBJECTS_MUTATION;const MUTATE_OBJECTS_MUTATION=({objectName:e,operationName:n,records:t,operation:o,keyField:r})=>{let T;return T="upsert"===o?t.map(((n,t)=>`\n alias${t+1}:upsert${e}(\n keyField: "${r||"UID"}",\n input: {\n ${Object.entries(n).map((([e,n])=>`${e}: ${"string"==typeof n?`"${n}"`:n}`)).join(", ")}\n }\n )\n `)).join("\n "):t.map(((n,t)=>`\n alias${t+1}:${o}${e}(\n input: {\n ${Object.entries(n).map((([e,n])=>`${e}: ${"string"==typeof n?`"${n}"`:n}`)).join(", ")}\n }\n )\n `)).join("\n "),`\n mutation ${n} {\n schema {\n ${T}\n }\n }\n `};exports.MUTATE_OBJECTS_MUTATION=MUTATE_OBJECTS_MUTATION;
@@ -1 +1 @@
1
- "use strict";var __decorate=this&&this.__decorate||function(e,t,a,r){var i,o=arguments.length,c=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,a):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)c=Reflect.decorate(e,t,a,r);else for(var n=e.length-1;n>=0;n--)(i=e[n])&&(c=(o<3?i(c):o>3?i(t,a,c):i(t,a))||c);return o>3&&c&&Object.defineProperty(t,a,c),c},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockService=void 0;const logging_1=require("../logging"),logger_1=__importDefault(require("../logging/logger")),KEY_PREFIX="Z_LOCK_";class LockService{constructor(e){this.configVarClient=e}async acquireLock(e){const t="Z_LOCK_"+e.name,a=new Date(Date.now()+e.ttl).toISOString();try{let r=null;try{r=await this.configVarClient.get(t)}catch(e){}if(r){if(r.expiryDate&&new Date<new Date(r.expiryDate))return!1;await this.configVarClient.delete(t)}return await this.configVarClient.create({key:t,value:e.name,configType:"plain-text",description:e.description,expiryDate:a}),!0}catch(t){return logger_1.default.error(`Failed to acquire lock: ${e.name}`),!1}}async releaseLock(e){const t="Z_LOCK_"+e;try{let e=null;try{e=await this.configVarClient.get(t)}catch(e){}e&&await this.configVarClient.delete(t)}catch(t){logger_1.default.error(`Failed to release lock: ${e}`)}}}exports.LockService=LockService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],LockService.prototype,"acquireLock",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String]),__metadata("design:returntype",Promise)],LockService.prototype,"releaseLock",null);
1
+ "use strict";var __decorate=this&&this.__decorate||function(e,t,r,i){var o,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,i);else for(var c=e.length-1;c>=0;c--)(o=e[c])&&(a=(n<3?o(a):n>3?o(t,r,a):o(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a},__metadata=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},__awaiter=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))((function(o,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function c(e){try{l(i.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,c)}l((i=i.apply(e,t||[])).next())}))},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockService=void 0;const logging_1=require("../logging"),logger_1=__importDefault(require("../logging/logger")),KEY_PREFIX="Z_LOCK_";class LockService{constructor(e){this.configVarClient=e}acquireLock(e){return __awaiter(this,void 0,void 0,(function*(){const t="Z_LOCK_"+e.name,r=new Date(Date.now()+e.ttl).toISOString();try{let i=null;try{i=yield this.configVarClient.get(t)}catch(e){}if(i){if(i.expiryDate&&new Date<new Date(i.expiryDate))return!1;yield this.configVarClient.delete(t)}return yield this.configVarClient.create({key:t,value:e.name,configType:"plain-text",description:e.description,expiryDate:r}),!0}catch(t){return logger_1.default.error(`Failed to acquire lock: ${e.name}`),!1}}))}releaseLock(e){return __awaiter(this,void 0,void 0,(function*(){const t="Z_LOCK_"+e;try{let e=null;try{e=yield this.configVarClient.get(t)}catch(e){}e&&(yield this.configVarClient.delete(t))}catch(t){logger_1.default.error(`Failed to release lock: ${e}`)}}))}}exports.LockService=LockService,__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",Promise)],LockService.prototype,"acquireLock",null),__decorate([(0,logging_1.LogMethod)(),__metadata("design:type",Function),__metadata("design:paramtypes",[String]),__metadata("design:returntype",Promise)],LockService.prototype,"releaseLock",null);
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MetadataService=void 0;class MetadataService{constructor(t){this.client=t}async getObjectMetadata(t){const e=await this.client.fetchAllMetadata(),a={};for(const c of t){const t=e.find((t=>t.name===c));if(!t)throw new Error(`Metadata mapping not found for object: ${c}`);a[c]=await this.client.fetchObjectMetadata(t.mapping)}return a}getPicklistValues(t){const e=t.fields.filter((t=>"picklist"===t.type)),a={};for(const t of e)a[t.name]=t.values.map((t=>t.value));return a}}exports.MetadataService=MetadataService;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(t,e,a,n){return new(a||(a=Promise))((function(i,r){function c(t){try{s(n.next(t))}catch(t){r(t)}}function o(t){try{s(n.throw(t))}catch(t){r(t)}}function s(t){var e;t.done?i(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(c,o)}s((n=n.apply(t,e||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MetadataService=void 0;class MetadataService{constructor(t){this.client=t}getObjectMetadata(t){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.client.fetchAllMetadata(),a={};for(const n of t){const t=e.find((t=>t.name===n));if(!t)throw new Error(`Metadata mapping not found for object: ${n}`);a[n]=yield this.client.fetchObjectMetadata(t.mapping)}return a}))}getPicklistValues(t){const e=t.fields.filter((t=>"picklist"===t.type)),a={};for(const t of e)a[t.name]=t.values.map((t=>t.value));return a}}exports.MetadataService=MetadataService;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DataService=void 0;const tenant_objects_1=require("../../../core/tenant-objects"),graphql_1=require("../../graphql");class DataService{constructor(e){this.graphqlService=e}async getResources(e){const t=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Resources.Name,operationName:"fetchResourcesWithAvailabilities"});t.withFields(tenant_objects_1.TenantObjects.Resources.Fields).withFilter("IsActive == true"),t.withParentQuery("PrimaryRegion").withFields(tenant_objects_1.TenantObjects.Regions.Fields),e.resourceIds&&e.resourceIds.size>0?t.withFilter(`UID IN ${JSON.stringify(Array.from(e.resourceIds))}`):e.regionIds&&e.regionIds.size>0&&t.withFilter(`PrimaryRegionId IN [${Array.from(e.regionIds).map((e=>`'${e}'`)).join(",")}]`),e.useTag&&t.withChildQuery(tenant_objects_1.TenantObjects.ResourceTags.Name).withParentQuery("Tag").withFields(tenant_objects_1.TenantObjects.Tags.Fields),e.useActivity&&t.withChildQuery(tenant_objects_1.TenantObjects.Activities.Name).withFields(tenant_objects_1.TenantObjects.Activities.Fields),e.useAvailability&&t.withChildQuery(tenant_objects_1.TenantObjects.Availabilities.Name).withFields(tenant_objects_1.TenantObjects.Availabilities.Fields),e.useJobAllocation&&t.withChildQuery(tenant_objects_1.TenantObjects.JobAllocations.Name).withFields(tenant_objects_1.TenantObjects.JobAllocations.Fields).withFilter("Status NOTIN ['Deleted', 'Declined']").withParentQuery("Job").withFields(tenant_objects_1.TenantObjects.Jobs.Fields);return(await t.execute()).records}async getHolidays(e,t,i){const s={},n=t?t.toISOString().split("T")[0]:null,a=i?i.toISOString().split("T")[0]:null,r=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Holidays.Name,operationName:"fetchHolidays"});r.withFields(tenant_objects_1.TenantObjects.Holidays.Fields),r.withFilter("Global == true"),n&&r.withFilter(`EndDate >= ${n}`),a&&r.withFilter(`StartDate <= ${a}`);const o=await r.execute();if(s.GLOBAL=o.records||[],e&&e.length>0){const t=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Holidays.Name,operationName:"fetchHolidays"});t.withFields(tenant_objects_1.TenantObjects.Holidays.Fields),t.withChildQuery(tenant_objects_1.TenantObjects.HolidayRegions.Name).withFields(tenant_objects_1.TenantObjects.HolidayRegions.Fields).withFilter(`RegionId IN [${e.map((e=>`'${e}'`)).join(",")}]`),n&&t.withFilter(`EndDate >= ${n}`),a&&t.withFilter(`StartDate <= ${a}`);const i=await t.execute();for(const e of i.records||[])for(const t of e.HolidayRegions||[]){const i=t.RegionId;s[i]||(s[i]=[]),s[i].push(e)}}return s}newQueryBuilder(e){const t=new graphql_1.GraphQLQueryBuilder(e);return t.setGraphqlService(this.graphqlService),t}}exports.DataService=DataService;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(s,a){function r(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.DataService=void 0;const tenant_objects_1=require("../../../core/tenant-objects"),graphql_1=require("../../graphql");class DataService{constructor(e){this.graphqlService=e}getResources(e){return __awaiter(this,void 0,void 0,(function*(){const t=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Resources.Name,operationName:"fetchResourcesWithAvailabilities"});t.withFields(tenant_objects_1.TenantObjects.Resources.Fields).withFilter("IsActive == true"),t.withParentQuery("PrimaryRegion").withFields(tenant_objects_1.TenantObjects.Regions.Fields),e.resourceIds&&e.resourceIds.size>0?t.withFilter(`UID IN ${JSON.stringify(Array.from(e.resourceIds))}`):e.regionIds&&e.regionIds.size>0&&t.withFilter(`PrimaryRegionId IN [${Array.from(e.regionIds).map((e=>`'${e}'`)).join(",")}]`),e.useTag&&t.withChildQuery(tenant_objects_1.TenantObjects.ResourceTags.Name).withParentQuery("Tag").withFields(tenant_objects_1.TenantObjects.Tags.Fields),e.useActivity&&t.withChildQuery(tenant_objects_1.TenantObjects.Activities.Name).withFields(tenant_objects_1.TenantObjects.Activities.Fields),e.useAvailability&&t.withChildQuery(tenant_objects_1.TenantObjects.Availabilities.Name).withFields(tenant_objects_1.TenantObjects.Availabilities.Fields),e.useJobAllocation&&t.withChildQuery(tenant_objects_1.TenantObjects.JobAllocations.Name).withFields(tenant_objects_1.TenantObjects.JobAllocations.Fields).withFilter("Status NOTIN ['Deleted', 'Declined']").withParentQuery("Job").withFields(tenant_objects_1.TenantObjects.Jobs.Fields);return(yield t.execute()).records}))}getHolidays(e,t,i){return __awaiter(this,void 0,void 0,(function*(){const n={},s=t?t.toISOString().split("T")[0]:null,a=i?i.toISOString().split("T")[0]:null,r=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Holidays.Name,operationName:"fetchHolidays"});r.withFields(tenant_objects_1.TenantObjects.Holidays.Fields),r.withFilter("Global == true"),s&&r.withFilter(`EndDate >= ${s}`),a&&r.withFilter(`StartDate <= ${a}`);const o=yield r.execute();if(n.GLOBAL=o.records||[],e&&e.length>0){const t=this.newQueryBuilder({objectName:tenant_objects_1.TenantObjects.Holidays.Name,operationName:"fetchHolidays"});t.withFields(tenant_objects_1.TenantObjects.Holidays.Fields),t.withChildQuery(tenant_objects_1.TenantObjects.HolidayRegions.Name).withFields(tenant_objects_1.TenantObjects.HolidayRegions.Fields).withFilter(`RegionId IN [${e.map((e=>`'${e}'`)).join(",")}]`),s&&t.withFilter(`EndDate >= ${s}`),a&&t.withFilter(`StartDate <= ${a}`);const i=yield t.execute();for(const e of i.records||[])for(const t of e.HolidayRegions||[]){const i=t.RegionId;n[i]||(n[i]=[]),n[i].push(e)}}return n}))}newQueryBuilder(e){const t=new graphql_1.GraphQLQueryBuilder(e);return t.setGraphqlService(this.graphqlService),t}}exports.DataService=DataService;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResourceAvailabilityService=void 0;class ResourceAvailabilityService{constructor(e){this.availabilityAPIClient=e}async getAvailabilityPatterns(e){const t=await this.availabilityAPIClient.fetchAvailability({resourceIds:Array.from(e.resourceIds||[]),start:e.startTime.toISOString(),end:e.endTime.toISOString(),mergedAvailabilities:!1,entries:!0}),i=new Map;return t.forEach((e=>{if(!e.entries)return;const t=e.entries.filter((e=>"pattern"===e.type)).map((e=>({id:`${e.start}_${e.end}`,name:`${e.name}(${e.type})`,start:e.start?new Date(e.start):new Date(0),finish:e.end?new Date(e.end):new Date(0),eventType:e.type})));i.set(e.resourceId,t)})),i}}exports.ResourceAvailabilityService=ResourceAvailabilityService;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,i,r){return new(i||(i=Promise))((function(a,n){function s(e){try{c(r.next(e))}catch(e){n(e)}}function o(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResourceAvailabilityService=void 0;class ResourceAvailabilityService{constructor(e){this.availabilityAPIClient=e}getAvailabilityPatterns(e){return __awaiter(this,void 0,void 0,(function*(){const t=yield this.availabilityAPIClient.fetchAvailability({resourceIds:Array.from(e.resourceIds||[]),start:e.startTime.toISOString(),end:e.endTime.toISOString(),mergedAvailabilities:!1,entries:!0}),i=new Map;return t.forEach((e=>{if(!e.entries)return;const t=e.entries.filter((e=>"pattern"===e.type)).map((e=>({id:`${e.start}_${e.end}`,name:`${e.name}(${e.type})`,start:e.start?new Date(e.start):new Date(0),finish:e.end?new Date(e.end):new Date(0),eventType:e.type})));i.set(e.resourceId,t)})),i}))}}exports.ResourceAvailabilityService=ResourceAvailabilityService;