@po-ui/ng-sync 5.22.3 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +22 -22
  2. package/{esm2015/lib/index.js → esm2020/lib/index.mjs} +15 -15
  3. package/{esm2015/lib/models/index.js → esm2020/lib/models/index.mjs} +6 -6
  4. package/{esm2015/lib/models/po-data-message.model.js → esm2020/lib/models/po-data-message.model.mjs} +57 -57
  5. package/esm2020/lib/models/po-data-transform.model.mjs +22 -0
  6. package/esm2020/lib/models/po-entity/po-entity.model.mjs +214 -0
  7. package/{esm2015/lib/models/po-event-sourcing-error-response.model.js → esm2020/lib/models/po-event-sourcing-error-response.model.mjs} +17 -17
  8. package/{esm2015/lib/models/po-network-status.model.js → esm2020/lib/models/po-network-status.model.mjs} +44 -44
  9. package/{esm2015/lib/models/po-network-type.enum.js → esm2020/lib/models/po-network-type.enum.mjs} +30 -30
  10. package/esm2020/lib/models/po-query-builder/po-query-builder.model.mjs +238 -0
  11. package/{esm2015/lib/models/po-request-type.enum.js → esm2020/lib/models/po-request-type.enum.mjs} +16 -16
  12. package/esm2020/lib/po-sync.module.mjs +45 -0
  13. package/{esm2015/lib/services/po-event-sourcing/enums/po-event-sourcing-operation.enum.js → esm2020/lib/services/po-event-sourcing/enums/po-event-sourcing-operation.enum.mjs} +17 -17
  14. package/{esm2015/lib/services/po-event-sourcing/index.js → esm2020/lib/services/po-event-sourcing/index.mjs} +4 -4
  15. package/esm2020/lib/services/po-event-sourcing/interfaces/po-event-sourcing-item.interface.mjs +2 -0
  16. package/esm2020/lib/services/po-event-sourcing/interfaces/po-event-sourcing-summary-item.interface.mjs +2 -0
  17. package/esm2020/lib/services/po-event-sourcing/po-event-sourcing.service.mjs +372 -0
  18. package/{esm2015/lib/services/po-http-client/interfaces/po-http-header-option.interface.js → esm2020/lib/services/po-http-client/interfaces/po-http-header-option.interface.mjs} +11 -11
  19. package/esm2020/lib/services/po-http-client/interfaces/po-http-request-data.interface.mjs +2 -0
  20. package/esm2020/lib/services/po-http-client/interfaces/po-response-api.interface.mjs +2 -0
  21. package/esm2020/lib/services/po-http-client/po-http-client.service.mjs +148 -0
  22. package/{esm2015/lib/services/po-http-client/po-http-request-type.enum.js → esm2020/lib/services/po-http-client/po-http-request-type.enum.mjs} +25 -25
  23. package/esm2020/lib/services/po-network/po-network.service.mjs +58 -0
  24. package/{esm2015/lib/services/po-schema/index.js → esm2020/lib/services/po-schema/index.mjs} +4 -4
  25. package/esm2020/lib/services/po-schema/po-schema-definition/po-schema-definition.service.mjs +77 -0
  26. package/{esm2015/lib/services/po-schema/po-schema-util/po-schema-util.model.js → esm2020/lib/services/po-schema/po-schema-util/po-schema-util.model.mjs} +124 -124
  27. package/esm2020/lib/services/po-schema/po-schema.service.mjs +174 -0
  28. package/esm2020/lib/services/po-sync/interfaces/po-sync-config.interface.mjs +2 -0
  29. package/esm2020/lib/services/po-sync/interfaces/po-sync-field-options.interface.mjs +2 -0
  30. package/esm2020/lib/services/po-sync/interfaces/po-sync-response.interface.mjs +2 -0
  31. package/esm2020/lib/services/po-sync/interfaces/po-sync-schema.interface.mjs +2 -0
  32. package/esm2020/lib/services/po-sync/po-sync.service.mjs +325 -0
  33. package/{esm2015/lib/utils/utils.js → esm2020/lib/utils/utils.mjs} +63 -63
  34. package/esm2020/po-ui-ng-sync.mjs +5 -0
  35. package/{esm2015/public-api.js → esm2020/public-api.mjs} +2 -2
  36. package/fesm2015/{po-ui-ng-sync.js → po-ui-ng-sync.mjs} +2074 -2058
  37. package/fesm2015/po-ui-ng-sync.mjs.map +1 -0
  38. package/fesm2020/po-ui-ng-sync.mjs +2018 -0
  39. package/fesm2020/po-ui-ng-sync.mjs.map +1 -0
  40. package/lib/index.d.ts +14 -14
  41. package/lib/models/index.d.ts +5 -5
  42. package/lib/models/po-data-message.model.d.ts +46 -46
  43. package/lib/models/po-data-transform.model.d.ts +52 -52
  44. package/lib/models/po-entity/po-entity.model.d.ts +122 -122
  45. package/lib/models/po-event-sourcing-error-response.model.d.ts +20 -20
  46. package/lib/models/po-network-status.model.d.ts +25 -25
  47. package/lib/models/po-network-type.enum.d.ts +28 -28
  48. package/lib/models/po-query-builder/po-query-builder.model.d.ts +126 -126
  49. package/lib/models/po-request-type.enum.d.ts +14 -14
  50. package/lib/po-sync.module.d.ts +12 -7
  51. package/lib/services/po-event-sourcing/enums/po-event-sourcing-operation.enum.d.ts +11 -11
  52. package/lib/services/po-event-sourcing/index.d.ts +3 -3
  53. package/lib/services/po-event-sourcing/interfaces/po-event-sourcing-item.interface.d.ts +26 -26
  54. package/lib/services/po-event-sourcing/interfaces/po-event-sourcing-summary-item.interface.d.ts +16 -16
  55. package/lib/services/po-event-sourcing/po-event-sourcing.service.d.ts +74 -71
  56. package/lib/services/po-http-client/interfaces/po-http-header-option.interface.d.ts +15 -15
  57. package/lib/services/po-http-client/interfaces/po-http-request-data.interface.d.ts +24 -24
  58. package/lib/services/po-http-client/interfaces/po-response-api.interface.d.ts +14 -14
  59. package/lib/services/po-http-client/po-http-client.service.d.ts +78 -75
  60. package/lib/services/po-http-client/po-http-request-type.enum.d.ts +23 -23
  61. package/lib/services/po-network/po-network.service.d.ts +36 -33
  62. package/lib/services/po-schema/index.d.ts +3 -3
  63. package/lib/services/po-schema/po-schema-definition/po-schema-definition.service.d.ts +51 -48
  64. package/lib/services/po-schema/po-schema-util/po-schema-util.model.d.ts +79 -79
  65. package/lib/services/po-schema/po-schema.service.d.ts +98 -95
  66. package/lib/services/po-sync/interfaces/po-sync-config.interface.d.ts +24 -24
  67. package/lib/services/po-sync/interfaces/po-sync-field-options.interface.d.ts +15 -15
  68. package/lib/services/po-sync/interfaces/po-sync-response.interface.d.ts +20 -20
  69. package/lib/services/po-sync/interfaces/po-sync-schema.interface.d.ts +37 -37
  70. package/lib/services/po-sync/po-sync.service.d.ts +162 -159
  71. package/lib/utils/utils.d.ts +36 -36
  72. package/package.json +30 -15
  73. package/po-ui-ng-sync-6.2.0.tgz +0 -0
  74. package/po-ui-ng-sync.d.ts +5 -8
  75. package/public-api.d.ts +1 -1
  76. package/schematics/README.md +169 -169
  77. package/schematics/collection.json +15 -15
  78. package/schematics/migrations.json +30 -25
  79. package/schematics/ng-add/index.d.ts +7 -7
  80. package/schematics/ng-add/index.js +33 -33
  81. package/schematics/ng-add/index.js.map +1 -1
  82. package/schematics/ng-add/index.spec.d.ts +1 -1
  83. package/schematics/ng-add/index.spec.js +62 -62
  84. package/schematics/ng-add/index.spec.js.map +1 -1
  85. package/schematics/ng-add/schema.json +7 -7
  86. package/schematics/ng-generate/schema/files/__path__/__name@dasherize__/__name@dasherize__.constants.ts.template +13 -13
  87. package/schematics/ng-generate/schema/index.d.ts +4 -4
  88. package/schematics/ng-generate/schema/index.js +12 -12
  89. package/schematics/ng-generate/schema/index.js.map +1 -1
  90. package/schematics/ng-generate/schema/index.spec.d.ts +1 -1
  91. package/schematics/ng-generate/schema/index.spec.js +44 -44
  92. package/schematics/ng-generate/schema/index.spec.js.map +1 -1
  93. package/schematics/ng-generate/schema/schema.d.ts +3 -3
  94. package/schematics/ng-generate/schema/schema.js +2 -2
  95. package/schematics/ng-generate/schema/schema.json +31 -31
  96. package/schematics/ng-update/v2/changes.d.ts +8 -8
  97. package/schematics/ng-update/v2/changes.js +20 -20
  98. package/schematics/ng-update/v2/index.d.ts +5 -5
  99. package/schematics/ng-update/v2/index.js +101 -101
  100. package/schematics/ng-update/v2/index.js.map +1 -1
  101. package/schematics/ng-update/v3/changes.d.ts +2 -2
  102. package/schematics/ng-update/v3/changes.js +14 -14
  103. package/schematics/ng-update/v3/index.d.ts +1 -1
  104. package/schematics/ng-update/v3/index.js +16 -16
  105. package/schematics/ng-update/v3/index.js.map +1 -1
  106. package/schematics/ng-update/v4/changes.d.ts +2 -2
  107. package/schematics/ng-update/v4/changes.js +14 -14
  108. package/schematics/ng-update/v4/index.d.ts +1 -1
  109. package/schematics/ng-update/v4/index.js +15 -15
  110. package/schematics/ng-update/v4/index.js.map +1 -1
  111. package/schematics/ng-update/v5/changes.d.ts +2 -2
  112. package/schematics/ng-update/v5/changes.js +13 -13
  113. package/schematics/ng-update/v5/index.d.ts +1 -1
  114. package/schematics/ng-update/v5/index.js +15 -15
  115. package/schematics/ng-update/v5/index.js.map +1 -1
  116. package/schematics/ng-update/v6/changes.d.ts +2 -0
  117. package/schematics/ng-update/v6/changes.js +14 -0
  118. package/schematics/ng-update/v6/changes.js.map +1 -0
  119. package/schematics/ng-update/v6/index.d.ts +1 -0
  120. package/schematics/ng-update/v6/index.js +16 -0
  121. package/schematics/ng-update/v6/index.js.map +1 -0
  122. package/bundles/po-ui-ng-sync.umd.js +0 -3002
  123. package/bundles/po-ui-ng-sync.umd.js.map +0 -1
  124. package/esm2015/lib/models/po-data-transform.model.js +0 -22
  125. package/esm2015/lib/models/po-entity/po-entity.model.js +0 -229
  126. package/esm2015/lib/models/po-query-builder/po-query-builder.model.js +0 -241
  127. package/esm2015/lib/po-sync.module.js +0 -31
  128. package/esm2015/lib/services/po-event-sourcing/interfaces/po-event-sourcing-item.interface.js +0 -2
  129. package/esm2015/lib/services/po-event-sourcing/interfaces/po-event-sourcing-summary-item.interface.js +0 -2
  130. package/esm2015/lib/services/po-event-sourcing/po-event-sourcing.service.js +0 -411
  131. package/esm2015/lib/services/po-http-client/interfaces/po-http-request-data.interface.js +0 -2
  132. package/esm2015/lib/services/po-http-client/interfaces/po-response-api.interface.js +0 -2
  133. package/esm2015/lib/services/po-http-client/po-http-client.service.js +0 -147
  134. package/esm2015/lib/services/po-network/po-network.service.js +0 -58
  135. package/esm2015/lib/services/po-schema/po-schema-definition/po-schema-definition.service.js +0 -80
  136. package/esm2015/lib/services/po-schema/po-schema.service.js +0 -198
  137. package/esm2015/lib/services/po-sync/interfaces/po-sync-config.interface.js +0 -2
  138. package/esm2015/lib/services/po-sync/interfaces/po-sync-field-options.interface.js +0 -2
  139. package/esm2015/lib/services/po-sync/interfaces/po-sync-response.interface.js +0 -2
  140. package/esm2015/lib/services/po-sync/interfaces/po-sync-schema.interface.js +0 -2
  141. package/esm2015/lib/services/po-sync/po-sync.service.js +0 -336
  142. package/esm2015/po-ui-ng-sync.js +0 -9
  143. package/fesm2015/po-ui-ng-sync.js.map +0 -1
  144. package/po-ui-ng-sync-5.22.3.tgz +0 -0
  145. package/po-ui-ng-sync.metadata.json +0 -1
@@ -1,2098 +1,2114 @@
1
1
  import { __awaiter } from 'tslib';
2
+ import * as i0 from '@angular/core';
2
3
  import { Injectable, NgModule } from '@angular/core';
3
4
  import * as HttpStatus from 'http-status-codes';
4
5
  import { Subject, Observable, of, merge, fromEvent, forkJoin, timer } from 'rxjs';
5
6
  import { map, expand, reduce, mapTo, mergeMap } from 'rxjs/operators';
6
- import { PoStorageService } from '@po-ui/ng-storage';
7
- import { HttpHeaders, HttpClient, HttpClientModule } from '@angular/common/http';
7
+ import * as i1 from '@po-ui/ng-storage';
8
+ import * as i1$1 from '@angular/common/http';
9
+ import { HttpHeaders, HttpClientModule } from '@angular/common/http';
10
+ import * as i1$2 from '@ionic-native/network/ngx';
8
11
  import { Network } from '@ionic-native/network/ngx';
9
12
 
10
- /**
11
- * @description
12
- *
13
- * Classe responsável por adaptar dados de APIs que não seguem
14
- * o padrão de [API do PO UI](https://po-ui.io/guides/api).
15
- *
16
- * Essa classe deve ser estendida por uma classe que implemente cada um de seus métodos, adaptando os parâmetros de
17
- * acordo com a API do *backend* existente que se deseja comunicar.
18
- */
19
- class PoDataTransform {
20
- /**
21
- * @docsPrivate
22
- *
23
- * Método responsável por receber e armazenar os dados retornados pela API para manipulação na classe `PoDataTransform`.
24
- *
25
- * @param {any} data Dados retornados pela API.
26
- */
27
- transform(data) {
28
- this.data = data;
29
- }
13
+ /**
14
+ * @description
15
+ *
16
+ * Classe responsável por adaptar dados de APIs que não seguem
17
+ * o padrão de [API do PO UI](https://po-ui.io/guides/api).
18
+ *
19
+ * Essa classe deve ser estendida por uma classe que implemente cada um de seus métodos, adaptando os parâmetros de
20
+ * acordo com a API do *backend* existente que se deseja comunicar.
21
+ */
22
+ class PoDataTransform {
23
+ /**
24
+ * @docsPrivate
25
+ *
26
+ * Método responsável por receber e armazenar os dados retornados pela API para manipulação na classe `PoDataTransform`.
27
+ *
28
+ * @param {any} data Dados retornados pela API.
29
+ */
30
+ transform(data) {
31
+ this.data = data;
32
+ }
30
33
  }
31
34
 
32
- /**
33
- * Retorna um *array* contendo os pares `[chave, valor]` do objeto.
34
- *
35
- * Semelhante ao método `Object.entries()` nativo do javascript.
36
- *
37
- * > Veja mais em: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
38
- *
39
- * @param object Objeto que será extraído os pares [chave, valor].
40
- */
41
- const getObjectEntries = (object) => {
42
- const objectName = Object.keys(object)[0];
43
- const objectValue = object[objectName];
44
- return [objectName, objectValue];
45
- };
46
- /**
47
- * Recebe um objeto e valida se o seu valor é diferente de *undefined* ou *null*.
48
- *
49
- * @param {object} parameter Objeto contento o nome do parâmetro que está sendo validado
50
- * e o seu valor.
51
- */
52
- const validateParameter = (parameter) => {
53
- const [paramName, paramValue] = getObjectEntries(parameter);
54
- if (paramValue === undefined || paramValue === null) {
55
- throw new Error(`The ${paramName} parameter cannot be undefined or null`);
56
- }
57
- };
58
- /**
59
- * Recebe um objeto e valida se o seu valor é uma instância de *Array* e se não
60
- * está vazio.
61
- *
62
- * @param value Objeto contento o nome da propriedade que está sendo validada e o seu valor.
63
- */
64
- const validateArray = (value) => {
65
- validateParameter(value);
66
- const [paramName, paramValue] = getObjectEntries(value);
67
- if (!(paramValue instanceof Array)) {
68
- throw new Error(`${paramName} is not an Array instance`);
69
- }
70
- if (!paramValue.length) {
71
- throw new Error(`${paramName} cannot be empty array`);
72
- }
73
- };
74
- /**
75
- * Recebe um arquivo e converte para uma string base64
76
- *
77
- * @param Objeto do tipo file.
78
- */
79
- const toBase64 = (file) => new Promise((resolve, reject) => {
80
- const reader = new FileReader();
81
- reader.readAsDataURL(file);
82
- reader.onload = () => resolve(reader.result);
83
- /* istanbul ignore next */
84
- reader.onerror = error => reject(error);
85
- });
86
- /**
87
- * Recebe uma string base64 e converte para um arquivo
88
- *
89
- * @param string base64.
90
- */
91
- const toFile = (url, fileName, mimeType) => fetch(url)
92
- .then(result => result.arrayBuffer())
35
+ /**
36
+ * Retorna um *array* contendo os pares `[chave, valor]` do objeto.
37
+ *
38
+ * Semelhante ao método `Object.entries()` nativo do javascript.
39
+ *
40
+ * > Veja mais em: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
41
+ *
42
+ * @param object Objeto que será extraído os pares [chave, valor].
43
+ */
44
+ const getObjectEntries = (object) => {
45
+ const objectName = Object.keys(object)[0];
46
+ const objectValue = object[objectName];
47
+ return [objectName, objectValue];
48
+ };
49
+ /**
50
+ * Recebe um objeto e valida se o seu valor é diferente de *undefined* ou *null*.
51
+ *
52
+ * @param {object} parameter Objeto contento o nome do parâmetro que está sendo validado
53
+ * e o seu valor.
54
+ */
55
+ const validateParameter = (parameter) => {
56
+ const [paramName, paramValue] = getObjectEntries(parameter);
57
+ if (paramValue === undefined || paramValue === null) {
58
+ throw new Error(`The ${paramName} parameter cannot be undefined or null`);
59
+ }
60
+ };
61
+ /**
62
+ * Recebe um objeto e valida se o seu valor é uma instância de *Array* e se não
63
+ * está vazio.
64
+ *
65
+ * @param value Objeto contento o nome da propriedade que está sendo validada e o seu valor.
66
+ */
67
+ const validateArray = (value) => {
68
+ validateParameter(value);
69
+ const [paramName, paramValue] = getObjectEntries(value);
70
+ if (!(paramValue instanceof Array)) {
71
+ throw new Error(`${paramName} is not an Array instance`);
72
+ }
73
+ if (!paramValue.length) {
74
+ throw new Error(`${paramName} cannot be empty array`);
75
+ }
76
+ };
77
+ /**
78
+ * Recebe um arquivo e converte para uma string base64
79
+ *
80
+ * @param Objeto do tipo file.
81
+ */
82
+ const toBase64 = (file) => new Promise((resolve, reject) => {
83
+ const reader = new FileReader();
84
+ reader.readAsDataURL(file);
85
+ reader.onload = () => resolve(reader.result);
86
+ /* istanbul ignore next */
87
+ reader.onerror = error => reject(error);
88
+ });
89
+ /**
90
+ * Recebe uma string base64 e converte para um arquivo
91
+ *
92
+ * @param string base64.
93
+ */
94
+ const toFile = (url, fileName, mimeType) => fetch(url)
95
+ .then(result => result.arrayBuffer())
93
96
  .then(buffer => new File([buffer], fileName, { type: mimeType }));
94
97
 
95
- /**
96
- * @description
97
- *
98
- * Classe que define a resposta de erro para um item da fila de eventos que não foi enviado ao servidor por
99
- * alguma inconsistência.
100
- *
101
- * > Pode ser utilizada em casos onde um item da fila é enviado ao servidor com inconsistência nos dados, por exemplo
102
- * uma operação de *delete* ou *update* sem o `id` do objeto.
103
- */
104
- class PoEventSourcingErrorResponse {
105
- /* istanbul ignore next */
106
- constructor({ message, operation }) {
107
- this.message = message;
108
- this.operation = operation;
109
- }
98
+ /**
99
+ * @description
100
+ *
101
+ * Classe que define a resposta de erro para um item da fila de eventos que não foi enviado ao servidor por
102
+ * alguma inconsistência.
103
+ *
104
+ * > Pode ser utilizada em casos onde um item da fila é enviado ao servidor com inconsistência nos dados, por exemplo
105
+ * uma operação de *delete* ou *update* sem o `id` do objeto.
106
+ */
107
+ class PoEventSourcingErrorResponse {
108
+ /* istanbul ignore next */
109
+ constructor({ message, operation }) {
110
+ this.message = message;
111
+ this.operation = operation;
112
+ }
110
113
  }
111
114
 
112
- /**
113
- * @docsPrivate
114
- *
115
- * Define as operações realizadas no sync.
116
- */
117
- var PoEventSourcingOperation;
118
- (function (PoEventSourcingOperation) {
119
- // Operação de exclusão.
120
- PoEventSourcingOperation["Delete"] = "DELETE";
121
- // Operação de requisição HTTP.
122
- PoEventSourcingOperation["Http"] = "HTTP";
123
- // Operação de inserção.
124
- PoEventSourcingOperation["Insert"] = "INSERT";
125
- // Operação de alteração.
126
- PoEventSourcingOperation["Update"] = "UPDATE";
115
+ /**
116
+ * @docsPrivate
117
+ *
118
+ * Define as operações realizadas no sync.
119
+ */
120
+ var PoEventSourcingOperation;
121
+ (function (PoEventSourcingOperation) {
122
+ // Operação de exclusão.
123
+ PoEventSourcingOperation["Delete"] = "DELETE";
124
+ // Operação de requisição HTTP.
125
+ PoEventSourcingOperation["Http"] = "HTTP";
126
+ // Operação de inserção.
127
+ PoEventSourcingOperation["Insert"] = "INSERT";
128
+ // Operação de alteração.
129
+ PoEventSourcingOperation["Update"] = "UPDATE";
127
130
  })(PoEventSourcingOperation || (PoEventSourcingOperation = {}));
128
131
 
129
- /**
130
- * @usedBy PoHttpClientService, PoHttpCommandResponse, PoSyncService
131
- *
132
- * @description
133
- *
134
- * Define o método de requisição HTTP.
135
- */
136
- var PoHttpRequestType;
137
- (function (PoHttpRequestType) {
138
- /** Método `delete` do protocolo HTTP. */
139
- PoHttpRequestType["DELETE"] = "DELETE";
140
- /** Método `get` do protocolo HTTP. */
141
- PoHttpRequestType["GET"] = "GET";
142
- /** Método `head` do protocolo HTTP. */
143
- PoHttpRequestType["HEAD"] = "HEAD";
144
- /** Método `options` do protocolo HTTP. */
145
- PoHttpRequestType["OPTIONS"] = "OPTIONS";
146
- /** Método `patch` do protocolo HTTP. */
147
- PoHttpRequestType["PATCH"] = "PATCH";
148
- /** Método `post` do protocolo HTTP. */
149
- PoHttpRequestType["POST"] = "POST";
150
- /** Método `put` do protocolo HTTP. */
151
- PoHttpRequestType["PUT"] = "PUT";
132
+ /**
133
+ * @usedBy PoHttpClientService, PoHttpCommandResponse, PoSyncService
134
+ *
135
+ * @description
136
+ *
137
+ * Define o método de requisição HTTP.
138
+ */
139
+ var PoHttpRequestType;
140
+ (function (PoHttpRequestType) {
141
+ /** Método `delete` do protocolo HTTP. */
142
+ PoHttpRequestType["DELETE"] = "DELETE";
143
+ /** Método `get` do protocolo HTTP. */
144
+ PoHttpRequestType["GET"] = "GET";
145
+ /** Método `head` do protocolo HTTP. */
146
+ PoHttpRequestType["HEAD"] = "HEAD";
147
+ /** Método `options` do protocolo HTTP. */
148
+ PoHttpRequestType["OPTIONS"] = "OPTIONS";
149
+ /** Método `patch` do protocolo HTTP. */
150
+ PoHttpRequestType["PATCH"] = "PATCH";
151
+ /** Método `post` do protocolo HTTP. */
152
+ PoHttpRequestType["POST"] = "POST";
153
+ /** Método `put` do protocolo HTTP. */
154
+ PoHttpRequestType["PUT"] = "PUT";
152
155
  })(PoHttpRequestType || (PoHttpRequestType = {}));
153
156
 
154
- /**
155
- * @docsPrivate
156
- *
157
- * @description
158
- *
159
- * Serviço para execução de requisições HTTP.
160
- */
161
- class PoHttpClientService {
162
- constructor(httpClient) {
163
- this.httpClient = httpClient;
164
- }
165
- /**
166
- * Constrói uma requisição HTTP personalizada.
167
- *
168
- * @param {PoHttpRequestData} poHttpOperationData Parâmetros para a construção
169
- * da requisição.
170
- */
171
- createRequest(poHttpOperationData) {
172
- const httpHeaders = this.createHttpHeaders(poHttpOperationData.headers);
173
- return this.httpClient.request(poHttpOperationData.method, poHttpOperationData.url, {
174
- observe: 'response',
175
- headers: httpHeaders,
176
- body: poHttpOperationData.body
177
- });
178
- }
179
- /**
180
- * Constrói uma requisição com o método `delete`.
181
- *
182
- * @param {string} url URL da requisição.
183
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
184
- */
185
- delete(url, httpHeaders) {
186
- const requestData = {
187
- url: url,
188
- method: PoHttpRequestType.DELETE,
189
- headers: httpHeaders
190
- };
191
- return this.createRequest(requestData);
192
- }
193
- /**
194
- * Constrói uma requisição com o método `get`.
195
- *
196
- * @param {string} url URL da requisição.
197
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
198
- */
199
- get(url, httpHeaders) {
200
- const requestData = {
201
- url: url,
202
- method: PoHttpRequestType.GET,
203
- headers: httpHeaders
204
- };
205
- return this.createRequest(requestData);
206
- }
207
- /**
208
- * Constrói uma requisição com o método `head`.
209
- *
210
- * @param {string} url URL da requisição.
211
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
212
- */
213
- head(url, httpHeaders) {
214
- const requestData = {
215
- url: url,
216
- method: PoHttpRequestType.HEAD,
217
- headers: httpHeaders
218
- };
219
- return this.createRequest(requestData);
220
- }
221
- /**
222
- * Constrói uma requisição com o método `options`.
223
- *
224
- * @param {string} url URL da requisição.
225
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
226
- */
227
- options(url, httpHeaders) {
228
- const requestData = {
229
- url: url,
230
- method: PoHttpRequestType.OPTIONS,
231
- headers: httpHeaders
232
- };
233
- return this.createRequest(requestData);
234
- }
235
- /**
236
- * Constrói uma requisição com o método `patch`.
237
- *
238
- * @param {string} url URL da requisição.
239
- * @param {any} body Corpo da requisição.
240
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
241
- */
242
- patch(url, body, httpHeaders) {
243
- const requestData = {
244
- url: url,
245
- method: PoHttpRequestType.PATCH,
246
- headers: httpHeaders,
247
- body: body
248
- };
249
- return this.createRequest(requestData);
250
- }
251
- /**
252
- * Constrói uma requisição com o método `post`.
253
- *
254
- * @param {string} url URL da requisição.
255
- * @param {any} body Corpo da requisição.
256
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
257
- */
258
- post(url, body, httpHeaders) {
259
- const requestData = {
260
- url: url,
261
- method: PoHttpRequestType.POST,
262
- headers: httpHeaders,
263
- body: body
264
- };
265
- return this.createRequest(requestData);
266
- }
267
- /**
268
- * Constrói uma requisição com o método `put`.
269
- *
270
- * @param {string} url URL da requisição.
271
- * @param {any} body Corpo da requisição.
272
- * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
273
- */
274
- put(url, body, httpHeaders) {
275
- const requestData = {
276
- url: url,
277
- method: PoHttpRequestType.PUT,
278
- headers: httpHeaders,
279
- body: body
280
- };
281
- return this.createRequest(requestData);
282
- }
283
- createHttpHeaders(poHttpOperationHeaders) {
284
- let httpHeaders = new HttpHeaders();
285
- if (poHttpOperationHeaders && poHttpOperationHeaders.length > 0) {
286
- poHttpOperationHeaders.forEach(poHttpHeader => (httpHeaders = httpHeaders.append(poHttpHeader.name, poHttpHeader.value)));
287
- }
288
- return httpHeaders;
289
- }
290
- }
291
- PoHttpClientService.decorators = [
292
- { type: Injectable }
293
- ];
294
- PoHttpClientService.ctorParameters = () => [
295
- { type: HttpClient }
296
- ];
297
-
298
- /**
299
- * @docsPrivate
300
- *
301
- * @description
302
- *
303
- * Método de requisição HTTP.
304
- */
305
- var PoRequestType;
306
- (function (PoRequestType) {
307
- PoRequestType["GET"] = "get";
308
- PoRequestType["DELETE"] = "delete";
309
- PoRequestType["DIFF"] = "diff";
310
- PoRequestType["PATCH"] = "patch";
311
- PoRequestType["POST"] = "post";
157
+ /**
158
+ * @docsPrivate
159
+ *
160
+ * @description
161
+ *
162
+ * Método de requisição HTTP.
163
+ */
164
+ var PoRequestType;
165
+ (function (PoRequestType) {
166
+ PoRequestType["GET"] = "get";
167
+ PoRequestType["DELETE"] = "delete";
168
+ PoRequestType["DIFF"] = "diff";
169
+ PoRequestType["PATCH"] = "patch";
170
+ PoRequestType["POST"] = "post";
312
171
  })(PoRequestType || (PoRequestType = {}));
313
172
 
314
- /**
315
- * @docsPrivate
316
- *
317
- * @description
318
- *
319
- * Serviço utilitário para operações no PoSyncSchema.
320
- */
321
- class PoSchemaUtil {
322
- /**
323
- * Verica se existem campos locais no *schema* informado.
324
- *
325
- * @param {PoSyncSchema} schema **Schema* a ser processado.
326
- *
327
- * @returns {boolean} Valor do tipo *boolean* que indica se existem campos locais no *schema* informado.
328
- */
329
- static containsLocalFields(schema) {
330
- if (schema.fields) {
331
- return !!schema.fields.find(field => typeof field === 'object' && field.local);
332
- }
333
- }
334
- /**
335
- * Retorna o valor atual do `lastSync` para determinado *schema*.
336
- *
337
- * @param {Array<PoSyncSchema>} storageSchemas Lista de *schemas* a serem pesquisados.
338
- * @param {string} schemaName Nome do *schema* que se deseja ler o lastSync.
339
- *
340
- * @returns {string} Retorna uma *string* com o valor da última sincronização.
341
- */
342
- static getLastSync(storageSchemas, schemaName) {
343
- if (storageSchemas) {
344
- const schemaFound = storageSchemas.find(schema => schema.name === schemaName);
345
- return schemaFound && schemaFound.lastSync ? schemaFound.lastSync : PoSchemaUtil.defaultLastSync;
346
- }
347
- return PoSchemaUtil.defaultLastSync;
348
- }
349
- /**
350
- * Retorna a lista de campos locais definidos no *schema*.
351
- *
352
- * @param {PoSyncSchema} schema **Schema* a ser processado.
353
- */
354
- static getLocalFieldNames(schema) {
355
- if (schema.fields) {
356
- return schema.fields.reduce((fieldsAccumulator, currentField) => {
357
- if (typeof currentField === 'object' && currentField.local) {
358
- fieldsAccumulator.push(currentField.name);
359
- }
360
- return fieldsAccumulator;
361
- }, []);
362
- }
363
- }
364
- /**
365
- * Retorna a lista de campos não locais definidos no *schema*.
366
- *
367
- * @param {PoSyncSchema} schema **Schema* a ser processado.
368
- */
369
- static getNonLocalFieldNames(schema) {
370
- if (schema.fields) {
371
- return schema.fields.reduce((fieldsAccumulator, currentField) => {
372
- if (typeof currentField === 'string' || !currentField.local) {
373
- fieldsAccumulator.push(typeof currentField === 'string' ? currentField : currentField.name);
374
- }
375
- return fieldsAccumulator;
376
- }, []);
377
- }
378
- }
379
- /**
380
- * Retorna o `id` referente ao registro do *schema* informado.
381
- *
382
- * @param {object} record Registro que será buscado o id.
383
- * @param {PoSyncSchema} schema **Schema* a ser processado.
384
- */
385
- static getRecordId(record, schema) {
386
- return record[schema.idField] || record[PoSchemaUtil.syncInternalIdFieldName];
387
- }
388
- /**
389
- * Retorna a url correspondente do `PoSyncSchema` dependendo do tipo da requisição `PoRequestType`.
390
- *
391
- * @param {PoSyncSchema} schema **Schema* a ser processado.
392
- * @param {PoRequestType} requestType Tipo da requisição.
393
- */
394
- static getUrl(schema, requestType) {
395
- return schema[`${requestType}UrlApi`];
396
- }
397
- /**
398
- * Compara se dois objetos são iguais baseado na lista de campos.
399
- *
400
- * @param {Array<string>} fields Lista de campos a serem considerados na comparação.
401
- * @param {any} model1 Objeto 1 a ser comparado.
402
- * @param {any} model2 Objeto 2 a ser comparado.
403
- */
404
- static isModelsEqual(fields, model1, model2) {
405
- if (fields) {
406
- return fields.every(field => JSON.stringify(model1[field]) === JSON.stringify(model2[field]));
407
- }
408
- }
409
- /**
410
- * Retorna uma lista com dois objetos referentes ao registro informado.
411
- * O primeiro é o registro com os campos que vão para o servidor e o segundo é com os campos locais.
412
- *
413
- * @param {PoSyncSchema} schema **Schema* do registro.
414
- * @param {object} record Registro que será realizada a separação dos campos locais e do servidor.
415
- */
416
- static separateSchemaFields(schema, record) {
417
- const localFields = PoSchemaUtil.getLocalFieldNames(schema);
418
- const localRecord = {};
419
- const serverRecord = {};
420
- Object.keys(record).forEach(field => {
421
- if (localFields.includes(field)) {
422
- localRecord[field] = record[field];
423
- }
424
- else {
425
- serverRecord[field] = record[field];
426
- }
427
- });
428
- return { serverRecord, localRecord };
429
- }
430
- }
431
- /** Valor `default` para o campo `lastSync`. */
432
- PoSchemaUtil.defaultLastSync = new Date(-8640000000000000).toISOString();
433
- /** Nome da chave do identificador interno do sync. */
434
- PoSchemaUtil.syncInternalIdFieldName = 'SyncInternalId';
435
- /** Nome da chave no `storage` para os Schemas. */
173
+ /**
174
+ * @docsPrivate
175
+ *
176
+ * @description
177
+ *
178
+ * Serviço utilitário para operações no PoSyncSchema.
179
+ */
180
+ class PoSchemaUtil {
181
+ /**
182
+ * Verica se existem campos locais no *schema* informado.
183
+ *
184
+ * @param {PoSyncSchema} schema **Schema* a ser processado.
185
+ *
186
+ * @returns {boolean} Valor do tipo *boolean* que indica se existem campos locais no *schema* informado.
187
+ */
188
+ static containsLocalFields(schema) {
189
+ if (schema.fields) {
190
+ return !!schema.fields.find(field => typeof field === 'object' && field.local);
191
+ }
192
+ }
193
+ /**
194
+ * Retorna o valor atual do `lastSync` para determinado *schema*.
195
+ *
196
+ * @param {Array<PoSyncSchema>} storageSchemas Lista de *schemas* a serem pesquisados.
197
+ * @param {string} schemaName Nome do *schema* que se deseja ler o lastSync.
198
+ *
199
+ * @returns {string} Retorna uma *string* com o valor da última sincronização.
200
+ */
201
+ static getLastSync(storageSchemas, schemaName) {
202
+ if (storageSchemas) {
203
+ const schemaFound = storageSchemas.find(schema => schema.name === schemaName);
204
+ return schemaFound && schemaFound.lastSync ? schemaFound.lastSync : PoSchemaUtil.defaultLastSync;
205
+ }
206
+ return PoSchemaUtil.defaultLastSync;
207
+ }
208
+ /**
209
+ * Retorna a lista de campos locais definidos no *schema*.
210
+ *
211
+ * @param {PoSyncSchema} schema **Schema* a ser processado.
212
+ */
213
+ static getLocalFieldNames(schema) {
214
+ if (schema.fields) {
215
+ return schema.fields.reduce((fieldsAccumulator, currentField) => {
216
+ if (typeof currentField === 'object' && currentField.local) {
217
+ fieldsAccumulator.push(currentField.name);
218
+ }
219
+ return fieldsAccumulator;
220
+ }, []);
221
+ }
222
+ }
223
+ /**
224
+ * Retorna a lista de campos não locais definidos no *schema*.
225
+ *
226
+ * @param {PoSyncSchema} schema **Schema* a ser processado.
227
+ */
228
+ static getNonLocalFieldNames(schema) {
229
+ if (schema.fields) {
230
+ return schema.fields.reduce((fieldsAccumulator, currentField) => {
231
+ if (typeof currentField === 'string' || !currentField.local) {
232
+ fieldsAccumulator.push(typeof currentField === 'string' ? currentField : currentField.name);
233
+ }
234
+ return fieldsAccumulator;
235
+ }, []);
236
+ }
237
+ }
238
+ /**
239
+ * Retorna o `id` referente ao registro do *schema* informado.
240
+ *
241
+ * @param {object} record Registro que será buscado o id.
242
+ * @param {PoSyncSchema} schema **Schema* a ser processado.
243
+ */
244
+ static getRecordId(record, schema) {
245
+ return record[schema.idField] || record[PoSchemaUtil.syncInternalIdFieldName];
246
+ }
247
+ /**
248
+ * Retorna a url correspondente do `PoSyncSchema` dependendo do tipo da requisição `PoRequestType`.
249
+ *
250
+ * @param {PoSyncSchema} schema **Schema* a ser processado.
251
+ * @param {PoRequestType} requestType Tipo da requisição.
252
+ */
253
+ static getUrl(schema, requestType) {
254
+ return schema[`${requestType}UrlApi`];
255
+ }
256
+ /**
257
+ * Compara se dois objetos são iguais baseado na lista de campos.
258
+ *
259
+ * @param {Array<string>} fields Lista de campos a serem considerados na comparação.
260
+ * @param {any} model1 Objeto 1 a ser comparado.
261
+ * @param {any} model2 Objeto 2 a ser comparado.
262
+ */
263
+ static isModelsEqual(fields, model1, model2) {
264
+ if (fields) {
265
+ return fields.every(field => JSON.stringify(model1[field]) === JSON.stringify(model2[field]));
266
+ }
267
+ }
268
+ /**
269
+ * Retorna uma lista com dois objetos referentes ao registro informado.
270
+ * O primeiro é o registro com os campos que vão para o servidor e o segundo é com os campos locais.
271
+ *
272
+ * @param {PoSyncSchema} schema **Schema* do registro.
273
+ * @param {object} record Registro que será realizada a separação dos campos locais e do servidor.
274
+ */
275
+ static separateSchemaFields(schema, record) {
276
+ const localFields = PoSchemaUtil.getLocalFieldNames(schema);
277
+ const localRecord = {};
278
+ const serverRecord = {};
279
+ Object.keys(record).forEach(field => {
280
+ if (localFields.includes(field)) {
281
+ localRecord[field] = record[field];
282
+ }
283
+ else {
284
+ serverRecord[field] = record[field];
285
+ }
286
+ });
287
+ return { serverRecord, localRecord };
288
+ }
289
+ }
290
+ /** Valor `default` para o campo `lastSync`. */
291
+ PoSchemaUtil.defaultLastSync = new Date(-8640000000000000).toISOString();
292
+ /** Nome da chave do identificador interno do sync. */
293
+ PoSchemaUtil.syncInternalIdFieldName = 'SyncInternalId';
294
+ /** Nome da chave no `storage` para os Schemas. */
436
295
  PoSchemaUtil.syncSchemasName = 'SyncSchemas';
437
296
 
438
- /**
439
- * @docsPrivate
440
- *
441
- * @description
442
- *
443
- * Serviço que disponibiliza métodos que permite operar sobre as definições dos *schemas*.
444
- */
445
- class PoSchemaDefinitionService {
446
- constructor(poStorage) {
447
- this.poStorage = poStorage;
448
- }
449
- /**
450
- * Destrói a chave do *storage* que contém as definições dos *schemas*.
451
- *
452
- * > Para que não venham ocorrer erros em ações que dependam das definições dos *schemas*,
453
- * recomenda-se utilizar o método `prepare()` em seguida.
454
- *
455
- * @returns {Promise<void>} Promessa que é resolvida quando a chave referente as definições dos *schemas* for destruída.
456
- */
457
- destroy() {
458
- return this.poStorage.remove(PoSchemaUtil.syncSchemasName);
459
- }
460
- /**
461
- * Busca um *schema* a partir do nome informado.
462
- *
463
- * @param {string} schemaName Nome do *schema*.
464
- * @returns {Promise<PoSyncSchema>} Promessa que é resolvida quando o *schema* for retornado.
465
- */
466
- get(schemaName) {
467
- return this.poStorage.getItemByField(PoSchemaUtil.syncSchemasName, 'name', schemaName);
468
- }
469
- /**
470
- * Retorna uma promessa com a lista dos *schemas* definidos.
471
- *
472
- * @returns {Promise<Array<PoSyncSchema>>} Promessa que é resolvida quando a lista dos *schemas* definidos for retornada.
473
- */
474
- getAll() {
475
- return this.poStorage.get(PoSchemaUtil.syncSchemasName);
476
- }
477
- /**
478
- * Salva uma lista de *schemas*.
479
- *
480
- * @param {Array<PoSyncSchema>} schemas Lista de schemas que serão salvos.
481
- * @returns {Promise<Array<PoSyncSchema>>} Promessa que é resolvida quando a lista de *schemas* for salva.
482
- */
483
- saveAll(schemas) {
484
- return this.poStorage.set(PoSchemaUtil.syncSchemasName, schemas);
485
- }
486
- /**
487
- * Atualiza um *schema* a partir do *schema name*.
488
- *
489
- * @param {PoSyncSchema} updatedSchema **Schema* que será atualizado.
490
- */
491
- update(updatedSchema) {
492
- return __awaiter(this, void 0, void 0, function* () {
493
- let schemas = yield this.getAll();
494
- const replaceUpdatedSchema = schema => {
495
- if (schema.name === updatedSchema.name) {
496
- return updatedSchema;
497
- }
498
- else {
499
- return schema;
500
- }
501
- };
502
- schemas = schemas.map(replaceUpdatedSchema);
503
- return this.saveAll(schemas);
504
- });
505
- }
506
- }
507
- PoSchemaDefinitionService.decorators = [
508
- { type: Injectable }
509
- ];
510
- PoSchemaDefinitionService.ctorParameters = () => [
511
- { type: PoStorageService }
512
- ];
297
+ /**
298
+ * @docsPrivate
299
+ *
300
+ * @description
301
+ *
302
+ * Serviço que disponibiliza métodos que permite operar sobre as definições dos *schemas*.
303
+ */
304
+ class PoSchemaDefinitionService {
305
+ constructor(poStorage) {
306
+ this.poStorage = poStorage;
307
+ }
308
+ /**
309
+ * Destrói a chave do *storage* que contém as definições dos *schemas*.
310
+ *
311
+ * > Para que não venham ocorrer erros em ações que dependam das definições dos *schemas*,
312
+ * recomenda-se utilizar o método `prepare()` em seguida.
313
+ *
314
+ * @returns {Promise<void>} Promessa que é resolvida quando a chave referente as definições dos *schemas* for destruída.
315
+ */
316
+ destroy() {
317
+ return this.poStorage.remove(PoSchemaUtil.syncSchemasName);
318
+ }
319
+ /**
320
+ * Busca um *schema* a partir do nome informado.
321
+ *
322
+ * @param {string} schemaName Nome do *schema*.
323
+ * @returns {Promise<PoSyncSchema>} Promessa que é resolvida quando o *schema* for retornado.
324
+ */
325
+ get(schemaName) {
326
+ return this.poStorage.getItemByField(PoSchemaUtil.syncSchemasName, 'name', schemaName);
327
+ }
328
+ /**
329
+ * Retorna uma promessa com a lista dos *schemas* definidos.
330
+ *
331
+ * @returns {Promise<Array<PoSyncSchema>>} Promessa que é resolvida quando a lista dos *schemas* definidos for retornada.
332
+ */
333
+ getAll() {
334
+ return this.poStorage.get(PoSchemaUtil.syncSchemasName);
335
+ }
336
+ /**
337
+ * Salva uma lista de *schemas*.
338
+ *
339
+ * @param {Array<PoSyncSchema>} schemas Lista de schemas que serão salvos.
340
+ * @returns {Promise<Array<PoSyncSchema>>} Promessa que é resolvida quando a lista de *schemas* for salva.
341
+ */
342
+ saveAll(schemas) {
343
+ return this.poStorage.set(PoSchemaUtil.syncSchemasName, schemas);
344
+ }
345
+ /**
346
+ * Atualiza um *schema* a partir do *schema name*.
347
+ *
348
+ * @param {PoSyncSchema} updatedSchema **Schema* que será atualizado.
349
+ */
350
+ update(updatedSchema) {
351
+ return __awaiter(this, void 0, void 0, function* () {
352
+ let schemas = yield this.getAll();
353
+ const replaceUpdatedSchema = schema => {
354
+ if (schema.name === updatedSchema.name) {
355
+ return updatedSchema;
356
+ }
357
+ else {
358
+ return schema;
359
+ }
360
+ };
361
+ schemas = schemas.map(replaceUpdatedSchema);
362
+ return this.saveAll(schemas);
363
+ });
364
+ }
365
+ }
366
+ PoSchemaDefinitionService.ɵfac = function PoSchemaDefinitionService_Factory(t) { return new (t || PoSchemaDefinitionService)(i0.ɵɵinject(i1.PoStorageService)); };
367
+ PoSchemaDefinitionService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoSchemaDefinitionService, factory: PoSchemaDefinitionService.ɵfac });
368
+ (function () {
369
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoSchemaDefinitionService, [{
370
+ type: Injectable
371
+ }], function () { return [{ type: i1.PoStorageService }]; }, null);
372
+ })();
513
373
 
514
- /**
515
- * @docsPrivate
516
- *
517
- * @description
518
- *
519
- * Serviço que realiza as operações nos `schemas`.
520
- */
521
- class PoSchemaService {
522
- constructor(poSchemaDefinitionService, poStorage) {
523
- this.poSchemaDefinitionService = poSchemaDefinitionService;
524
- this.poStorage = poStorage;
525
- }
526
- /**
527
- * Retorna o id a partir de uma chave de um *schema*.
528
- *
529
- * @param {string} schemaKey Chave do *schema* em que será realizada a busca do id.
530
- */
531
- static getIdByRecordKey(schemaKey) {
532
- return schemaKey.split(':')[1];
533
- }
534
- /**
535
- * Retorna a chave do *schema* informado.
536
- *
537
- * @param {string} schemaName Nome do *schema*.
538
- * @param {any} recordId Id do registro.
539
- * @param {boolean} isLocalKey Indica se é uma chave local.
540
- */
541
- static getRecordKey(schemaName, recordId, isLocalKey = false) {
542
- return isLocalKey ? `${schemaName}_local:${recordId}` : `${schemaName}:${recordId}`;
543
- }
544
- /**
545
- * Verifica se o dado informado é uma chave de um *schema*.
546
- *
547
- * @param {string} data Dado que será verificado se é uma chave de um *schema*.
548
- * @param {string} schemaName Nome do *schema*.
549
- */
550
- static isSchemaKey(data, schemaName) {
551
- return data ? data.startsWith(`${schemaName}:`) : false;
552
- }
553
- /**
554
- * Cria um novo registro para o *schema* informado.
555
- *
556
- * @param {PoSyncSchema} schema **Schema* em que será criado o registro.
557
- * @param {object} newRecord Registro que será criado.
558
- */
559
- create(schema, newRecord) {
560
- return __awaiter(this, void 0, void 0, function* () {
561
- const id = PoSchemaUtil.getRecordId(newRecord, schema);
562
- return this.save(schema, newRecord, id);
563
- });
564
- }
565
- /**
566
- * Destrói as chaves do *storage* que contém os registros dos *schemas*.
567
- *
568
- * @returns {Promise<void>} Promessa que é resolvida quando as chaves referentes aos *schemas* forem destruídas.
569
- */
570
- destroySchemasRecords() {
571
- return __awaiter(this, void 0, void 0, function* () {
572
- const schemas = yield this.poSchemaDefinitionService.getAll();
573
- const storageKeys = yield this.poStorage.keys();
574
- for (const key of storageKeys) {
575
- const schemaKey = schemas.find(schema => PoSchemaService.isSchemaKey(key, schema.name));
576
- if (schemaKey) {
577
- const id = PoSchemaService.getIdByRecordKey(key);
578
- yield this.remove(schemaKey.name, id);
579
- }
580
- }
581
- });
582
- }
583
- /**
584
- * Retorna o registro referente ao *schema* informado.
585
- *
586
- * @param {string} schemaName Nome do *schema*.
587
- * @param {any} recordId Id do registro.
588
- */
589
- get(schemaName, recordId) {
590
- return __awaiter(this, void 0, void 0, function* () {
591
- const isLocalRecord = true;
592
- const localRecord = yield this.getRecord(schemaName, recordId, isLocalRecord);
593
- const record = yield this.getRecord(schemaName, recordId);
594
- return Object.assign(record, localRecord);
595
- });
596
- }
597
- /**
598
- * Retorna todos os registros referente ao *schema* informado.
599
- *
600
- * @param {string} schemaName Nome do *schema*.
601
- */
602
- getAll(schemaName) {
603
- return __awaiter(this, void 0, void 0, function* () {
604
- const storageKeys = yield this.poStorage.keys();
605
- const schemaRecords = [];
606
- for (const key of storageKeys) {
607
- if (PoSchemaService.isSchemaKey(key, schemaName)) {
608
- const id = PoSchemaService.getIdByRecordKey(key);
609
- schemaRecords.push(yield this.get(schemaName, id));
610
- }
611
- }
612
- return schemaRecords;
613
- });
614
- }
615
- /**
616
- * Aguarda a liberação do recurso limitado, posteriormente o envolve em um comportamento
617
- * de bloqueio e desbloqueio.
618
- *
619
- * @param {Function} limitedResource Função que será envolvida no comportamento de bloqueio e desbloqueio.
620
- */
621
- limitedCallWrap(limitedResource) {
622
- return this.poStorage.limitedCallWrap(limitedResource);
623
- }
624
- /**
625
- * Remove um registro de um *schema* informado.
626
- *
627
- * @param {string} schemaName Nome do *schema*.
628
- * @param {any} recordId Id do registro.
629
- */
630
- remove(schemaName, recordId) {
631
- return __awaiter(this, void 0, void 0, function* () {
632
- const recordKey = PoSchemaService.getRecordKey(schemaName, recordId);
633
- const localRecordKey = PoSchemaService.getRecordKey(schemaName, recordId, true);
634
- yield this.poStorage.remove(recordKey);
635
- yield this.poStorage.remove(localRecordKey);
636
- });
637
- }
638
- /**
639
- * Atualiza um registro de um *schema* informado.
640
- *
641
- * @param {PoSyncSchema} schema **Schema* referente ao registro que será alterado.
642
- * @param {object} record Registro que será atualizado.
643
- * @param {any} recordId Id do registro que deseja ser alterado. Deve ser utilizado em casos em que o id foi alterado.
644
- */
645
- update(schema, record, recordId) {
646
- return __awaiter(this, void 0, void 0, function* () {
647
- const id = PoSchemaUtil.getRecordId(record, schema);
648
- if (recordId) {
649
- record = yield this.updateRecordId(schema.name, record, recordId);
650
- }
651
- return this.save(schema, record, id);
652
- });
653
- }
654
- /**
655
- * Atualiza todos os registros de um *schema*.
656
- *
657
- * @param {PoSyncSchema} schema **Schema* referente aos registros que serão alterados.
658
- * @param {Array<object>} records Lista de registros que serão alterados.
659
- */
660
- updateAll(schema, records) {
661
- return __awaiter(this, void 0, void 0, function* () {
662
- for (const record of records) {
663
- yield this.update(schema, record);
664
- }
665
- });
666
- }
667
- getRecord(schemaName, recordId, isLocalRecord = false) {
668
- return __awaiter(this, void 0, void 0, function* () {
669
- return (yield this.poStorage.get(PoSchemaService.getRecordKey(schemaName, recordId, isLocalRecord))) || {};
670
- });
671
- }
672
- save(schema, record, recordId) {
673
- return __awaiter(this, void 0, void 0, function* () {
674
- const { serverRecord, localRecord } = PoSchemaUtil.separateSchemaFields(schema, record);
675
- const recordKey = PoSchemaService.getRecordKey(schema.name, recordId);
676
- yield this.poStorage.set(recordKey, serverRecord);
677
- yield this.saveLocalFields(schema.name, localRecord, recordId);
678
- return record;
679
- });
680
- }
681
- saveLocalFields(schemaName, localFields, recordId) {
682
- return __awaiter(this, void 0, void 0, function* () {
683
- const containsLocalFields = Object.keys(localFields).length;
684
- if (containsLocalFields) {
685
- const localRecordKey = PoSchemaService.getRecordKey(schemaName, recordId, true);
686
- yield this.poStorage.set(localRecordKey, localFields);
687
- }
688
- });
689
- }
690
- updateRecordId(schemaName, record, recordId) {
691
- return __awaiter(this, void 0, void 0, function* () {
692
- const isLocalRecord = true;
693
- const localRecord = yield this.getRecord(schemaName, recordId, isLocalRecord);
694
- yield this.remove(schemaName, recordId);
695
- return Object.assign(record, localRecord);
696
- });
697
- }
698
- }
699
- PoSchemaService.decorators = [
700
- { type: Injectable }
701
- ];
702
- PoSchemaService.ctorParameters = () => [
703
- { type: PoSchemaDefinitionService },
704
- { type: PoStorageService }
705
- ];
374
+ /**
375
+ * @docsPrivate
376
+ *
377
+ * @description
378
+ *
379
+ * Serviço que realiza as operações nos `schemas`.
380
+ */
381
+ class PoSchemaService {
382
+ constructor(poSchemaDefinitionService, poStorage) {
383
+ this.poSchemaDefinitionService = poSchemaDefinitionService;
384
+ this.poStorage = poStorage;
385
+ }
386
+ /**
387
+ * Retorna o id a partir de uma chave de um *schema*.
388
+ *
389
+ * @param {string} schemaKey Chave do *schema* em que será realizada a busca do id.
390
+ */
391
+ static getIdByRecordKey(schemaKey) {
392
+ return schemaKey.split(':')[1];
393
+ }
394
+ /**
395
+ * Retorna a chave do *schema* informado.
396
+ *
397
+ * @param {string} schemaName Nome do *schema*.
398
+ * @param {any} recordId Id do registro.
399
+ * @param {boolean} isLocalKey Indica se é uma chave local.
400
+ */
401
+ static getRecordKey(schemaName, recordId, isLocalKey = false) {
402
+ return isLocalKey ? `${schemaName}_local:${recordId}` : `${schemaName}:${recordId}`;
403
+ }
404
+ /**
405
+ * Verifica se o dado informado é uma chave de um *schema*.
406
+ *
407
+ * @param {string} data Dado que será verificado se é uma chave de um *schema*.
408
+ * @param {string} schemaName Nome do *schema*.
409
+ */
410
+ static isSchemaKey(data, schemaName) {
411
+ return data ? data.startsWith(`${schemaName}:`) : false;
412
+ }
413
+ /**
414
+ * Cria um novo registro para o *schema* informado.
415
+ *
416
+ * @param {PoSyncSchema} schema **Schema* em que será criado o registro.
417
+ * @param {object} newRecord Registro que será criado.
418
+ */
419
+ create(schema, newRecord) {
420
+ return __awaiter(this, void 0, void 0, function* () {
421
+ const id = PoSchemaUtil.getRecordId(newRecord, schema);
422
+ return this.save(schema, newRecord, id);
423
+ });
424
+ }
425
+ /**
426
+ * Destrói as chaves do *storage* que contém os registros dos *schemas*.
427
+ *
428
+ * @returns {Promise<void>} Promessa que é resolvida quando as chaves referentes aos *schemas* forem destruídas.
429
+ */
430
+ destroySchemasRecords() {
431
+ return __awaiter(this, void 0, void 0, function* () {
432
+ const schemas = yield this.poSchemaDefinitionService.getAll();
433
+ const storageKeys = yield this.poStorage.keys();
434
+ for (const key of storageKeys) {
435
+ const schemaKey = schemas.find(schema => PoSchemaService.isSchemaKey(key, schema.name));
436
+ if (schemaKey) {
437
+ const id = PoSchemaService.getIdByRecordKey(key);
438
+ yield this.remove(schemaKey.name, id);
439
+ }
440
+ }
441
+ });
442
+ }
443
+ /**
444
+ * Retorna o registro referente ao *schema* informado.
445
+ *
446
+ * @param {string} schemaName Nome do *schema*.
447
+ * @param {any} recordId Id do registro.
448
+ */
449
+ get(schemaName, recordId) {
450
+ return __awaiter(this, void 0, void 0, function* () {
451
+ const isLocalRecord = true;
452
+ const localRecord = yield this.getRecord(schemaName, recordId, isLocalRecord);
453
+ const record = yield this.getRecord(schemaName, recordId);
454
+ return Object.assign(record, localRecord);
455
+ });
456
+ }
457
+ /**
458
+ * Retorna todos os registros referente ao *schema* informado.
459
+ *
460
+ * @param {string} schemaName Nome do *schema*.
461
+ */
462
+ getAll(schemaName) {
463
+ return __awaiter(this, void 0, void 0, function* () {
464
+ const storageKeys = yield this.poStorage.keys();
465
+ const schemaRecords = [];
466
+ for (const key of storageKeys) {
467
+ if (PoSchemaService.isSchemaKey(key, schemaName)) {
468
+ const id = PoSchemaService.getIdByRecordKey(key);
469
+ schemaRecords.push(yield this.get(schemaName, id));
470
+ }
471
+ }
472
+ return schemaRecords;
473
+ });
474
+ }
475
+ /**
476
+ * Aguarda a liberação do recurso limitado, posteriormente o envolve em um comportamento
477
+ * de bloqueio e desbloqueio.
478
+ *
479
+ * @param {Function} limitedResource Função que será envolvida no comportamento de bloqueio e desbloqueio.
480
+ */
481
+ limitedCallWrap(limitedResource) {
482
+ return this.poStorage.limitedCallWrap(limitedResource);
483
+ }
484
+ /**
485
+ * Remove um registro de um *schema* informado.
486
+ *
487
+ * @param {string} schemaName Nome do *schema*.
488
+ * @param {any} recordId Id do registro.
489
+ */
490
+ remove(schemaName, recordId) {
491
+ return __awaiter(this, void 0, void 0, function* () {
492
+ const recordKey = PoSchemaService.getRecordKey(schemaName, recordId);
493
+ const localRecordKey = PoSchemaService.getRecordKey(schemaName, recordId, true);
494
+ yield this.poStorage.remove(recordKey);
495
+ yield this.poStorage.remove(localRecordKey);
496
+ });
497
+ }
498
+ /**
499
+ * Atualiza um registro de um *schema* informado.
500
+ *
501
+ * @param {PoSyncSchema} schema **Schema* referente ao registro que será alterado.
502
+ * @param {object} record Registro que será atualizado.
503
+ * @param {any} recordId Id do registro que deseja ser alterado. Deve ser utilizado em casos em que o id foi alterado.
504
+ */
505
+ update(schema, record, recordId) {
506
+ return __awaiter(this, void 0, void 0, function* () {
507
+ const id = PoSchemaUtil.getRecordId(record, schema);
508
+ if (recordId) {
509
+ record = yield this.updateRecordId(schema.name, record, recordId);
510
+ }
511
+ return this.save(schema, record, id);
512
+ });
513
+ }
514
+ /**
515
+ * Atualiza todos os registros de um *schema*.
516
+ *
517
+ * @param {PoSyncSchema} schema **Schema* referente aos registros que serão alterados.
518
+ * @param {Array<object>} records Lista de registros que serão alterados.
519
+ */
520
+ updateAll(schema, records) {
521
+ return __awaiter(this, void 0, void 0, function* () {
522
+ for (const record of records) {
523
+ yield this.update(schema, record);
524
+ }
525
+ });
526
+ }
527
+ getRecord(schemaName, recordId, isLocalRecord = false) {
528
+ return __awaiter(this, void 0, void 0, function* () {
529
+ return (yield this.poStorage.get(PoSchemaService.getRecordKey(schemaName, recordId, isLocalRecord))) || {};
530
+ });
531
+ }
532
+ save(schema, record, recordId) {
533
+ return __awaiter(this, void 0, void 0, function* () {
534
+ const { serverRecord, localRecord } = PoSchemaUtil.separateSchemaFields(schema, record);
535
+ const recordKey = PoSchemaService.getRecordKey(schema.name, recordId);
536
+ yield this.poStorage.set(recordKey, serverRecord);
537
+ yield this.saveLocalFields(schema.name, localRecord, recordId);
538
+ return record;
539
+ });
540
+ }
541
+ saveLocalFields(schemaName, localFields, recordId) {
542
+ return __awaiter(this, void 0, void 0, function* () {
543
+ const containsLocalFields = Object.keys(localFields).length;
544
+ if (containsLocalFields) {
545
+ const localRecordKey = PoSchemaService.getRecordKey(schemaName, recordId, true);
546
+ yield this.poStorage.set(localRecordKey, localFields);
547
+ }
548
+ });
549
+ }
550
+ updateRecordId(schemaName, record, recordId) {
551
+ return __awaiter(this, void 0, void 0, function* () {
552
+ const isLocalRecord = true;
553
+ const localRecord = yield this.getRecord(schemaName, recordId, isLocalRecord);
554
+ yield this.remove(schemaName, recordId);
555
+ return Object.assign(record, localRecord);
556
+ });
557
+ }
558
+ }
559
+ PoSchemaService.ɵfac = function PoSchemaService_Factory(t) { return new (t || PoSchemaService)(i0.ɵɵinject(PoSchemaDefinitionService), i0.ɵɵinject(i1.PoStorageService)); };
560
+ PoSchemaService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoSchemaService, factory: PoSchemaService.ɵfac });
561
+ (function () {
562
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoSchemaService, [{
563
+ type: Injectable
564
+ }], function () { return [{ type: PoSchemaDefinitionService }, { type: i1.PoStorageService }]; }, null);
565
+ })();
706
566
 
707
- class PoEventSourcingService {
708
- constructor(poSchemaDefinition, poSchemaService, poStorage, poHttpClient) {
709
- this.poSchemaDefinition = poSchemaDefinition;
710
- this.poSchemaService = poSchemaService;
711
- this.poStorage = poStorage;
712
- this.poHttpClient = poHttpClient;
713
- this.stoppedQueueEventSourcing = false;
714
- this.responseSubject = new Subject();
715
- this.schemasSyncConfig = {};
716
- }
717
- static getUrl(eventSourcingItem, schema, requestType) {
718
- const schemaUrl = PoSchemaUtil.getUrl(schema, requestType);
719
- const schemaId = eventSourcingItem.record[schema.idField];
720
- if (requestType === PoRequestType.GET) {
721
- return schemaUrl;
722
- }
723
- if ([PoRequestType.DELETE, PoRequestType.PATCH].includes(requestType)) {
724
- return schemaUrl ? `${schemaUrl}/${schemaId}` : `${PoSchemaUtil.getUrl(schema, PoRequestType.GET)}/${schemaId}`;
725
- }
726
- if (requestType === PoRequestType.POST) {
727
- return schemaUrl ? schemaUrl : PoSchemaUtil.getUrl(schema, PoRequestType.GET);
728
- }
729
- }
730
- create(schemaName, newItem, customRequestId) {
731
- const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Insert, newItem, schemaName, customRequestId);
732
- return this.insertEventSourcingQueue(eventSourcingItem);
733
- }
734
- createBatchEvents(schemaName, eventList) {
735
- return __awaiter(this, void 0, void 0, function* () {
736
- const eventSourcingList = this.createEventSourcingList(schemaName, eventList);
737
- yield this.poStorage.appendArrayToArray(PoEventSourcingService.event_sourcing_name, eventSourcingList);
738
- this.notifyEventCreation();
739
- });
740
- }
741
- /**
742
- * Destrói a chave do *storage* que contém a fila de dados que estão esperando para serem enviados ao
743
- * servidor *(EventSourcing)*.
744
- *
745
- * @returns {Promise<void>} Promessa que é resolvida quando a chave referente a fila de *EventSourcing* for destruída.
746
- */
747
- destroyEventSourcingQueue() {
748
- return this.poStorage.remove(PoEventSourcingService.event_sourcing_name);
749
- }
750
- httpCommand(httpOperationData, customRequestId) {
751
- return __awaiter(this, void 0, void 0, function* () {
752
- httpOperationData = yield this.serializeBody(httpOperationData);
753
- const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Http, httpOperationData, undefined, customRequestId);
754
- yield this.insertEventSourcingQueue(eventSourcingItem);
755
- return eventSourcingItem.id;
756
- });
757
- }
758
- responsesSubject() {
759
- return this.responseSubject.asObservable();
760
- }
761
- onSaveData() {
762
- if (!this.eventSub) {
763
- this.eventSub = Observable.create(subscriber => (this.emitter = subscriber));
764
- }
765
- return this.eventSub;
766
- }
767
- remove(schemaName, itemToDelete, customRequestId) {
768
- const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Delete, itemToDelete, schemaName, customRequestId);
769
- return this.insertEventSourcingQueue(eventSourcingItem);
770
- }
771
- removeEventSourcingItem(idEventSourcingItem) {
772
- return this.poStorage.removeItemFromArray(PoEventSourcingService.event_sourcing_name, 'id', idEventSourcingItem);
773
- }
774
- syncGet() {
775
- const syncGetFunction = () => __awaiter(this, void 0, void 0, function* () {
776
- return this.poSchemaDefinition.getAll().then(schemas => {
777
- const schemaPromises = this.updateStorageSchemas(schemas);
778
- return Promise.all(schemaPromises);
779
- });
780
- });
781
- return this.poSchemaService.limitedCallWrap(syncGetFunction);
782
- }
783
- syncSend() {
784
- return __awaiter(this, void 0, void 0, function* () {
785
- const syncSendFunction = () => __awaiter(this, void 0, void 0, function* () {
786
- const itemOfQueue = yield this.poStorage.getFirstItem(PoEventSourcingService.event_sourcing_name);
787
- if (itemOfQueue) {
788
- yield this.selectOperation(itemOfQueue);
789
- }
790
- if (this.stoppedQueueEventSourcing || !itemOfQueue) {
791
- this.stoppedQueueEventSourcing = false;
792
- return Promise.resolve();
793
- }
794
- return syncSendFunction();
795
- });
796
- return this.poSchemaService.limitedCallWrap(syncSendFunction);
797
- });
798
- }
799
- update(schemaName, itemUpdated, customRequestId) {
800
- const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Update, itemUpdated, schemaName, customRequestId);
801
- return this.insertEventSourcingQueue(eventSourcingItem);
802
- }
803
- /* Avalia se o body é do tipo File e se for converte para base64 */
804
- serializeBody(requestData) {
805
- return __awaiter(this, void 0, void 0, function* () {
806
- let { body, mimeType, bodyType, fileName } = requestData;
807
- if (body instanceof File) {
808
- bodyType = 'File';
809
- mimeType = body.type;
810
- fileName = body.name;
811
- body = yield toBase64(body);
812
- }
813
- return Object.assign(Object.assign({}, requestData), { body, mimeType, bodyType, fileName });
814
- });
815
- }
816
- buildUrlParams(schema, baseUrl, pageNumber) {
817
- const params = [];
818
- params.push(`${this.config.dataTransform.getPageSizeParamName()}=${schema.pageSize}`);
819
- params.push(`${this.config.dataTransform.getPageParamName()}=${pageNumber}`);
820
- return `${baseUrl}?${params.join('&')}`;
821
- }
822
- checkRecordIdExists(recordId, operation) {
823
- if (!recordId) {
824
- const error = {
825
- message: 'Identifier not defined',
826
- operation: operation
827
- };
828
- throw new PoEventSourcingErrorResponse(error);
829
- }
830
- }
831
- concatPageItems(pageAcumulator, requestBody) {
832
- if (requestBody[this.config.dataTransform.getItemsFieldName()]) {
833
- pageAcumulator.data = [...pageAcumulator.data, ...requestBody[this.config.dataTransform.getItemsFieldName()]];
834
- }
835
- return pageAcumulator;
836
- }
837
- createEventSourcingItem(operation, newItem, schemaName, customRequestId, id) {
838
- if (!schemaName && operation !== PoEventSourcingOperation.Http) {
839
- throw new Error('PoSyncSchema is not defined.');
840
- }
841
- return {
842
- id: id ? id : new Date().getTime(),
843
- dateTime: new Date().getTime(),
844
- schema: schemaName,
845
- operation: operation,
846
- record: newItem,
847
- customRequestId: customRequestId
848
- };
849
- }
850
- createEventSourcingList(schemaName, eventList) {
851
- return eventList.map((eventItem, index) => {
852
- const id = new Date().getTime() + index;
853
- return this.createEventSourcingItem(eventItem.operation, eventItem.record, schemaName, eventItem.customRequestId, id);
854
- });
855
- }
856
- createSchemaSyncConfig(schemaName) {
857
- this.schemasSyncConfig[schemaName] = {
858
- page: undefined,
859
- currentUrlDiff: undefined,
860
- responseDate: undefined
861
- };
862
- }
863
- deleteOperation(eventSourcingItem) {
864
- return __awaiter(this, void 0, void 0, function* () {
865
- try {
866
- const schema = yield this.poSchemaDefinition.get(eventSourcingItem.schema);
867
- const recordId = eventSourcingItem.record[schema.idField];
868
- this.checkRecordIdExists(recordId, PoEventSourcingOperation.Delete);
869
- const url = PoEventSourcingService.getUrl(eventSourcingItem, schema, PoRequestType.DELETE);
870
- const response = yield this.sendServerItem(url, PoHttpRequestType.DELETE);
871
- yield this.removeEventSourcingValidItem(response.status, eventSourcingItem);
872
- return yield this.sendResponseSubject(eventSourcingItem, response);
873
- }
874
- catch (errorResponse) {
875
- return this.sendResponseSubject(eventSourcingItem, errorResponse, true);
876
- }
877
- });
878
- }
879
- diffServerItems(currentUrlDiff) {
880
- return this.poHttpClient.get(currentUrlDiff);
881
- }
882
- getBodyAndDate(schemaName, response) {
883
- const getDateFieldName = this.config.dataTransform.getDateFieldName();
884
- const responseSyncDate = response.body[getDateFieldName];
885
- this.schemasSyncConfig[schemaName]['responseDate'] = responseSyncDate;
886
- return response.body;
887
- }
888
- getServerDiffRecords(schema, baseUrl) {
889
- return __awaiter(this, void 0, void 0, function* () {
890
- const initialAcumulatorPage = { entity: schema.name, data: [] };
891
- const diffUrl = this.schemasSyncConfig[schema.name]['currentUrlDiff'];
892
- const serverResponse = yield this.diffServerItems(diffUrl)
893
- .pipe(map(response => this.getBodyAndDate(schema.name, response)), expand(data => this.paginateSchemaData(data, schema, baseUrl)), reduce((pageAcumulator, requestBody) => this.concatPageItems(pageAcumulator, requestBody), initialAcumulatorPage))
894
- .toPromise();
895
- return serverResponse.data;
896
- });
897
- }
898
- httpOperation(eventSourcingItem) {
899
- return __awaiter(this, void 0, void 0, function* () {
900
- try {
901
- const requestData = yield this.createPoHttpRequestData(eventSourcingItem.record.url, eventSourcingItem.record.method, eventSourcingItem.record, eventSourcingItem.record.headers);
902
- const response = yield this.poHttpClient.createRequest(requestData).toPromise();
903
- const poHttpCommandResponse = {
904
- id: eventSourcingItem.id,
905
- customRequestId: eventSourcingItem.customRequestId,
906
- request: eventSourcingItem.record,
907
- response: response
908
- };
909
- this.responseSubject.next(poHttpCommandResponse);
910
- return this.removeEventSourcingValidItem(response.status, eventSourcingItem);
911
- }
912
- catch (errorHttpClient) {
913
- return this.sendResponseSubject(eventSourcingItem, errorHttpClient, true);
914
- }
915
- });
916
- }
917
- insertEventSourcingQueue(eventSourcingItem) {
918
- return __awaiter(this, void 0, void 0, function* () {
919
- const eventSourcingUpdatedQueue = yield this.poStorage.appendItemToArray(PoEventSourcingService.event_sourcing_name, eventSourcingItem);
920
- this.notifyEventCreation();
921
- return Promise.resolve(eventSourcingUpdatedQueue);
922
- });
923
- }
924
- insertOperation(currentEventSourcingItem) {
925
- return __awaiter(this, void 0, void 0, function* () {
926
- const schema = yield this.poSchemaDefinition.get(currentEventSourcingItem.schema);
927
- const url = PoEventSourcingService.getUrl(currentEventSourcingItem, schema, PoRequestType.POST);
928
- try {
929
- const response = yield this.sendServerItem(url, PoHttpRequestType.POST, currentEventSourcingItem.record);
930
- const recordUpdatedByServer = response.body;
931
- yield this.removeEventSourcingValidItem(response.status, currentEventSourcingItem);
932
- const id = currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName];
933
- yield this.poSchemaService.update(schema, recordUpdatedByServer, id);
934
- const eventSourcingItems = yield this.poStorage.get(PoEventSourcingService.event_sourcing_name);
935
- yield this.updatePendingEventSourcing(currentEventSourcingItem, schema.idField, recordUpdatedByServer, eventSourcingItems);
936
- return this.sendResponseSubject(currentEventSourcingItem, response);
937
- }
938
- catch (errorHttpClient) {
939
- return this.sendResponseSubject(currentEventSourcingItem, errorHttpClient, true);
940
- }
941
- });
942
- }
943
- isValidStatus(status) {
944
- return PoEventSourcingService.VALID_HTTP_STATUS_CODES.includes(status);
945
- }
946
- notifyEventCreation() {
947
- if (this.emitter) {
948
- this.emitter.next();
949
- }
950
- }
951
- paginateSchemaData(data, schema, baseUrl) {
952
- this.config.dataTransform.transform(data);
953
- if (this.config.dataTransform.hasNext()) {
954
- this.schemasSyncConfig[schema.name]['currentUrlDiff'] = this.buildUrlParams(schema, baseUrl, ++this.schemasSyncConfig[schema.name]['page']);
955
- return this.diffServerItems(this.schemasSyncConfig[schema.name]['currentUrlDiff']).pipe(map(response => this.getBodyAndDate(schema.name, response)));
956
- }
957
- return of();
958
- }
959
- removeEventSourcingValidItem(status, eventSourcingItem) {
960
- if (this.isValidStatus(status) || eventSourcingItem.operation === PoEventSourcingOperation.Http) {
961
- return this.removeEventSourcingItem(eventSourcingItem.id);
962
- }
963
- }
964
- selectOperation(eventSourcingItem) {
965
- switch (eventSourcingItem.operation) {
966
- case PoEventSourcingOperation.Insert:
967
- return this.insertOperation(eventSourcingItem);
968
- case PoEventSourcingOperation.Update:
969
- return this.updateOperation(eventSourcingItem);
970
- case PoEventSourcingOperation.Delete:
971
- return this.deleteOperation(eventSourcingItem);
972
- case PoEventSourcingOperation.Http:
973
- return this.httpOperation(eventSourcingItem);
974
- }
975
- }
976
- sendResponseSubject(eventSourcingItem, response, isSubjectError = false) {
977
- const poSyncResponse = {
978
- id: eventSourcingItem.id,
979
- customRequestId: eventSourcingItem.customRequestId,
980
- request: eventSourcingItem.record,
981
- response: response
982
- };
983
- this.stoppedQueueEventSourcing = isSubjectError;
984
- this.responseSubject.next(poSyncResponse);
985
- return Promise.resolve();
986
- }
987
- sendServerItem(url, method, body) {
988
- return __awaiter(this, void 0, void 0, function* () {
989
- const requestData = yield this.createPoHttpRequestData(url, method, body);
990
- return this.poHttpClient.createRequest(requestData).toPromise();
991
- });
992
- }
993
- createPoHttpRequestData(url, method, record, headers) {
994
- var _a;
995
- return __awaiter(this, void 0, void 0, function* () {
996
- let body = (_a = record.body) !== null && _a !== void 0 ? _a : record;
997
- if (record.bodyType === 'File') {
998
- body = yield this.createFormData(body, record.fileName, record.mimeType, record.formField);
999
- }
1000
- return { url, method, body, headers };
1001
- });
1002
- }
1003
- createFormData(body, fileName, mimeType, formField = 'file') {
1004
- return __awaiter(this, void 0, void 0, function* () {
1005
- const file = yield toFile(body, fileName, mimeType);
1006
- const formData = new FormData();
1007
- formData.append(formField, file, fileName);
1008
- return formData;
1009
- });
1010
- }
1011
- updateOperation(eventSourcingItem) {
1012
- return __awaiter(this, void 0, void 0, function* () {
1013
- const schema = yield this.poSchemaDefinition.get(eventSourcingItem.schema);
1014
- const url = PoEventSourcingService.getUrl(eventSourcingItem, schema, PoRequestType.PATCH);
1015
- try {
1016
- const recordId = eventSourcingItem.record[schema.idField];
1017
- this.checkRecordIdExists(recordId, PoEventSourcingOperation.Update);
1018
- const response = yield this.sendServerItem(url, PoHttpRequestType.PUT, eventSourcingItem.record);
1019
- yield this.removeEventSourcingValidItem(response.status, eventSourcingItem);
1020
- return yield this.sendResponseSubject(eventSourcingItem, response);
1021
- }
1022
- catch (errorHttpClient) {
1023
- return this.sendResponseSubject(eventSourcingItem, errorHttpClient, true);
1024
- }
1025
- });
1026
- }
1027
- updatePendingEventSourcing(currentEventSourcingItem, idFieldSchema, inserted, eventSourcingItems) {
1028
- if (currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName]) {
1029
- eventSourcingItems.forEach((eventSourcingItem, position) => {
1030
- const isCurrentEventSourcingItem = !eventSourcingItem.record[idFieldSchema] &&
1031
- eventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName] ===
1032
- currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName];
1033
- if (isCurrentEventSourcingItem) {
1034
- eventSourcingItems[position].record[idFieldSchema] = inserted[idFieldSchema];
1035
- }
1036
- });
1037
- return this.poStorage.set(PoEventSourcingService.event_sourcing_name, eventSourcingItems);
1038
- }
1039
- else {
1040
- return Promise.resolve();
1041
- }
1042
- }
1043
- updateRecords(serverRecords, schema) {
1044
- return __awaiter(this, void 0, void 0, function* () {
1045
- for (const serverRecord of serverRecords) {
1046
- yield this.updateRecordByServerRecord(serverRecord, schema);
1047
- }
1048
- });
1049
- }
1050
- updateRecordByServerRecord(serverRecord, schema) {
1051
- return __awaiter(this, void 0, void 0, function* () {
1052
- const recordId = serverRecord[schema.idField];
1053
- const storageRecord = yield this.poSchemaService.get(schema.name, recordId);
1054
- const existsStorageRecord = !!Object.keys(storageRecord).length;
1055
- if (existsStorageRecord && serverRecord[schema.deletedField]) {
1056
- return yield this.poSchemaService.remove(schema.name, serverRecord[schema.idField]);
1057
- }
1058
- if (existsStorageRecord && !serverRecord[schema.deletedField]) {
1059
- return yield this.poSchemaService.update(schema, serverRecord);
1060
- }
1061
- if (!existsStorageRecord && !serverRecord[schema.deletedField]) {
1062
- return yield this.poSchemaService.create(schema, serverRecord);
1063
- }
1064
- });
1065
- }
1066
- updateStorageBySchema(schema) {
1067
- return __awaiter(this, void 0, void 0, function* () {
1068
- this.createSchemaSyncConfig(schema.name);
1069
- this.schemasSyncConfig[schema.name]['page'] = 1;
1070
- const baseUrl = `${PoSchemaUtil.getUrl(schema, PoRequestType.DIFF)}/${schema.lastSync}`;
1071
- this.schemasSyncConfig[schema.name]['currentUrlDiff'] = this.buildUrlParams(schema, baseUrl, this.schemasSyncConfig[schema.name]['page']);
1072
- const serverRecords = yield this.getServerDiffRecords(schema, baseUrl);
1073
- yield this.updateRecords(serverRecords, schema);
1074
- schema.lastSync = this.schemasSyncConfig[schema.name]['responseDate'];
1075
- yield this.poSchemaDefinition.update(schema);
1076
- });
1077
- }
1078
- updateStorageSchemas(schemas) {
1079
- return schemas.map((schema) => this.updateStorageBySchema(schema));
1080
- }
1081
- }
1082
- PoEventSourcingService.event_sourcing_name = 'EventSourcing';
1083
- PoEventSourcingService.VALID_HTTP_STATUS_CODES = [
1084
- HttpStatus.OK,
1085
- HttpStatus.CREATED,
1086
- HttpStatus.ACCEPTED,
1087
- HttpStatus.NON_AUTHORITATIVE_INFORMATION,
1088
- HttpStatus.NO_CONTENT,
1089
- HttpStatus.RESET_CONTENT,
1090
- HttpStatus.PARTIAL_CONTENT,
1091
- HttpStatus.MULTI_STATUS // 207
1092
- ];
1093
- PoEventSourcingService.decorators = [
1094
- { type: Injectable }
1095
- ];
1096
- PoEventSourcingService.ctorParameters = () => [
1097
- { type: PoSchemaDefinitionService },
1098
- { type: PoSchemaService },
1099
- { type: PoStorageService },
1100
- { type: PoHttpClientService }
567
+ /**
568
+ * @docsPrivate
569
+ *
570
+ * @description
571
+ *
572
+ * Serviço para execução de requisições HTTP.
573
+ */
574
+ class PoHttpClientService {
575
+ constructor(httpClient) {
576
+ this.httpClient = httpClient;
577
+ }
578
+ /**
579
+ * Constrói uma requisição HTTP personalizada.
580
+ *
581
+ * @param {PoHttpRequestData} poHttpOperationData Parâmetros para a construção
582
+ * da requisição.
583
+ */
584
+ createRequest(poHttpOperationData) {
585
+ const httpHeaders = this.createHttpHeaders(poHttpOperationData.headers);
586
+ return this.httpClient.request(poHttpOperationData.method, poHttpOperationData.url, {
587
+ observe: 'response',
588
+ headers: httpHeaders,
589
+ body: poHttpOperationData.body
590
+ });
591
+ }
592
+ /**
593
+ * Constrói uma requisição com o método `delete`.
594
+ *
595
+ * @param {string} url URL da requisição.
596
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
597
+ */
598
+ delete(url, httpHeaders) {
599
+ const requestData = {
600
+ url: url,
601
+ method: PoHttpRequestType.DELETE,
602
+ headers: httpHeaders
603
+ };
604
+ return this.createRequest(requestData);
605
+ }
606
+ /**
607
+ * Constrói uma requisição com o método `get`.
608
+ *
609
+ * @param {string} url URL da requisição.
610
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
611
+ */
612
+ get(url, httpHeaders) {
613
+ const requestData = {
614
+ url: url,
615
+ method: PoHttpRequestType.GET,
616
+ headers: httpHeaders
617
+ };
618
+ return this.createRequest(requestData);
619
+ }
620
+ /**
621
+ * Constrói uma requisição com o método `head`.
622
+ *
623
+ * @param {string} url URL da requisição.
624
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
625
+ */
626
+ head(url, httpHeaders) {
627
+ const requestData = {
628
+ url: url,
629
+ method: PoHttpRequestType.HEAD,
630
+ headers: httpHeaders
631
+ };
632
+ return this.createRequest(requestData);
633
+ }
634
+ /**
635
+ * Constrói uma requisição com o método `options`.
636
+ *
637
+ * @param {string} url URL da requisição.
638
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
639
+ */
640
+ options(url, httpHeaders) {
641
+ const requestData = {
642
+ url: url,
643
+ method: PoHttpRequestType.OPTIONS,
644
+ headers: httpHeaders
645
+ };
646
+ return this.createRequest(requestData);
647
+ }
648
+ /**
649
+ * Constrói uma requisição com o método `patch`.
650
+ *
651
+ * @param {string} url URL da requisição.
652
+ * @param {any} body Corpo da requisição.
653
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
654
+ */
655
+ patch(url, body, httpHeaders) {
656
+ const requestData = {
657
+ url: url,
658
+ method: PoHttpRequestType.PATCH,
659
+ headers: httpHeaders,
660
+ body: body
661
+ };
662
+ return this.createRequest(requestData);
663
+ }
664
+ /**
665
+ * Constrói uma requisição com o método `post`.
666
+ *
667
+ * @param {string} url URL da requisição.
668
+ * @param {any} body Corpo da requisição.
669
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
670
+ */
671
+ post(url, body, httpHeaders) {
672
+ const requestData = {
673
+ url: url,
674
+ method: PoHttpRequestType.POST,
675
+ headers: httpHeaders,
676
+ body: body
677
+ };
678
+ return this.createRequest(requestData);
679
+ }
680
+ /**
681
+ * Constrói uma requisição com o método `put`.
682
+ *
683
+ * @param {string} url URL da requisição.
684
+ * @param {any} body Corpo da requisição.
685
+ * @param {Array<PoHeaderOption>} httpHeaders Cabeçalhos da requisição.
686
+ */
687
+ put(url, body, httpHeaders) {
688
+ const requestData = {
689
+ url: url,
690
+ method: PoHttpRequestType.PUT,
691
+ headers: httpHeaders,
692
+ body: body
693
+ };
694
+ return this.createRequest(requestData);
695
+ }
696
+ createHttpHeaders(poHttpOperationHeaders) {
697
+ let httpHeaders = new HttpHeaders();
698
+ if (poHttpOperationHeaders && poHttpOperationHeaders.length > 0) {
699
+ poHttpOperationHeaders.forEach(poHttpHeader => (httpHeaders = httpHeaders.append(poHttpHeader.name, poHttpHeader.value)));
700
+ }
701
+ return httpHeaders;
702
+ }
703
+ }
704
+ PoHttpClientService.ɵfac = function PoHttpClientService_Factory(t) { return new (t || PoHttpClientService)(i0.ɵɵinject(i1$1.HttpClient)); };
705
+ PoHttpClientService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoHttpClientService, factory: PoHttpClientService.ɵfac });
706
+ (function () {
707
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoHttpClientService, [{
708
+ type: Injectable
709
+ }], function () { return [{ type: i1$1.HttpClient }]; }, null);
710
+ })();
711
+
712
+ class PoEventSourcingService {
713
+ constructor(poSchemaDefinition, poSchemaService, poStorage, poHttpClient) {
714
+ this.poSchemaDefinition = poSchemaDefinition;
715
+ this.poSchemaService = poSchemaService;
716
+ this.poStorage = poStorage;
717
+ this.poHttpClient = poHttpClient;
718
+ this.stoppedQueueEventSourcing = false;
719
+ this.responseSubject = new Subject();
720
+ this.schemasSyncConfig = {};
721
+ }
722
+ static getUrl(eventSourcingItem, schema, requestType) {
723
+ const schemaUrl = PoSchemaUtil.getUrl(schema, requestType);
724
+ const schemaId = eventSourcingItem.record[schema.idField];
725
+ if (requestType === PoRequestType.GET) {
726
+ return schemaUrl;
727
+ }
728
+ if ([PoRequestType.DELETE, PoRequestType.PATCH].includes(requestType)) {
729
+ return schemaUrl ? `${schemaUrl}/${schemaId}` : `${PoSchemaUtil.getUrl(schema, PoRequestType.GET)}/${schemaId}`;
730
+ }
731
+ if (requestType === PoRequestType.POST) {
732
+ return schemaUrl ? schemaUrl : PoSchemaUtil.getUrl(schema, PoRequestType.GET);
733
+ }
734
+ }
735
+ create(schemaName, newItem, customRequestId) {
736
+ const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Insert, newItem, schemaName, customRequestId);
737
+ return this.insertEventSourcingQueue(eventSourcingItem);
738
+ }
739
+ createBatchEvents(schemaName, eventList) {
740
+ return __awaiter(this, void 0, void 0, function* () {
741
+ const eventSourcingList = this.createEventSourcingList(schemaName, eventList);
742
+ yield this.poStorage.appendArrayToArray(PoEventSourcingService.event_sourcing_name, eventSourcingList);
743
+ this.notifyEventCreation();
744
+ });
745
+ }
746
+ /**
747
+ * Destrói a chave do *storage* que contém a fila de dados que estão esperando para serem enviados ao
748
+ * servidor *(EventSourcing)*.
749
+ *
750
+ * @returns {Promise<void>} Promessa que é resolvida quando a chave referente a fila de *EventSourcing* for destruída.
751
+ */
752
+ destroyEventSourcingQueue() {
753
+ return this.poStorage.remove(PoEventSourcingService.event_sourcing_name);
754
+ }
755
+ httpCommand(httpOperationData, customRequestId) {
756
+ return __awaiter(this, void 0, void 0, function* () {
757
+ httpOperationData = yield this.serializeBody(httpOperationData);
758
+ const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Http, httpOperationData, undefined, customRequestId);
759
+ yield this.insertEventSourcingQueue(eventSourcingItem);
760
+ return eventSourcingItem.id;
761
+ });
762
+ }
763
+ responsesSubject() {
764
+ return this.responseSubject.asObservable();
765
+ }
766
+ onSaveData() {
767
+ if (!this.eventSub) {
768
+ this.eventSub = Observable.create(subscriber => (this.emitter = subscriber));
769
+ }
770
+ return this.eventSub;
771
+ }
772
+ remove(schemaName, itemToDelete, customRequestId) {
773
+ const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Delete, itemToDelete, schemaName, customRequestId);
774
+ return this.insertEventSourcingQueue(eventSourcingItem);
775
+ }
776
+ removeEventSourcingItem(idEventSourcingItem) {
777
+ return this.poStorage.removeItemFromArray(PoEventSourcingService.event_sourcing_name, 'id', idEventSourcingItem);
778
+ }
779
+ syncGet() {
780
+ const syncGetFunction = () => __awaiter(this, void 0, void 0, function* () {
781
+ return this.poSchemaDefinition.getAll().then(schemas => {
782
+ const schemaPromises = this.updateStorageSchemas(schemas);
783
+ return Promise.all(schemaPromises);
784
+ });
785
+ });
786
+ return this.poSchemaService.limitedCallWrap(syncGetFunction);
787
+ }
788
+ syncSend() {
789
+ return __awaiter(this, void 0, void 0, function* () {
790
+ const syncSendFunction = () => __awaiter(this, void 0, void 0, function* () {
791
+ const itemOfQueue = yield this.poStorage.getFirstItem(PoEventSourcingService.event_sourcing_name);
792
+ if (itemOfQueue) {
793
+ yield this.selectOperation(itemOfQueue);
794
+ }
795
+ if (this.stoppedQueueEventSourcing || !itemOfQueue) {
796
+ this.stoppedQueueEventSourcing = false;
797
+ return Promise.resolve();
798
+ }
799
+ return syncSendFunction();
800
+ });
801
+ return this.poSchemaService.limitedCallWrap(syncSendFunction);
802
+ });
803
+ }
804
+ update(schemaName, itemUpdated, customRequestId) {
805
+ const eventSourcingItem = this.createEventSourcingItem(PoEventSourcingOperation.Update, itemUpdated, schemaName, customRequestId);
806
+ return this.insertEventSourcingQueue(eventSourcingItem);
807
+ }
808
+ /* Avalia se o body é do tipo File e se for converte para base64 */
809
+ serializeBody(requestData) {
810
+ return __awaiter(this, void 0, void 0, function* () {
811
+ let { body, mimeType, bodyType, fileName } = requestData;
812
+ if (body instanceof File) {
813
+ bodyType = 'File';
814
+ mimeType = body.type;
815
+ fileName = body.name;
816
+ body = yield toBase64(body);
817
+ }
818
+ return Object.assign(Object.assign({}, requestData), { body, mimeType, bodyType, fileName });
819
+ });
820
+ }
821
+ buildUrlParams(schema, baseUrl, pageNumber) {
822
+ const params = [];
823
+ params.push(`${this.config.dataTransform.getPageSizeParamName()}=${schema.pageSize}`);
824
+ params.push(`${this.config.dataTransform.getPageParamName()}=${pageNumber}`);
825
+ return `${baseUrl}?${params.join('&')}`;
826
+ }
827
+ checkRecordIdExists(recordId, operation) {
828
+ if (!recordId) {
829
+ const error = {
830
+ message: 'Identifier not defined',
831
+ operation: operation
832
+ };
833
+ throw new PoEventSourcingErrorResponse(error);
834
+ }
835
+ }
836
+ concatPageItems(pageAcumulator, requestBody) {
837
+ if (requestBody[this.config.dataTransform.getItemsFieldName()]) {
838
+ pageAcumulator.data = [...pageAcumulator.data, ...requestBody[this.config.dataTransform.getItemsFieldName()]];
839
+ }
840
+ return pageAcumulator;
841
+ }
842
+ createEventSourcingItem(operation, newItem, schemaName, customRequestId, id) {
843
+ if (!schemaName && operation !== PoEventSourcingOperation.Http) {
844
+ throw new Error('PoSyncSchema is not defined.');
845
+ }
846
+ return {
847
+ id: id ? id : new Date().getTime(),
848
+ dateTime: new Date().getTime(),
849
+ schema: schemaName,
850
+ operation: operation,
851
+ record: newItem,
852
+ customRequestId: customRequestId
853
+ };
854
+ }
855
+ createEventSourcingList(schemaName, eventList) {
856
+ return eventList.map((eventItem, index) => {
857
+ const id = new Date().getTime() + index;
858
+ return this.createEventSourcingItem(eventItem.operation, eventItem.record, schemaName, eventItem.customRequestId, id);
859
+ });
860
+ }
861
+ createSchemaSyncConfig(schemaName) {
862
+ this.schemasSyncConfig[schemaName] = {
863
+ page: undefined,
864
+ currentUrlDiff: undefined,
865
+ responseDate: undefined
866
+ };
867
+ }
868
+ deleteOperation(eventSourcingItem) {
869
+ return __awaiter(this, void 0, void 0, function* () {
870
+ try {
871
+ const schema = yield this.poSchemaDefinition.get(eventSourcingItem.schema);
872
+ const recordId = eventSourcingItem.record[schema.idField];
873
+ this.checkRecordIdExists(recordId, PoEventSourcingOperation.Delete);
874
+ const url = PoEventSourcingService.getUrl(eventSourcingItem, schema, PoRequestType.DELETE);
875
+ const response = yield this.sendServerItem(url, PoHttpRequestType.DELETE);
876
+ yield this.removeEventSourcingValidItem(response.status, eventSourcingItem);
877
+ return yield this.sendResponseSubject(eventSourcingItem, response);
878
+ }
879
+ catch (errorResponse) {
880
+ return this.sendResponseSubject(eventSourcingItem, errorResponse, true);
881
+ }
882
+ });
883
+ }
884
+ diffServerItems(currentUrlDiff) {
885
+ return this.poHttpClient.get(currentUrlDiff);
886
+ }
887
+ getBodyAndDate(schemaName, response) {
888
+ const getDateFieldName = this.config.dataTransform.getDateFieldName();
889
+ const responseSyncDate = response.body[getDateFieldName];
890
+ this.schemasSyncConfig[schemaName]['responseDate'] = responseSyncDate;
891
+ return response.body;
892
+ }
893
+ getServerDiffRecords(schema, baseUrl) {
894
+ return __awaiter(this, void 0, void 0, function* () {
895
+ const initialAcumulatorPage = { entity: schema.name, data: [] };
896
+ const diffUrl = this.schemasSyncConfig[schema.name]['currentUrlDiff'];
897
+ const serverResponse = yield this.diffServerItems(diffUrl)
898
+ .pipe(map(response => this.getBodyAndDate(schema.name, response)), expand(data => this.paginateSchemaData(data, schema, baseUrl)), reduce((pageAcumulator, requestBody) => this.concatPageItems(pageAcumulator, requestBody), initialAcumulatorPage))
899
+ .toPromise();
900
+ return serverResponse.data;
901
+ });
902
+ }
903
+ httpOperation(eventSourcingItem) {
904
+ return __awaiter(this, void 0, void 0, function* () {
905
+ try {
906
+ const requestData = yield this.createPoHttpRequestData(eventSourcingItem.record.url, eventSourcingItem.record.method, eventSourcingItem.record, eventSourcingItem.record.headers);
907
+ const response = yield this.poHttpClient.createRequest(requestData).toPromise();
908
+ const poHttpCommandResponse = {
909
+ id: eventSourcingItem.id,
910
+ customRequestId: eventSourcingItem.customRequestId,
911
+ request: eventSourcingItem.record,
912
+ response: response
913
+ };
914
+ this.responseSubject.next(poHttpCommandResponse);
915
+ return this.removeEventSourcingValidItem(response.status, eventSourcingItem);
916
+ }
917
+ catch (errorHttpClient) {
918
+ return this.sendResponseSubject(eventSourcingItem, errorHttpClient, true);
919
+ }
920
+ });
921
+ }
922
+ insertEventSourcingQueue(eventSourcingItem) {
923
+ return __awaiter(this, void 0, void 0, function* () {
924
+ const eventSourcingUpdatedQueue = yield this.poStorage.appendItemToArray(PoEventSourcingService.event_sourcing_name, eventSourcingItem);
925
+ this.notifyEventCreation();
926
+ return Promise.resolve(eventSourcingUpdatedQueue);
927
+ });
928
+ }
929
+ insertOperation(currentEventSourcingItem) {
930
+ return __awaiter(this, void 0, void 0, function* () {
931
+ const schema = yield this.poSchemaDefinition.get(currentEventSourcingItem.schema);
932
+ const url = PoEventSourcingService.getUrl(currentEventSourcingItem, schema, PoRequestType.POST);
933
+ try {
934
+ const response = yield this.sendServerItem(url, PoHttpRequestType.POST, currentEventSourcingItem.record);
935
+ const recordUpdatedByServer = response.body;
936
+ yield this.removeEventSourcingValidItem(response.status, currentEventSourcingItem);
937
+ const id = currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName];
938
+ yield this.poSchemaService.update(schema, recordUpdatedByServer, id);
939
+ const eventSourcingItems = yield this.poStorage.get(PoEventSourcingService.event_sourcing_name);
940
+ yield this.updatePendingEventSourcing(currentEventSourcingItem, schema.idField, recordUpdatedByServer, eventSourcingItems);
941
+ return this.sendResponseSubject(currentEventSourcingItem, response);
942
+ }
943
+ catch (errorHttpClient) {
944
+ return this.sendResponseSubject(currentEventSourcingItem, errorHttpClient, true);
945
+ }
946
+ });
947
+ }
948
+ isValidStatus(status) {
949
+ return PoEventSourcingService.VALID_HTTP_STATUS_CODES.includes(status);
950
+ }
951
+ notifyEventCreation() {
952
+ if (this.emitter) {
953
+ this.emitter.next();
954
+ }
955
+ }
956
+ paginateSchemaData(data, schema, baseUrl) {
957
+ this.config.dataTransform.transform(data);
958
+ if (this.config.dataTransform.hasNext()) {
959
+ this.schemasSyncConfig[schema.name]['currentUrlDiff'] = this.buildUrlParams(schema, baseUrl, ++this.schemasSyncConfig[schema.name]['page']);
960
+ return this.diffServerItems(this.schemasSyncConfig[schema.name]['currentUrlDiff']).pipe(map(response => this.getBodyAndDate(schema.name, response)));
961
+ }
962
+ return of();
963
+ }
964
+ removeEventSourcingValidItem(status, eventSourcingItem) {
965
+ if (this.isValidStatus(status) || eventSourcingItem.operation === PoEventSourcingOperation.Http) {
966
+ return this.removeEventSourcingItem(eventSourcingItem.id);
967
+ }
968
+ }
969
+ selectOperation(eventSourcingItem) {
970
+ switch (eventSourcingItem.operation) {
971
+ case PoEventSourcingOperation.Insert:
972
+ return this.insertOperation(eventSourcingItem);
973
+ case PoEventSourcingOperation.Update:
974
+ return this.updateOperation(eventSourcingItem);
975
+ case PoEventSourcingOperation.Delete:
976
+ return this.deleteOperation(eventSourcingItem);
977
+ case PoEventSourcingOperation.Http:
978
+ return this.httpOperation(eventSourcingItem);
979
+ }
980
+ }
981
+ sendResponseSubject(eventSourcingItem, response, isSubjectError = false) {
982
+ const poSyncResponse = {
983
+ id: eventSourcingItem.id,
984
+ customRequestId: eventSourcingItem.customRequestId,
985
+ request: eventSourcingItem.record,
986
+ response: response
987
+ };
988
+ this.stoppedQueueEventSourcing = isSubjectError;
989
+ this.responseSubject.next(poSyncResponse);
990
+ return Promise.resolve();
991
+ }
992
+ sendServerItem(url, method, body) {
993
+ return __awaiter(this, void 0, void 0, function* () {
994
+ const requestData = yield this.createPoHttpRequestData(url, method, body);
995
+ return this.poHttpClient.createRequest(requestData).toPromise();
996
+ });
997
+ }
998
+ createPoHttpRequestData(url, method, record, headers) {
999
+ var _a;
1000
+ return __awaiter(this, void 0, void 0, function* () {
1001
+ let body = (_a = record.body) !== null && _a !== void 0 ? _a : record;
1002
+ if (record.bodyType === 'File') {
1003
+ body = yield this.createFormData(body, record.fileName, record.mimeType, record.formField);
1004
+ }
1005
+ return { url, method, body, headers };
1006
+ });
1007
+ }
1008
+ createFormData(body, fileName, mimeType, formField = 'file') {
1009
+ return __awaiter(this, void 0, void 0, function* () {
1010
+ const file = yield toFile(body, fileName, mimeType);
1011
+ const formData = new FormData();
1012
+ formData.append(formField, file, fileName);
1013
+ return formData;
1014
+ });
1015
+ }
1016
+ updateOperation(eventSourcingItem) {
1017
+ return __awaiter(this, void 0, void 0, function* () {
1018
+ const schema = yield this.poSchemaDefinition.get(eventSourcingItem.schema);
1019
+ const url = PoEventSourcingService.getUrl(eventSourcingItem, schema, PoRequestType.PATCH);
1020
+ try {
1021
+ const recordId = eventSourcingItem.record[schema.idField];
1022
+ this.checkRecordIdExists(recordId, PoEventSourcingOperation.Update);
1023
+ const response = yield this.sendServerItem(url, PoHttpRequestType.PUT, eventSourcingItem.record);
1024
+ yield this.removeEventSourcingValidItem(response.status, eventSourcingItem);
1025
+ return yield this.sendResponseSubject(eventSourcingItem, response);
1026
+ }
1027
+ catch (errorHttpClient) {
1028
+ return this.sendResponseSubject(eventSourcingItem, errorHttpClient, true);
1029
+ }
1030
+ });
1031
+ }
1032
+ updatePendingEventSourcing(currentEventSourcingItem, idFieldSchema, inserted, eventSourcingItems) {
1033
+ if (currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName]) {
1034
+ eventSourcingItems.forEach((eventSourcingItem, position) => {
1035
+ const isCurrentEventSourcingItem = !eventSourcingItem.record[idFieldSchema] &&
1036
+ eventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName] ===
1037
+ currentEventSourcingItem.record[PoSchemaUtil.syncInternalIdFieldName];
1038
+ if (isCurrentEventSourcingItem) {
1039
+ eventSourcingItems[position].record[idFieldSchema] = inserted[idFieldSchema];
1040
+ }
1041
+ });
1042
+ return this.poStorage.set(PoEventSourcingService.event_sourcing_name, eventSourcingItems);
1043
+ }
1044
+ else {
1045
+ return Promise.resolve();
1046
+ }
1047
+ }
1048
+ updateRecords(serverRecords, schema) {
1049
+ return __awaiter(this, void 0, void 0, function* () {
1050
+ for (const serverRecord of serverRecords) {
1051
+ yield this.updateRecordByServerRecord(serverRecord, schema);
1052
+ }
1053
+ });
1054
+ }
1055
+ updateRecordByServerRecord(serverRecord, schema) {
1056
+ return __awaiter(this, void 0, void 0, function* () {
1057
+ const recordId = serverRecord[schema.idField];
1058
+ const storageRecord = yield this.poSchemaService.get(schema.name, recordId);
1059
+ const existsStorageRecord = !!Object.keys(storageRecord).length;
1060
+ if (existsStorageRecord && serverRecord[schema.deletedField]) {
1061
+ return yield this.poSchemaService.remove(schema.name, serverRecord[schema.idField]);
1062
+ }
1063
+ if (existsStorageRecord && !serverRecord[schema.deletedField]) {
1064
+ return yield this.poSchemaService.update(schema, serverRecord);
1065
+ }
1066
+ if (!existsStorageRecord && !serverRecord[schema.deletedField]) {
1067
+ return yield this.poSchemaService.create(schema, serverRecord);
1068
+ }
1069
+ });
1070
+ }
1071
+ updateStorageBySchema(schema) {
1072
+ return __awaiter(this, void 0, void 0, function* () {
1073
+ this.createSchemaSyncConfig(schema.name);
1074
+ this.schemasSyncConfig[schema.name]['page'] = 1;
1075
+ const baseUrl = `${PoSchemaUtil.getUrl(schema, PoRequestType.DIFF)}/${schema.lastSync}`;
1076
+ this.schemasSyncConfig[schema.name]['currentUrlDiff'] = this.buildUrlParams(schema, baseUrl, this.schemasSyncConfig[schema.name]['page']);
1077
+ const serverRecords = yield this.getServerDiffRecords(schema, baseUrl);
1078
+ yield this.updateRecords(serverRecords, schema);
1079
+ schema.lastSync = this.schemasSyncConfig[schema.name]['responseDate'];
1080
+ yield this.poSchemaDefinition.update(schema);
1081
+ });
1082
+ }
1083
+ updateStorageSchemas(schemas) {
1084
+ return schemas.map((schema) => this.updateStorageBySchema(schema));
1085
+ }
1086
+ }
1087
+ PoEventSourcingService.event_sourcing_name = 'EventSourcing';
1088
+ PoEventSourcingService.VALID_HTTP_STATUS_CODES = [
1089
+ HttpStatus.OK,
1090
+ HttpStatus.CREATED,
1091
+ HttpStatus.ACCEPTED,
1092
+ HttpStatus.NON_AUTHORITATIVE_INFORMATION,
1093
+ HttpStatus.NO_CONTENT,
1094
+ HttpStatus.RESET_CONTENT,
1095
+ HttpStatus.PARTIAL_CONTENT,
1096
+ HttpStatus.MULTI_STATUS // 207
1101
1097
  ];
1098
+ PoEventSourcingService.ɵfac = function PoEventSourcingService_Factory(t) { return new (t || PoEventSourcingService)(i0.ɵɵinject(PoSchemaDefinitionService), i0.ɵɵinject(PoSchemaService), i0.ɵɵinject(i1.PoStorageService), i0.ɵɵinject(PoHttpClientService)); };
1099
+ PoEventSourcingService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoEventSourcingService, factory: PoEventSourcingService.ɵfac });
1100
+ (function () {
1101
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoEventSourcingService, [{
1102
+ type: Injectable
1103
+ }], function () { return [{ type: PoSchemaDefinitionService }, { type: PoSchemaService }, { type: i1.PoStorageService }, { type: PoHttpClientService }]; }, null);
1104
+ })();
1102
1105
 
1103
- /**
1104
- * @description
1105
- *
1106
- * Classe utilitária para construir consultas sobre os registros de um *schema*.
1107
- *
1108
- * A utilização dos métodos desta classe é feita a partir do retorno do método `PoEntity.find()`. Por exemplo,
1109
- * para utilizar o método `PoQueryBuilder.page()`, é necessário:
1110
- *
1111
- * ``` typescript
1112
- * PoSyncService.getModel('schema name').find().page(2).exec();
1113
- * ```
1114
- *
1115
- * O `PoQueryBuilder` foi projetado para que os seus métodos sejam
1116
- * chamados em cascata e ao final desse encadeamento invocar o método
1117
- * `PoQueryBuilder.exec()` para que a busca seja concluída. Por exemplo:
1118
- *
1119
- * ``` typescript
1120
- * PoSyncService
1121
- * .getModel('schema name')
1122
- * .find()
1123
- * .page(2)
1124
- * .pageSize(5)
1125
- * .sort()
1126
- * .exec();
1127
- * ```
1128
- */
1129
- class PoQueryBuilder {
1130
- constructor(poSchemaService, schema) {
1131
- this.poSchemaService = poSchemaService;
1132
- this.schema = schema;
1133
- this._page = 1;
1134
- this.filters = {};
1135
- }
1136
- /**
1137
- * Ao final da chamada dos métodos do `PoQueryBuilder` utilizados, este método deve ser chamado para que a busca seja concluída.
1138
- *
1139
- * @return {Promise<PoResponseApi | object>} Registros do *schema* na qual foi aplicado a consulta.
1140
- */
1141
- exec() {
1142
- return __awaiter(this, void 0, void 0, function* () {
1143
- let storageData = yield this.poSchemaService.getAll(this.schema.name);
1144
- if (storageData && storageData.length) {
1145
- if (Object.keys(this.filters).length) {
1146
- storageData = this.applyFilters(storageData);
1147
- }
1148
- if (this.fields) {
1149
- storageData = this.applyFields(this.schema.fields, storageData);
1150
- }
1151
- if (this._sort) {
1152
- storageData = this.order(storageData, this._sort);
1153
- }
1154
- if (this._limit) {
1155
- return storageData[0];
1156
- }
1157
- else {
1158
- return this.paginate(storageData);
1159
- }
1160
- }
1161
- else {
1162
- return {
1163
- hasNext: false,
1164
- items: []
1165
- };
1166
- }
1167
- });
1168
- }
1169
- /**
1170
- * Aplica filtros sobre os registros, baseados nos campos e valores definidos como filtro. Por exemplo:
1171
- *
1172
- * ```
1173
- * PoQueryBuilder.filter({ name: 'Marie', age: 24 });
1174
- * ```
1175
- * Retorna todos os registros que contenham a propriedade `name` igual a Marie e `age` igual a 24.
1176
- *
1177
- * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1178
- *
1179
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1180
- */
1181
- filter(filter) {
1182
- if (filter && typeof filter === 'object') {
1183
- this.filters = Object.assign(Object.assign({}, this.filters), filter);
1184
- }
1185
- else {
1186
- throw new Error('Filter must be an object');
1187
- }
1188
- return this;
1189
- }
1190
- /**
1191
- * Limita o número de registros que serão retornados.
1192
- *
1193
- * @param {number} limit Número de registros retornados.
1194
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1195
- */
1196
- limit(limit) {
1197
- this._limit = limit;
1198
- return this;
1199
- }
1200
- /**
1201
- * Especifica a página de registros que se deseja retornar.
1202
- *
1203
- * @param {number} page Número da página.
1204
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1205
- */
1206
- page(page) {
1207
- validateParameter({ page });
1208
- this._page = page;
1209
- return this;
1210
- }
1211
- /**
1212
- * Define quantos elementos serão retornados por página.
1213
- *
1214
- * @param {number} pageSize Número de registros por página.
1215
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1216
- */
1217
- pageSize(pageSize) {
1218
- validateParameter({ pageSize });
1219
- this._pageSize = pageSize;
1220
- return this;
1221
- }
1222
- /**
1223
- * Utilizado para definir quais campos do *schema* serão retornados na consulta.
1224
- *
1225
- * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1226
- * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1227
- * Por exemplo, a definição abaixo:
1228
- *
1229
- * ```
1230
- * PoQueryBuilder.select('name age address');
1231
- * ```
1232
- * Irá retornar apenas os campos `name`, `age` e `address`. Para não retornar um campo ou mais basta fazer:
1233
- *
1234
- * ```
1235
- * PoQueryBuilder.select('-name -age');
1236
- * ```
1237
- *
1238
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1239
- */
1240
- select(fields) {
1241
- validateParameter({ fields });
1242
- this.fields = fields;
1243
- return this;
1244
- }
1245
- /**
1246
- * Ordena os registros por um campo.
1247
- *
1248
- * @param {string} field Campo a ser ordenado. Para ordenar de forma decrescente basta colocar o caractere `-`
1249
- * na frente do campo. Por exemplo:
1250
- * ```
1251
- * PoQueryBuilder.sort('-name');
1252
- * ```
1253
- *
1254
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1255
- */
1256
- sort(field) {
1257
- validateParameter({ field });
1258
- this._sort = field;
1259
- return this;
1260
- }
1261
- /**
1262
- * Essa função serve como alias para o `PoQueryBuilder.filter()`. É utilizada somente para dar maior legibilidade ao código.
1263
- *
1264
- * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1265
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1266
- */
1267
- where(filter) {
1268
- return this.filter(filter);
1269
- }
1270
- applyFields(schemaFields, data) {
1271
- const receivedFields = this.fields.split(' ');
1272
- let restrictedFields = [];
1273
- let selectedFields = [];
1274
- [selectedFields, restrictedFields] = this.groupFields(receivedFields);
1275
- if (!selectedFields.length && restrictedFields.length) {
1276
- selectedFields = [...schemaFields];
1277
- }
1278
- if (restrictedFields.length) {
1279
- selectedFields = this.removeRestrictedFields(restrictedFields, selectedFields);
1280
- }
1281
- selectedFields = this.removeDuplicate(selectedFields);
1282
- return this.removeFieldsData(data, selectedFields);
1283
- }
1284
- applyFilters(data) {
1285
- Object.keys(this.filters).forEach(filterKey => {
1286
- data = data.filter(item => item[filterKey] === this.filters[filterKey]);
1287
- });
1288
- return data;
1289
- }
1290
- groupFields(receivedFields) {
1291
- const restrictedFields = [];
1292
- const selectedFields = [];
1293
- receivedFields.forEach(fields => {
1294
- if (fields.startsWith('-')) {
1295
- restrictedFields.push(fields.substring(1));
1296
- }
1297
- else {
1298
- selectedFields.push(fields);
1299
- }
1300
- });
1301
- return [selectedFields, restrictedFields];
1302
- }
1303
- paginate(data) {
1304
- const dataLength = data.length;
1305
- const pageSize = this._pageSize || dataLength;
1306
- const pages = Math.ceil(dataLength / pageSize);
1307
- const begin = this._page * pageSize - pageSize;
1308
- const end = begin + pageSize;
1309
- return { hasNext: this._page < pages, items: data.slice(begin, end) };
1310
- }
1311
- order(data, sortingField) {
1312
- const descendingOrder = sortingField.startsWith('-');
1313
- sortingField = descendingOrder ? sortingField.substr(1) : sortingField;
1314
- return data.sort((optionA, optionB) => {
1315
- if (optionA[sortingField] > optionB[sortingField]) {
1316
- return !descendingOrder ? 1 : -1;
1317
- }
1318
- if (optionA[sortingField] < optionB[sortingField]) {
1319
- return !descendingOrder ? -1 : 1;
1320
- }
1321
- return 0;
1322
- });
1323
- }
1324
- removeDuplicate(fields) {
1325
- return fields.filter((item, position) => fields.indexOf(item) === position);
1326
- }
1327
- removeFieldsData(data, chosenFields) {
1328
- data.forEach(item => {
1329
- Object.keys(item).forEach(keyItem => {
1330
- if (!chosenFields.includes(keyItem)) {
1331
- delete item[keyItem];
1332
- }
1333
- });
1334
- });
1335
- return data;
1336
- }
1337
- removeRestrictedFields(restrictedFields, fields) {
1338
- return fields.filter(field => !restrictedFields.includes(field));
1339
- }
1106
+ /**
1107
+ * @description
1108
+ *
1109
+ * Classe utilitária para construir consultas sobre os registros de um *schema*.
1110
+ *
1111
+ * A utilização dos métodos desta classe é feita a partir do retorno do método `PoEntity.find()`. Por exemplo,
1112
+ * para utilizar o método `PoQueryBuilder.page()`, é necessário:
1113
+ *
1114
+ * ``` typescript
1115
+ * PoSyncService.getModel('schema name').find().page(2).exec();
1116
+ * ```
1117
+ *
1118
+ * O `PoQueryBuilder` foi projetado para que os seus métodos sejam
1119
+ * chamados em cascata e ao final desse encadeamento invocar o método
1120
+ * `PoQueryBuilder.exec()` para que a busca seja concluída. Por exemplo:
1121
+ *
1122
+ * ``` typescript
1123
+ * PoSyncService
1124
+ * .getModel('schema name')
1125
+ * .find()
1126
+ * .page(2)
1127
+ * .pageSize(5)
1128
+ * .sort()
1129
+ * .exec();
1130
+ * ```
1131
+ */
1132
+ class PoQueryBuilder {
1133
+ constructor(poSchemaService, schema) {
1134
+ this.poSchemaService = poSchemaService;
1135
+ this.schema = schema;
1136
+ this._page = 1;
1137
+ this.filters = {};
1138
+ }
1139
+ /**
1140
+ * Ao final da chamada dos métodos do `PoQueryBuilder` utilizados, este método deve ser chamado para que a busca seja concluída.
1141
+ *
1142
+ * @return {Promise<PoResponseApi | object>} Registros do *schema* na qual foi aplicado a consulta.
1143
+ */
1144
+ exec() {
1145
+ return __awaiter(this, void 0, void 0, function* () {
1146
+ let storageData = yield this.poSchemaService.getAll(this.schema.name);
1147
+ if (storageData && storageData.length) {
1148
+ if (Object.keys(this.filters).length) {
1149
+ storageData = this.applyFilters(storageData);
1150
+ }
1151
+ if (this.fields) {
1152
+ storageData = this.applyFields(this.schema.fields, storageData);
1153
+ }
1154
+ if (this._sort) {
1155
+ storageData = this.order(storageData, this._sort);
1156
+ }
1157
+ if (this._limit) {
1158
+ return storageData[0];
1159
+ }
1160
+ else {
1161
+ return this.paginate(storageData);
1162
+ }
1163
+ }
1164
+ else {
1165
+ return {
1166
+ hasNext: false,
1167
+ items: []
1168
+ };
1169
+ }
1170
+ });
1171
+ }
1172
+ /**
1173
+ * Aplica filtros sobre os registros, baseados nos campos e valores definidos como filtro. Por exemplo:
1174
+ *
1175
+ * ```
1176
+ * PoQueryBuilder.filter({ name: 'Marie', age: 24 });
1177
+ * ```
1178
+ * Retorna todos os registros que contenham a propriedade `name` igual a Marie e `age` igual a 24.
1179
+ *
1180
+ * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1181
+ *
1182
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1183
+ */
1184
+ filter(filter) {
1185
+ if (filter && typeof filter === 'object') {
1186
+ this.filters = Object.assign(Object.assign({}, this.filters), filter);
1187
+ }
1188
+ else {
1189
+ throw new Error('Filter must be an object');
1190
+ }
1191
+ return this;
1192
+ }
1193
+ /**
1194
+ * Limita o número de registros que serão retornados.
1195
+ *
1196
+ * @param {number} limit Número de registros retornados.
1197
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1198
+ */
1199
+ limit(limit) {
1200
+ this._limit = limit;
1201
+ return this;
1202
+ }
1203
+ /**
1204
+ * Especifica a página de registros que se deseja retornar.
1205
+ *
1206
+ * @param {number} page Número da página.
1207
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1208
+ */
1209
+ page(page) {
1210
+ validateParameter({ page });
1211
+ this._page = page;
1212
+ return this;
1213
+ }
1214
+ /**
1215
+ * Define quantos elementos serão retornados por página.
1216
+ *
1217
+ * @param {number} pageSize Número de registros por página.
1218
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1219
+ */
1220
+ pageSize(pageSize) {
1221
+ validateParameter({ pageSize });
1222
+ this._pageSize = pageSize;
1223
+ return this;
1224
+ }
1225
+ /**
1226
+ * Utilizado para definir quais campos do *schema* serão retornados na consulta.
1227
+ *
1228
+ * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1229
+ * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1230
+ * Por exemplo, a definição abaixo:
1231
+ *
1232
+ * ```
1233
+ * PoQueryBuilder.select('name age address');
1234
+ * ```
1235
+ * Irá retornar apenas os campos `name`, `age` e `address`. Para não retornar um campo ou mais basta fazer:
1236
+ *
1237
+ * ```
1238
+ * PoQueryBuilder.select('-name -age');
1239
+ * ```
1240
+ *
1241
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1242
+ */
1243
+ select(fields) {
1244
+ validateParameter({ fields });
1245
+ this.fields = fields;
1246
+ return this;
1247
+ }
1248
+ /**
1249
+ * Ordena os registros por um campo.
1250
+ *
1251
+ * @param {string} field Campo a ser ordenado. Para ordenar de forma decrescente basta colocar o caractere `-`
1252
+ * na frente do campo. Por exemplo:
1253
+ * ```
1254
+ * PoQueryBuilder.sort('-name');
1255
+ * ```
1256
+ *
1257
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1258
+ */
1259
+ sort(field) {
1260
+ validateParameter({ field });
1261
+ this._sort = field;
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Essa função serve como alias para o `PoQueryBuilder.filter()`. É utilizada somente para dar maior legibilidade ao código.
1266
+ *
1267
+ * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1268
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um novo método do `PoQueryBuilder`.
1269
+ */
1270
+ where(filter) {
1271
+ return this.filter(filter);
1272
+ }
1273
+ applyFields(schemaFields, data) {
1274
+ const receivedFields = this.fields.split(' ');
1275
+ let restrictedFields = [];
1276
+ let selectedFields = [];
1277
+ [selectedFields, restrictedFields] = this.groupFields(receivedFields);
1278
+ if (!selectedFields.length && restrictedFields.length) {
1279
+ selectedFields = [...schemaFields];
1280
+ }
1281
+ if (restrictedFields.length) {
1282
+ selectedFields = this.removeRestrictedFields(restrictedFields, selectedFields);
1283
+ }
1284
+ selectedFields = this.removeDuplicate(selectedFields);
1285
+ return this.removeFieldsData(data, selectedFields);
1286
+ }
1287
+ applyFilters(data) {
1288
+ Object.keys(this.filters).forEach(filterKey => {
1289
+ data = data.filter(item => item[filterKey] === this.filters[filterKey]);
1290
+ });
1291
+ return data;
1292
+ }
1293
+ groupFields(receivedFields) {
1294
+ const restrictedFields = [];
1295
+ const selectedFields = [];
1296
+ receivedFields.forEach(fields => {
1297
+ if (fields.startsWith('-')) {
1298
+ restrictedFields.push(fields.substring(1));
1299
+ }
1300
+ else {
1301
+ selectedFields.push(fields);
1302
+ }
1303
+ });
1304
+ return [selectedFields, restrictedFields];
1305
+ }
1306
+ paginate(data) {
1307
+ const dataLength = data.length;
1308
+ const pageSize = this._pageSize || dataLength;
1309
+ const pages = Math.ceil(dataLength / pageSize);
1310
+ const begin = this._page * pageSize - pageSize;
1311
+ const end = begin + pageSize;
1312
+ return { hasNext: this._page < pages, items: data.slice(begin, end) };
1313
+ }
1314
+ order(data, sortingField) {
1315
+ const descendingOrder = sortingField.startsWith('-');
1316
+ sortingField = descendingOrder ? sortingField.substr(1) : sortingField;
1317
+ return data.sort((optionA, optionB) => {
1318
+ if (optionA[sortingField] > optionB[sortingField]) {
1319
+ return !descendingOrder ? 1 : -1;
1320
+ }
1321
+ if (optionA[sortingField] < optionB[sortingField]) {
1322
+ return !descendingOrder ? -1 : 1;
1323
+ }
1324
+ return 0;
1325
+ });
1326
+ }
1327
+ removeDuplicate(fields) {
1328
+ return fields.filter((item, position) => fields.indexOf(item) === position);
1329
+ }
1330
+ removeFieldsData(data, chosenFields) {
1331
+ data.forEach(item => {
1332
+ Object.keys(item).forEach(keyItem => {
1333
+ if (!chosenFields.includes(keyItem)) {
1334
+ delete item[keyItem];
1335
+ }
1336
+ });
1337
+ });
1338
+ return data;
1339
+ }
1340
+ removeRestrictedFields(restrictedFields, fields) {
1341
+ return fields.filter(field => !restrictedFields.includes(field));
1342
+ }
1340
1343
  }
1341
1344
 
1342
- /**
1343
- * @description
1344
- *
1345
- * Uma instância `PoEntity` representa um *schema* e ela contém métodos que possibilitam manipular seus registros,
1346
- * como por exemplo: buscar, criar e remover.
1347
- *
1348
- * Esta instância pode ser obtida a partir do retorno do método `PoSyncService.getModel('schema name')`.
1349
- */
1350
- class PoEntity {
1351
- constructor(eventSourcing, schema, poSchemaService) {
1352
- this.eventSourcing = eventSourcing;
1353
- this.schema = schema;
1354
- this.poSchemaService = poSchemaService;
1355
- }
1356
- /**
1357
- * Busca os registros do *schema*, podendo filtrar o resultado a partir do filtro passado e retornando apenas
1358
- * os campos definidos.
1359
- *
1360
- * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1361
- * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1362
- *
1363
- * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1364
- * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1365
- * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1366
- * Por exemplo, a definição abaixo:
1367
- *
1368
- * ```
1369
- * PoQueryBuilder.select('name age address');
1370
- * ```
1371
- * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1372
- *
1373
- * ```
1374
- * PoQueryBuilder.select('-name -age');
1375
- * ```
1376
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1377
- */
1378
- find(filter, fields) {
1379
- const query = new PoQueryBuilder(this.poSchemaService, this.schema);
1380
- if (filter) {
1381
- query.filter(filter);
1382
- }
1383
- if (fields) {
1384
- query.select(fields);
1385
- }
1386
- return query;
1387
- }
1388
- /**
1389
- * Busca um registro pelo seu *id*.
1390
- *
1391
- * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1392
- * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1393
- *
1394
- * @param {any} id Identificador do registro.
1395
- * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1396
- * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1397
- * Por exemplo, a definição abaixo:
1398
- *
1399
- * ```
1400
- * PoQueryBuilder.select('name age address');
1401
- * ```
1402
- * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1403
- *
1404
- * ```
1405
- * PoQueryBuilder.select('-name -age');
1406
- * ```
1407
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1408
- */
1409
- findById(id, fields) {
1410
- return this.findOne({ [this.schema.idField]: id }, fields);
1411
- }
1412
- /**
1413
- * Semelhante ao método `PoEntity.find()`, porém retorna apenas o primeiro registro encontrado na busca.
1414
- *
1415
- * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1416
- * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1417
- *
1418
- * @param {any} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1419
- * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1420
- * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1421
- * Por exemplo, a definição abaixo:
1422
- *
1423
- * ```
1424
- * PoQueryBuilder.select('name age address');
1425
- * ```
1426
- * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1427
- *
1428
- * ```
1429
- * PoQueryBuilder.select('-name -age');
1430
- * ```
1431
- * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1432
- */
1433
- findOne(filter, fields) {
1434
- const query = this.find(filter, fields);
1435
- query.limit(1);
1436
- return query;
1437
- }
1438
- /**
1439
- * Remove um registro.
1440
- *
1441
- * @param {object} record Registro que será removido.
1442
- * @param {string} customRequestId Identificador customizado do comando.
1443
- * @returns {Promise} Promessa que é concluída após o registro ser removido.
1444
- */
1445
- remove(record, customRequestId) {
1446
- return __awaiter(this, void 0, void 0, function* () {
1447
- validateParameter({ record });
1448
- const remove = () => __awaiter(this, void 0, void 0, function* () {
1449
- const idField = record[this.schema.idField] ? this.schema.idField : PoSchemaUtil.syncInternalIdFieldName;
1450
- const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, record)['serverRecord'];
1451
- yield this.poSchemaService.remove(this.schema.name, record[idField]);
1452
- yield this.eventSourcing.remove(this.schema.name, serverRecord, customRequestId);
1453
- });
1454
- return this.poSchemaService.limitedCallWrap(remove);
1455
- });
1456
- }
1457
- /**
1458
- * Altera ou inclui um registro.
1459
- *
1460
- * > O registro será alterado se ele possuir um *id*, caso contrário um novo registro será criado.
1461
- *
1462
- * @param {object} record Registro que será persistido.
1463
- * @param {string} customRequestId Identificador customizado do comando.
1464
- * @returns {Promise} Promessa que é concluída após o registro ser alterado ou incluído.
1465
- */
1466
- save(record, customRequestId) {
1467
- return __awaiter(this, void 0, void 0, function* () {
1468
- validateParameter({ record });
1469
- return this.poSchemaService.limitedCallWrap(this.selectSaveType.bind(this, record, true, customRequestId));
1470
- });
1471
- }
1472
- /**
1473
- * Salva uma lista de registros em lote.
1474
- *
1475
- * > Para cada registro da lista, será inserido um novo registro se o mesmo não tiver *id*, caso contrário
1476
- * será contado como uma atualização de um registro existente.
1477
- *
1478
- * @param {Array<object>} records Lista de registros que serão persistidos.
1479
- * @param {Array<string> | string} customRequestIds Identificador customizado do comando.
1480
- *
1481
- * Ao passar uma lista de identificadores, cada índice da lista de identificadores deverá
1482
- * corresponder ao índice do registro na lista de registros.
1483
- * @returns {Promise<any>} Promessa que é concluída após os registros serem alterados ou incluídos.
1484
- */
1485
- saveAll(records, customRequestIds) {
1486
- return __awaiter(this, void 0, void 0, function* () {
1487
- validateParameter({ records });
1488
- const saveAll = () => __awaiter(this, void 0, void 0, function* () {
1489
- const batchEvents = [];
1490
- for (let index = 0; index < records.length; index++) {
1491
- const record = records[index];
1492
- const sendToEventSourcing = false;
1493
- const isNonLocalRecordChanged = yield this.isNonLocalRecordChanged(record);
1494
- const updatedRecord = yield this.selectSaveType(record, sendToEventSourcing);
1495
- if (isNonLocalRecordChanged) {
1496
- const customRequestId = customRequestIds instanceof Array ? customRequestIds[index] : customRequestIds;
1497
- const eventOperation = this.createEventOperation(record, updatedRecord, customRequestId);
1498
- batchEvents.push(eventOperation);
1499
- }
1500
- }
1501
- yield this.eventSourcing.createBatchEvents(this.schema.name, batchEvents);
1502
- });
1503
- return this.poSchemaService.limitedCallWrap(saveAll);
1504
- });
1505
- }
1506
- create(newRecord, sendToEventSourcing, customRequestId) {
1507
- return __awaiter(this, void 0, void 0, function* () {
1508
- const time = new Date().getTime();
1509
- const syncProperties = {
1510
- [PoSchemaUtil.syncInternalIdFieldName]: time,
1511
- SyncInsertedDateTime: time,
1512
- SyncUpdatedDateTime: null,
1513
- SyncExclusionDateTime: null,
1514
- SyncDeleted: false,
1515
- SyncStatus: 0
1516
- };
1517
- const recordWithSyncProperties = Object.assign(Object.assign({}, newRecord), syncProperties);
1518
- const recordedData = yield this.poSchemaService.create(this.schema, recordWithSyncProperties);
1519
- if (sendToEventSourcing) {
1520
- yield this.eventSourcing.create(this.schema.name, recordWithSyncProperties, customRequestId);
1521
- }
1522
- return recordedData;
1523
- });
1524
- }
1525
- createEventOperation(record, updatedRecord, customRequestId) {
1526
- const operation = PoSchemaUtil.getRecordId(record, this.schema)
1527
- ? PoEventSourcingOperation.Update
1528
- : PoEventSourcingOperation.Insert;
1529
- const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord'];
1530
- return {
1531
- record: serverRecord,
1532
- customRequestId: customRequestId,
1533
- operation: operation
1534
- };
1535
- }
1536
- isNonLocalRecordChanged(updatedRecord) {
1537
- return __awaiter(this, void 0, void 0, function* () {
1538
- const nonLocalFieldNames = PoSchemaUtil.getNonLocalFieldNames(this.schema);
1539
- const record = yield this.poSchemaService.get(this.schema.name, updatedRecord[this.schema.idField]);
1540
- return !PoSchemaUtil.isModelsEqual(nonLocalFieldNames, record, updatedRecord);
1541
- });
1542
- }
1543
- selectSaveType(record, sendToEventSourcing, customRequestId) {
1544
- return __awaiter(this, void 0, void 0, function* () {
1545
- const hasId = PoSchemaUtil.getRecordId(record, this.schema);
1546
- return hasId
1547
- ? yield this.update(record, sendToEventSourcing, customRequestId)
1548
- : yield this.create(record, sendToEventSourcing, customRequestId);
1549
- });
1550
- }
1551
- update(updatedRecord, sendToEventSourcing, customRequestId) {
1552
- return __awaiter(this, void 0, void 0, function* () {
1553
- updatedRecord.SyncUpdatedDateTime = new Date().getTime();
1554
- updatedRecord.SyncStatus = 0;
1555
- const isNonLocalRecordChanged = yield this.isNonLocalRecordChanged(updatedRecord);
1556
- const recordedData = yield this.poSchemaService.update(this.schema, updatedRecord);
1557
- if (isNonLocalRecordChanged && sendToEventSourcing) {
1558
- const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord'];
1559
- yield this.eventSourcing.update(this.schema.name, serverRecord, customRequestId);
1560
- }
1561
- return recordedData;
1562
- });
1563
- }
1345
+ /**
1346
+ * @description
1347
+ *
1348
+ * Uma instância `PoEntity` representa um *schema* e ela contém métodos que possibilitam manipular seus registros,
1349
+ * como por exemplo: buscar, criar e remover.
1350
+ *
1351
+ * Esta instância pode ser obtida a partir do retorno do método `PoSyncService.getModel('schema name')`.
1352
+ */
1353
+ class PoEntity {
1354
+ constructor(eventSourcing, schema, poSchemaService) {
1355
+ this.eventSourcing = eventSourcing;
1356
+ this.schema = schema;
1357
+ this.poSchemaService = poSchemaService;
1358
+ }
1359
+ /**
1360
+ * Busca os registros do *schema*, podendo filtrar o resultado a partir do filtro passado e retornando apenas
1361
+ * os campos definidos.
1362
+ *
1363
+ * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1364
+ * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1365
+ *
1366
+ * @param {object} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1367
+ * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1368
+ * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1369
+ * Por exemplo, a definição abaixo:
1370
+ *
1371
+ * ```
1372
+ * PoQueryBuilder.select('name age address');
1373
+ * ```
1374
+ * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1375
+ *
1376
+ * ```
1377
+ * PoQueryBuilder.select('-name -age');
1378
+ * ```
1379
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1380
+ */
1381
+ find(filter, fields) {
1382
+ const query = new PoQueryBuilder(this.poSchemaService, this.schema);
1383
+ if (filter) {
1384
+ query.filter(filter);
1385
+ }
1386
+ if (fields) {
1387
+ query.select(fields);
1388
+ }
1389
+ return query;
1390
+ }
1391
+ /**
1392
+ * Busca um registro pelo seu *id*.
1393
+ *
1394
+ * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1395
+ * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1396
+ *
1397
+ * @param {any} id Identificador do registro.
1398
+ * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1399
+ * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1400
+ * Por exemplo, a definição abaixo:
1401
+ *
1402
+ * ```
1403
+ * PoQueryBuilder.select('name age address');
1404
+ * ```
1405
+ * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1406
+ *
1407
+ * ```
1408
+ * PoQueryBuilder.select('-name -age');
1409
+ * ```
1410
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1411
+ */
1412
+ findById(id, fields) {
1413
+ return this.findOne({ [this.schema.idField]: id }, fields);
1414
+ }
1415
+ /**
1416
+ * Semelhante ao método `PoEntity.find()`, porém retorna apenas o primeiro registro encontrado na busca.
1417
+ *
1418
+ * Para que esta busca seja concluída é necessário utilizar o método `PoQueryBuilder.exec()`.
1419
+ * Veja mais em: [PoQueryBuilder](/documentation/po-query-builder).
1420
+ *
1421
+ * @param {any} filter Objeto que contém os campos e valores a serem filtrados no *schema*.
1422
+ * @param {string} fields Campos que serão retornados nos registros. Este campos devem estar dentro de
1423
+ * uma *string* separados por espaço podendo usar o caractere `-` para excluir campos.
1424
+ * Por exemplo, a definição abaixo:
1425
+ *
1426
+ * ```
1427
+ * PoQueryBuilder.select('name age address');
1428
+ * ```
1429
+ * Irá retornar apenas os campos `name`, `age` e `address`. E para não mostrar um campo ou mais basta fazer:
1430
+ *
1431
+ * ```
1432
+ * PoQueryBuilder.select('-name -age');
1433
+ * ```
1434
+ * @returns {PoQueryBuilder} Objeto que possibilita encadear um método do `PoQueryBuilder`.
1435
+ */
1436
+ findOne(filter, fields) {
1437
+ const query = this.find(filter, fields);
1438
+ query.limit(1);
1439
+ return query;
1440
+ }
1441
+ /**
1442
+ * Remove um registro.
1443
+ *
1444
+ * @param {object} record Registro que será removido.
1445
+ * @param {string} customRequestId Identificador customizado do comando.
1446
+ * @returns {Promise} Promessa que é concluída após o registro ser removido.
1447
+ */
1448
+ remove(record, customRequestId) {
1449
+ return __awaiter(this, void 0, void 0, function* () {
1450
+ validateParameter({ record });
1451
+ const remove = () => __awaiter(this, void 0, void 0, function* () {
1452
+ const idField = record[this.schema.idField] ? this.schema.idField : PoSchemaUtil.syncInternalIdFieldName;
1453
+ const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, record)['serverRecord'];
1454
+ yield this.poSchemaService.remove(this.schema.name, record[idField]);
1455
+ yield this.eventSourcing.remove(this.schema.name, serverRecord, customRequestId);
1456
+ });
1457
+ return this.poSchemaService.limitedCallWrap(remove);
1458
+ });
1459
+ }
1460
+ /**
1461
+ * Altera ou inclui um registro.
1462
+ *
1463
+ * > O registro será alterado se ele possuir um *id*, caso contrário um novo registro será criado.
1464
+ *
1465
+ * @param {object} record Registro que será persistido.
1466
+ * @param {string} customRequestId Identificador customizado do comando.
1467
+ * @returns {Promise} Promessa que é concluída após o registro ser alterado ou incluído.
1468
+ */
1469
+ save(record, customRequestId) {
1470
+ return __awaiter(this, void 0, void 0, function* () {
1471
+ validateParameter({ record });
1472
+ return this.poSchemaService.limitedCallWrap(this.selectSaveType.bind(this, record, true, customRequestId));
1473
+ });
1474
+ }
1475
+ /**
1476
+ * Salva uma lista de registros em lote.
1477
+ *
1478
+ * > Para cada registro da lista, será inserido um novo registro se o mesmo não tiver *id*, caso contrário
1479
+ * será contado como uma atualização de um registro existente.
1480
+ *
1481
+ * @param {Array<object>} records Lista de registros que serão persistidos.
1482
+ * @param {Array<string> | string} customRequestIds Identificador customizado do comando.
1483
+ *
1484
+ * Ao passar uma lista de identificadores, cada índice da lista de identificadores deverá
1485
+ * corresponder ao índice do registro na lista de registros.
1486
+ * @returns {Promise<any>} Promessa que é concluída após os registros serem alterados ou incluídos.
1487
+ */
1488
+ saveAll(records, customRequestIds) {
1489
+ return __awaiter(this, void 0, void 0, function* () {
1490
+ validateParameter({ records });
1491
+ const saveAll = () => __awaiter(this, void 0, void 0, function* () {
1492
+ const batchEvents = [];
1493
+ for (let index = 0; index < records.length; index++) {
1494
+ const record = records[index];
1495
+ const sendToEventSourcing = false;
1496
+ const isNonLocalRecordChanged = yield this.isNonLocalRecordChanged(record);
1497
+ const updatedRecord = yield this.selectSaveType(record, sendToEventSourcing);
1498
+ if (isNonLocalRecordChanged) {
1499
+ const customRequestId = customRequestIds instanceof Array ? customRequestIds[index] : customRequestIds;
1500
+ const eventOperation = this.createEventOperation(record, updatedRecord, customRequestId);
1501
+ batchEvents.push(eventOperation);
1502
+ }
1503
+ }
1504
+ yield this.eventSourcing.createBatchEvents(this.schema.name, batchEvents);
1505
+ });
1506
+ return this.poSchemaService.limitedCallWrap(saveAll);
1507
+ });
1508
+ }
1509
+ create(newRecord, sendToEventSourcing, customRequestId) {
1510
+ return __awaiter(this, void 0, void 0, function* () {
1511
+ const time = new Date().getTime();
1512
+ const syncProperties = {
1513
+ [PoSchemaUtil.syncInternalIdFieldName]: time,
1514
+ SyncInsertedDateTime: time,
1515
+ SyncUpdatedDateTime: null,
1516
+ SyncExclusionDateTime: null,
1517
+ SyncDeleted: false,
1518
+ SyncStatus: 0
1519
+ };
1520
+ const recordWithSyncProperties = Object.assign(Object.assign({}, newRecord), syncProperties);
1521
+ const recordedData = yield this.poSchemaService.create(this.schema, recordWithSyncProperties);
1522
+ if (sendToEventSourcing) {
1523
+ yield this.eventSourcing.create(this.schema.name, recordWithSyncProperties, customRequestId);
1524
+ }
1525
+ return recordedData;
1526
+ });
1527
+ }
1528
+ createEventOperation(record, updatedRecord, customRequestId) {
1529
+ const operation = PoSchemaUtil.getRecordId(record, this.schema)
1530
+ ? PoEventSourcingOperation.Update
1531
+ : PoEventSourcingOperation.Insert;
1532
+ const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord'];
1533
+ return {
1534
+ record: serverRecord,
1535
+ customRequestId: customRequestId,
1536
+ operation: operation
1537
+ };
1538
+ }
1539
+ isNonLocalRecordChanged(updatedRecord) {
1540
+ return __awaiter(this, void 0, void 0, function* () {
1541
+ const nonLocalFieldNames = PoSchemaUtil.getNonLocalFieldNames(this.schema);
1542
+ const record = yield this.poSchemaService.get(this.schema.name, updatedRecord[this.schema.idField]);
1543
+ return !PoSchemaUtil.isModelsEqual(nonLocalFieldNames, record, updatedRecord);
1544
+ });
1545
+ }
1546
+ selectSaveType(record, sendToEventSourcing, customRequestId) {
1547
+ return __awaiter(this, void 0, void 0, function* () {
1548
+ const hasId = PoSchemaUtil.getRecordId(record, this.schema);
1549
+ return hasId
1550
+ ? yield this.update(record, sendToEventSourcing, customRequestId)
1551
+ : yield this.create(record, sendToEventSourcing, customRequestId);
1552
+ });
1553
+ }
1554
+ update(updatedRecord, sendToEventSourcing, customRequestId) {
1555
+ return __awaiter(this, void 0, void 0, function* () {
1556
+ updatedRecord.SyncUpdatedDateTime = new Date().getTime();
1557
+ updatedRecord.SyncStatus = 0;
1558
+ const isNonLocalRecordChanged = yield this.isNonLocalRecordChanged(updatedRecord);
1559
+ const recordedData = yield this.poSchemaService.update(this.schema, updatedRecord);
1560
+ if (isNonLocalRecordChanged && sendToEventSourcing) {
1561
+ const serverRecord = PoSchemaUtil.separateSchemaFields(this.schema, updatedRecord)['serverRecord'];
1562
+ yield this.eventSourcing.update(this.schema.name, serverRecord, customRequestId);
1563
+ }
1564
+ return recordedData;
1565
+ });
1566
+ }
1564
1567
  }
1565
1568
 
1566
- /**
1567
- * @usedBy PoSyncConfig, PoNetworkStatus
1568
- *
1569
- * @description
1570
- *
1571
- * Tipos de rede existentes no dispositivo.
1572
- */
1573
- var PoNetworkType;
1574
- (function (PoNetworkType) {
1575
- /** Define o tipo de rede como desconhecido (`unknown`). */
1576
- PoNetworkType[PoNetworkType["unknown"] = 0] = "unknown";
1577
- /** Define o tipo de rede como `Ethernet`. */
1578
- PoNetworkType[PoNetworkType["ethernet"] = 1] = "ethernet";
1579
- /** Define o tipo de rede como `WiFi`. */
1580
- PoNetworkType[PoNetworkType["wifi"] = 2] = "wifi";
1581
- /** Define o tipo de rede como `2G`. */
1582
- PoNetworkType[PoNetworkType["_2g"] = 3] = "_2g";
1583
- /** Define o tipo de rede como `3G`. */
1584
- PoNetworkType[PoNetworkType["_3g"] = 4] = "_3g";
1585
- /** Define o tipo de rede como `4G`. */
1586
- PoNetworkType[PoNetworkType["_4g"] = 5] = "_4g";
1587
- /**
1588
- * Define o tipo de rede como `cellular`. Isso acontece na utilização dos navegadores
1589
- * dentro do dispositvo móvel, com exceção do *web view*.
1590
- */
1591
- PoNetworkType[PoNetworkType["cellular"] = 6] = "cellular";
1592
- /** Define o tipo de rede como `none`. */
1593
- PoNetworkType[PoNetworkType["none"] = 7] = "none";
1569
+ /**
1570
+ * @usedBy PoSyncConfig, PoNetworkStatus
1571
+ *
1572
+ * @description
1573
+ *
1574
+ * Tipos de rede existentes no dispositivo.
1575
+ */
1576
+ var PoNetworkType;
1577
+ (function (PoNetworkType) {
1578
+ /** Define o tipo de rede como desconhecido (`unknown`). */
1579
+ PoNetworkType[PoNetworkType["unknown"] = 0] = "unknown";
1580
+ /** Define o tipo de rede como `Ethernet`. */
1581
+ PoNetworkType[PoNetworkType["ethernet"] = 1] = "ethernet";
1582
+ /** Define o tipo de rede como `WiFi`. */
1583
+ PoNetworkType[PoNetworkType["wifi"] = 2] = "wifi";
1584
+ /** Define o tipo de rede como `2G`. */
1585
+ PoNetworkType[PoNetworkType["_2g"] = 3] = "_2g";
1586
+ /** Define o tipo de rede como `3G`. */
1587
+ PoNetworkType[PoNetworkType["_3g"] = 4] = "_3g";
1588
+ /** Define o tipo de rede como `4G`. */
1589
+ PoNetworkType[PoNetworkType["_4g"] = 5] = "_4g";
1590
+ /**
1591
+ * Define o tipo de rede como `cellular`. Isso acontece na utilização dos navegadores
1592
+ * dentro do dispositvo móvel, com exceção do *web view*.
1593
+ */
1594
+ PoNetworkType[PoNetworkType["cellular"] = 6] = "cellular";
1595
+ /** Define o tipo de rede como `none`. */
1596
+ PoNetworkType[PoNetworkType["none"] = 7] = "none";
1594
1597
  })(PoNetworkType || (PoNetworkType = {}));
1595
1598
 
1596
- /**
1597
- * @docsPrivate
1598
- *
1599
- * @description
1600
- *
1601
- * Classe responsável por implementar a classe `PoDataTransform` com os campos referentes ao padrão de
1602
- * [API do PO UI](https://po-ui.io/guides/api).
1603
- */
1604
- class PoDataMessage extends PoDataTransform {
1605
- /**
1606
- * Retorna a propriedade `po_sync_date`, responsável por informar a data da última sincronização no guia de
1607
- * [API do PO UI](https://po-ui.io/guides/api).
1608
- *
1609
- * @returns {string} Nome do campo que contém a data da última sincronização.
1610
- */
1611
- getDateFieldName() {
1612
- return 'po_sync_date';
1613
- }
1614
- /**
1615
- * Retorna a propriedade `items`, responsável por informar a lista de registros vindos da API no guia de
1616
- * [API do PO UI](https://po-ui.io/guides/api).
1617
- *
1618
- * @returns {string} Nome da propriedade que contém a lista de registros.
1619
- */
1620
- getItemsFieldName() {
1621
- return 'items';
1622
- }
1623
- /**
1624
- * Retorna a propriedade `page`, responsável por informar o número da página de registros que a API retorna no guia de
1625
- * [API do PO UI](https://po-ui.io/guides/api).
1626
- *
1627
- * @returns {string} Nome da propriedade responsável por informar o número da página de registros.
1628
- */
1629
- getPageParamName() {
1630
- return 'page';
1631
- }
1632
- /**
1633
- * Retorna a propriedade `pageSize`, responsável pela quantidade de registros que serão exibidos por página no guia de
1634
- * [API do PO UI](https://po-ui.io/guides/api).
1635
- *
1636
- * @returns {string} Nome do parâmetro responsável pela quantidade de registros por página.
1637
- */
1638
- getPageSizeParamName() {
1639
- return 'pageSize';
1640
- }
1641
- /**
1642
- * Retorna um valor `boolean`, de acordo com a propriedade `hasNext` que é responsável por informar se há uma nova
1643
- * página de registros disponível no guia de [API do PO UI](https://po-ui.io/guides/api).
1644
- *
1645
- * @returns {boolean} Informa se tem próxima página de registros.
1646
- */
1647
- hasNext() {
1648
- return this.data.hasNext;
1649
- }
1599
+ /**
1600
+ * @docsPrivate
1601
+ *
1602
+ * @description
1603
+ *
1604
+ * Classe responsável por implementar a classe `PoDataTransform` com os campos referentes ao padrão de
1605
+ * [API do PO UI](https://po-ui.io/guides/api).
1606
+ */
1607
+ class PoDataMessage extends PoDataTransform {
1608
+ /**
1609
+ * Retorna a propriedade `po_sync_date`, responsável por informar a data da última sincronização no guia de
1610
+ * [API do PO UI](https://po-ui.io/guides/api).
1611
+ *
1612
+ * @returns {string} Nome do campo que contém a data da última sincronização.
1613
+ */
1614
+ getDateFieldName() {
1615
+ return 'po_sync_date';
1616
+ }
1617
+ /**
1618
+ * Retorna a propriedade `items`, responsável por informar a lista de registros vindos da API no guia de
1619
+ * [API do PO UI](https://po-ui.io/guides/api).
1620
+ *
1621
+ * @returns {string} Nome da propriedade que contém a lista de registros.
1622
+ */
1623
+ getItemsFieldName() {
1624
+ return 'items';
1625
+ }
1626
+ /**
1627
+ * Retorna a propriedade `page`, responsável por informar o número da página de registros que a API retorna no guia de
1628
+ * [API do PO UI](https://po-ui.io/guides/api).
1629
+ *
1630
+ * @returns {string} Nome da propriedade responsável por informar o número da página de registros.
1631
+ */
1632
+ getPageParamName() {
1633
+ return 'page';
1634
+ }
1635
+ /**
1636
+ * Retorna a propriedade `pageSize`, responsável pela quantidade de registros que serão exibidos por página no guia de
1637
+ * [API do PO UI](https://po-ui.io/guides/api).
1638
+ *
1639
+ * @returns {string} Nome do parâmetro responsável pela quantidade de registros por página.
1640
+ */
1641
+ getPageSizeParamName() {
1642
+ return 'pageSize';
1643
+ }
1644
+ /**
1645
+ * Retorna um valor `boolean`, de acordo com a propriedade `hasNext` que é responsável por informar se há uma nova
1646
+ * página de registros disponível no guia de [API do PO UI](https://po-ui.io/guides/api).
1647
+ *
1648
+ * @returns {boolean} Informa se tem próxima página de registros.
1649
+ */
1650
+ hasNext() {
1651
+ return this.data.hasNext;
1652
+ }
1650
1653
  }
1651
1654
 
1652
- /**
1653
- * @description
1654
- *
1655
- * Classe responsável por identificar a conexão de rede disponível no dispositivo.
1656
- */
1657
- class PoNetworkStatus {
1658
- constructor(networtkType) {
1659
- this.setNetworkConnection(networtkType);
1660
- }
1661
- /**
1662
- * Retorna se o dispositivo está conectado na rede.
1663
- *
1664
- * @returns {boolean} Status da conexão com a rede.
1665
- */
1666
- get status() {
1667
- return this.type !== PoNetworkType.none;
1668
- }
1669
- /**
1670
- * Retorna o tipo de conexão do dispositivo.
1671
- *
1672
- * @returns {PoNetworkType} Tipo da conexão com a rede.
1673
- */
1674
- get type() {
1675
- return this._type;
1676
- }
1677
- set type(type) {
1678
- this._type = type;
1679
- }
1680
- /* istanbul ignore next */
1681
- setDefaultTypeNavigation() {
1682
- return navigator.onLine ? PoNetworkType['ethernet'] : PoNetworkType.none;
1683
- }
1684
- setNetworkConnection(networtkType) {
1685
- if (!networtkType) {
1686
- this.type = this.setDefaultTypeNavigation();
1687
- }
1688
- else {
1689
- const isGenerationMobile = ['2g', '3g', '4g'].includes(networtkType);
1690
- this.type = isGenerationMobile ? PoNetworkType['_' + networtkType] : PoNetworkType[String(networtkType)];
1691
- }
1692
- }
1655
+ /**
1656
+ * @description
1657
+ *
1658
+ * Classe responsável por identificar a conexão de rede disponível no dispositivo.
1659
+ */
1660
+ class PoNetworkStatus {
1661
+ constructor(networtkType) {
1662
+ this.setNetworkConnection(networtkType);
1663
+ }
1664
+ /**
1665
+ * Retorna se o dispositivo está conectado na rede.
1666
+ *
1667
+ * @returns {boolean} Status da conexão com a rede.
1668
+ */
1669
+ get status() {
1670
+ return this.type !== PoNetworkType.none;
1671
+ }
1672
+ /**
1673
+ * Retorna o tipo de conexão do dispositivo.
1674
+ *
1675
+ * @returns {PoNetworkType} Tipo da conexão com a rede.
1676
+ */
1677
+ get type() {
1678
+ return this._type;
1679
+ }
1680
+ set type(type) {
1681
+ this._type = type;
1682
+ }
1683
+ /* istanbul ignore next */
1684
+ setDefaultTypeNavigation() {
1685
+ return navigator.onLine ? PoNetworkType['ethernet'] : PoNetworkType.none;
1686
+ }
1687
+ setNetworkConnection(networtkType) {
1688
+ if (!networtkType) {
1689
+ this.type = this.setDefaultTypeNavigation();
1690
+ }
1691
+ else {
1692
+ const isGenerationMobile = ['2g', '3g', '4g'].includes(networtkType);
1693
+ this.type = isGenerationMobile ? PoNetworkType['_' + networtkType] : PoNetworkType[String(networtkType)];
1694
+ }
1695
+ }
1693
1696
  }
1694
1697
 
1695
- /**
1696
- * @description
1697
- *
1698
- * O `PoNetworkService` é utilizado para verificar o status e o tipo da conexão de rede do dispositivo.
1699
- */
1700
- class PoNetworkService {
1701
- constructor(network) {
1702
- this.initNetwork(network);
1703
- }
1704
- /**
1705
- * Retorna as propriedades tipo e status da conexão do dispositivo no momento da chamada.
1706
- *
1707
- * @returns {PoNetworkStatus} Instância de [PoNetworkStatus](/documentation/po-network-status) com as
1708
- * propriedades da conexão.
1709
- */
1710
- getConnectionStatus() {
1711
- this.poNetworkStatus = new PoNetworkStatus(this.networkType);
1712
- return this.poNetworkStatus;
1713
- }
1714
- /**
1715
- * Notifica as mudanças no tipo de conexão de rede do dispositivo.
1716
- *
1717
- * @returns {Observable<{ status: boolean, type: string }>} Observable com as propriedades da conexão.
1718
- */
1719
- onChange() {
1720
- return this.networkTypeNow.asObservable();
1721
- }
1722
- getNavigatorStatus() {
1723
- return merge(fromEvent(window, 'offline').pipe(mapTo(false)), fromEvent(window, 'online').pipe(mapTo(true)), Observable.create(sub => {
1724
- sub.next(navigator.onLine);
1725
- sub.complete();
1726
- }));
1727
- }
1728
- initNetwork(network) {
1729
- this.networkTypeNow = new Subject();
1730
- this.initSubscriber(network);
1731
- }
1732
- initSubscriber(network) {
1733
- if (network) {
1734
- this.getNavigatorStatus().subscribe(status => {
1735
- this.networkType = network.type;
1736
- this.networkTypeNow.next({ status: status, type: this.networkType });
1737
- });
1738
- }
1739
- }
1740
- }
1741
- PoNetworkService.decorators = [
1742
- { type: Injectable }
1743
- ];
1744
- PoNetworkService.ctorParameters = () => [
1745
- { type: Network }
1746
- ];
1698
+ /**
1699
+ * @description
1700
+ *
1701
+ * O `PoNetworkService` é utilizado para verificar o status e o tipo da conexão de rede do dispositivo.
1702
+ */
1703
+ class PoNetworkService {
1704
+ constructor(network) {
1705
+ this.initNetwork(network);
1706
+ }
1707
+ /**
1708
+ * Retorna as propriedades tipo e status da conexão do dispositivo no momento da chamada.
1709
+ *
1710
+ * @returns {PoNetworkStatus} Instância de [PoNetworkStatus](/documentation/po-network-status) com as
1711
+ * propriedades da conexão.
1712
+ */
1713
+ getConnectionStatus() {
1714
+ this.poNetworkStatus = new PoNetworkStatus(this.networkType);
1715
+ return this.poNetworkStatus;
1716
+ }
1717
+ /**
1718
+ * Notifica as mudanças no tipo de conexão de rede do dispositivo.
1719
+ *
1720
+ * @returns {Observable<{ status: boolean, type: string }>} Observable com as propriedades da conexão.
1721
+ */
1722
+ onChange() {
1723
+ return this.networkTypeNow.asObservable();
1724
+ }
1725
+ getNavigatorStatus() {
1726
+ return merge(fromEvent(window, 'offline').pipe(mapTo(false)), fromEvent(window, 'online').pipe(mapTo(true)), Observable.create(sub => {
1727
+ sub.next(navigator.onLine);
1728
+ sub.complete();
1729
+ }));
1730
+ }
1731
+ initNetwork(network) {
1732
+ this.networkTypeNow = new Subject();
1733
+ this.initSubscriber(network);
1734
+ }
1735
+ initSubscriber(network) {
1736
+ if (network) {
1737
+ this.getNavigatorStatus().subscribe(status => {
1738
+ this.networkType = network.type;
1739
+ this.networkTypeNow.next({ status: status, type: this.networkType });
1740
+ });
1741
+ }
1742
+ }
1743
+ }
1744
+ PoNetworkService.ɵfac = function PoNetworkService_Factory(t) { return new (t || PoNetworkService)(i0.ɵɵinject(i1$2.Network)); };
1745
+ PoNetworkService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoNetworkService, factory: PoNetworkService.ɵfac });
1746
+ (function () {
1747
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoNetworkService, [{
1748
+ type: Injectable
1749
+ }], function () { return [{ type: i1$2.Network }]; }, null);
1750
+ })();
1747
1751
 
1748
- /**
1749
- * @description
1750
- *
1751
- * O `PoSyncService` é utilizado para configurar toda a base de dados que receberá as informações que serão
1752
- * armazenadas *offline* vindas do servidor. Nele ocorre toda a preparação dos modelos de dados retornados por
1753
- * cada consulta.
1754
- */
1755
- class PoSyncService {
1756
- constructor(poEventSourcingService, poHttpClient, poNetworkService, poSchemaDefinitionService, poSchemaService) {
1757
- this.poEventSourcingService = poEventSourcingService;
1758
- this.poHttpClient = poHttpClient;
1759
- this.poNetworkService = poNetworkService;
1760
- this.poSchemaDefinitionService = poSchemaDefinitionService;
1761
- this.poSchemaService = poSchemaService;
1762
- this.models = [];
1763
- this.finishSyncSubject = new Subject();
1764
- this.isSyncEnabled = true;
1765
- this.syncing = false;
1766
- }
1767
- /**
1768
- * Destrói todas as chaves do *storage* referentes ao `po-sync`, ou seja,
1769
- * as definições dos *schemas*, os registros de cada *schema* e a fila
1770
- * de eventos que estão para ser enviados ao servidor *(EventSourcing)*.
1771
- *
1772
- * > Para que não venham ocorrer erros em ações que dependam das definições dos *schemas*,
1773
- * recomenda-se utilizar o método `prepare()` em seguida.
1774
- *
1775
- * > Veja mais detalhes em [Fundamentos do PO Sync - Alterando as definições dos schemas](/guides/sync-fundamentals).
1776
- *
1777
- * @returns {Promise<any>} Promessa que é resolvida quando as chaves referentes ao `po-sync` forem destruídas.
1778
- */
1779
- destroy() {
1780
- return __awaiter(this, void 0, void 0, function* () {
1781
- const destroyFunction = () => __awaiter(this, void 0, void 0, function* () {
1782
- yield this.poSchemaService.destroySchemasRecords();
1783
- yield this.poSchemaDefinitionService.destroy();
1784
- yield this.poEventSourcingService.destroyEventSourcingQueue();
1785
- });
1786
- return this.poSchemaService.limitedCallWrap(destroyFunction);
1787
- });
1788
- }
1789
- /**
1790
- * Desabilita todos os tipos de sincronização de dados (periódica, reativa e manual).
1791
- *
1792
- * > Para habilitar novamente a sincronização utilize o método [`PoSyncService.enableSync()`](documentation/po-sync#enable-sync).
1793
- */
1794
- disableSync() {
1795
- this.isSyncEnabled = false;
1796
- if (this.timer && this.subscription) {
1797
- this.subscription.unsubscribe();
1798
- }
1799
- }
1800
- /**
1801
- * <a id="enable-sync"></a>
1802
- * Habilita todos os tipos de sincronização de dados (periódica, reativa e manual).
1803
- *
1804
- * Por padrão, sempre que se inicializa uma aplicação com PO Sync as sincronizações já estão habilitadas.
1805
- */
1806
- enableSync() {
1807
- this.isSyncEnabled = true;
1808
- this.createSubscribe();
1809
- }
1810
- /**
1811
- * Método que disponibiliza a partir de sua inscrição o evento de retorno das operações da fila de eventos que
1812
- * foram enviadas ao servidor. A cada operação enviada para o servidor, será disparado um evento para a inscrição
1813
- * deste método.
1814
- *
1815
- * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1816
- *
1817
- * @returns {Observable<PoSyncResponse>} Observable com um objeto do tipo `PoSyncResponse`.
1818
- */
1819
- getResponses() {
1820
- return this.poEventSourcingService.responsesSubject();
1821
- }
1822
- /**
1823
- * Retorna uma instância de `PoEntity` para um determinado *schema*.
1824
- *
1825
- * > Veja mais detalhes em [Fundamentos do PO Sync - Manipulando os registros de um schema](/guides/sync-fundamentals).
1826
- *
1827
- * @param {string} schemaName Nome do *schema*.
1828
- * @returns {PoEntity} Objeto para efetuar consultas e alterações nos dados.
1829
- */
1830
- getModel(schemaName) {
1831
- const model = this.models[schemaName];
1832
- if (!model) {
1833
- throw new Error('Model not found: ' + schemaName);
1834
- }
1835
- return model;
1836
- }
1837
- /**
1838
- * Insere uma requisição HTTP na fila de eventos do `po-sync`.
1839
- *
1840
- * > Veja mais detalhes em [Fundamentos do PO Sync - Inserindo requisições HTTP na fila de eventos](/guides/sync-fundamentals).
1841
- *
1842
- * @param {PoHttpRequestData} poHttpRequestData Dados da requisição HTTP.
1843
- * @param {string} customRequestId Identificador customizado da requisição HTTP.
1844
- * @returns {Promise<number>} Promessa com o identificador da requisição HTTP criada.
1845
- */
1846
- insertHttpCommand(requestData, customRequestId) {
1847
- validateParameter({ requestData });
1848
- return this.poEventSourcingService.httpCommand(requestData, customRequestId);
1849
- }
1850
- /**
1851
- * Efetua uma chamada na API do servidor para realizar a carga inicial dos dados. Deve ser chamado apenas uma vez
1852
- * na aplicação, após a preparação dos *schemas* realizada através do método `PoSyncService.prepare()`.
1853
- *
1854
- * > Veja mais detalhes em [Fundamentos do PO Sync - Carga inicial dos dados](/guides/sync-fundamentals).
1855
- *
1856
- * @returns {Observable<Array<{ entity: string, data: Array<any> }>>} Observable que notificará quando a
1857
- * carga inicial for concluída.
1858
- */
1859
- loadData() {
1860
- const loads = [];
1861
- this.schemas.forEach(el => loads.push(this.loadEntityData(el)));
1862
- return forkJoin(loads);
1863
- }
1864
- /**
1865
- * Responsável por notificar sempre que houver sincronismo.
1866
- *
1867
- * > Veja mais detalhes em [Fundamentos do PO Sync - Notificação pós-sincronização](/guides/sync-fundamentals).
1868
- *
1869
- * @returns {Observable<any>} Observable que é disparado a cada sincronismo realizado.
1870
- */
1871
- onSync() {
1872
- if (!this.eventSub) {
1873
- this.eventSub = Observable.create(e => {
1874
- this.emitter = e;
1875
- });
1876
- }
1877
- return this.eventSub;
1878
- }
1879
- /**
1880
- * Prepara a aplicação criando os schemas e aplica as configurações.
1881
- *
1882
- * > Veja mais detalhes em [Fundamentos do PO Sync - Preparando a aplicação](/guides/sync-fundamentals).
1883
- *
1884
- * @param {Array<PoSyncSchema>} schemas Lista de *schemas* a serem preparados.
1885
- * @param {PoSyncConfig} config Configurações adicionais.
1886
- * @returns {Promise<any>} Promessa que é resolvida quando a aplicação estiver preparada para a utilização do `po-sync`.
1887
- */
1888
- prepare(schemas, config) {
1889
- validateArray({ schemas });
1890
- const defaultSyncConfig = {
1891
- type: this.poNetworkService.getConnectionStatus().type,
1892
- period: 60,
1893
- dataTransform: new PoDataMessage()
1894
- };
1895
- this.schemas = schemas;
1896
- this.config = config || defaultSyncConfig;
1897
- this.config.dataTransform = this.config.dataTransform || new PoDataMessage();
1898
- this.poEventSourcingService.config = this.config;
1899
- this.startTimer(this.config.period);
1900
- this.reactiveSync();
1901
- this.poEventSourcingService.onSaveData().subscribe(() => this.sync());
1902
- return this.saveSchemas().then(() => {
1903
- this.schemas.forEach(schema => {
1904
- this.models[schema.name] = new PoEntity(this.poEventSourcingService, schema, this.poSchemaService);
1905
- });
1906
- return Promise.resolve();
1907
- });
1908
- }
1909
- /**
1910
- * Remove um item da fila de eventos que espera a sincronização.
1911
- *
1912
- * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1913
- *
1914
- * @param {any} idEventSourcing Identificador do item da fila de eventos.
1915
- * @returns {Promise<any>} Promessa que é resolvida quando o item da fila de eventos é removido.
1916
- */
1917
- removeItemOfSync(idEventSourcing) {
1918
- return this.poEventSourcingService.removeEventSourcingItem(idEventSourcing);
1919
- }
1920
- /**
1921
- * Reenvia os comandos pendentes na fila (inclusão, alteração e exclusão) e busca novos dados do servidor.
1922
- *
1923
- * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1924
- *
1925
- * @returns {Promise<any>} Promessa que resolve o sincronismo disparado.
1926
- */
1927
- resumeSync() {
1928
- if (!this.canSync()) {
1929
- const finishSyncSubscription = this.finishSyncSubject.asObservable().subscribe(() => {
1930
- finishSyncSubscription.unsubscribe();
1931
- return this.sync();
1932
- });
1933
- return Promise.resolve();
1934
- }
1935
- return this.sync();
1936
- }
1937
- /**
1938
- * Dispara o sincronismo enviando os eventos pendentes (inclusão, alteração e exclusão) e buscando novos dados do servidor.
1939
- *
1940
- * O sincronismo somente será executado depois que o acesso a base de dados local do dispositivo for liberada.
1941
- *
1942
- * > Veja mais detalhes em [Fundamentos do PO Sync - Sincronização manual](/guides/sync-fundamentals).
1943
- *
1944
- * @returns {Promise<any>} Promessa que é resolvida quando o sincronismo for finalizado.
1945
- */
1946
- sync() {
1947
- return __awaiter(this, void 0, void 0, function* () {
1948
- if (this.canSync()) {
1949
- this.startSync();
1950
- try {
1951
- yield this.poEventSourcingService.syncSend();
1952
- yield this.poEventSourcingService.syncGet();
1953
- if (this.emitter) {
1954
- this.emitter.next();
1955
- }
1956
- this.finishSync();
1957
- }
1958
- catch (error) {
1959
- this.syncError();
1960
- }
1961
- }
1962
- });
1963
- }
1964
- canSync() {
1965
- if (this.syncing || !this.isSyncEnabled) {
1966
- return false;
1967
- }
1968
- else {
1969
- const currentConnection = this.poNetworkService.getConnectionStatus();
1970
- const isConfiguredConnection = this.config && currentConnection.type === this.config.type;
1971
- const isConfigIncludesType = this.config && this.config.type instanceof Array && this.config.type.includes(currentConnection.type);
1972
- return currentConnection.status && (!this.config || isConfiguredConnection || isConfigIncludesType);
1973
- }
1974
- }
1975
- createSubscribe() {
1976
- if (this.timer) {
1977
- this.subscription = this.timer.subscribe(() => {
1978
- this.sync().then(() => {
1979
- this.subscription.unsubscribe();
1980
- this.subscription = null;
1981
- this.timer = null;
1982
- this.startTimer(this.config.period);
1983
- });
1984
- });
1985
- }
1986
- }
1987
- finishSync() {
1988
- this.syncing = false;
1989
- this.finishSyncSubject.next();
1990
- }
1991
- getOnePage(schema, page = 1) {
1992
- const params = [];
1993
- params.push(`${this.config.dataTransform.getPageSizeParamName()}=${schema.pageSize}`);
1994
- params.push(`${this.config.dataTransform.getPageParamName()}=${page}`);
1995
- const url = `${PoSchemaUtil.getUrl(schema, PoRequestType.GET)}?${params.join('&')}`;
1996
- return this.poHttpClient.get(url).pipe(map(response => response.body), mergeMap(responseBody => {
1997
- const now = new Date().getTime();
1998
- responseBody[this.config.dataTransform.getItemsFieldName()].map(item => {
1999
- item.SyncInsertedDateTime = now;
2000
- item.SyncUpdatedDateTime = null;
2001
- item.SyncExclusionDateTime = null;
2002
- item.SyncDeleted = false;
2003
- item.SyncStatus = 2;
2004
- });
2005
- return this.poSchemaService
2006
- .updateAll(schema, responseBody[this.config.dataTransform.getItemsFieldName()])
2007
- .then(() => responseBody);
2008
- }));
2009
- }
2010
- loadEntityData(schema) {
2011
- let page = 1;
2012
- return this.getOnePage(schema, page).pipe(expand(data => {
2013
- this.config.dataTransform.transform(data);
2014
- const hasNext = this.config.dataTransform.hasNext();
2015
- if (hasNext) {
2016
- return this.getOnePage(schema, ++page);
2017
- }
2018
- else {
2019
- return of();
2020
- }
2021
- }), reduce((acc, obj) => {
2022
- acc.data = acc.data.concat(obj[this.config.dataTransform.getItemsFieldName()]);
2023
- return acc;
2024
- }, {
2025
- entity: schema.name,
2026
- data: []
2027
- }));
2028
- }
2029
- reactiveSync() {
2030
- this.poNetworkService.onChange().subscribe(networkStatus => {
2031
- if (networkStatus.status) {
2032
- this.startTimer(this.config.period);
2033
- return this.sync();
2034
- }
2035
- if (this.subscription) {
2036
- this.subscription.unsubscribe();
2037
- }
2038
- });
2039
- }
2040
- saveSchemas() {
2041
- return __awaiter(this, void 0, void 0, function* () {
2042
- const storageSchemas = yield this.poSchemaDefinitionService.getAll();
2043
- this.schemas.forEach(schema => (schema.lastSync = PoSchemaUtil.getLastSync(storageSchemas, schema.name)));
2044
- return this.poSchemaDefinitionService.saveAll(this.schemas);
2045
- });
2046
- }
2047
- startSync() {
2048
- this.syncing = true;
2049
- }
2050
- startTimer(period) {
2051
- if (period && this.isSyncEnabled) {
2052
- this.timer = timer(period * 1000);
2053
- this.createSubscribe();
2054
- }
2055
- }
2056
- syncError() {
2057
- this.finishSync();
2058
- }
2059
- }
2060
- PoSyncService.decorators = [
2061
- { type: Injectable }
2062
- ];
2063
- PoSyncService.ctorParameters = () => [
2064
- { type: PoEventSourcingService },
2065
- { type: PoHttpClientService },
2066
- { type: PoNetworkService },
2067
- { type: PoSchemaDefinitionService },
2068
- { type: PoSchemaService }
2069
- ];
1752
+ /**
1753
+ * @description
1754
+ *
1755
+ * O `PoSyncService` é utilizado para configurar toda a base de dados que receberá as informações que serão
1756
+ * armazenadas *offline* vindas do servidor. Nele ocorre toda a preparação dos modelos de dados retornados por
1757
+ * cada consulta.
1758
+ */
1759
+ class PoSyncService {
1760
+ constructor(poEventSourcingService, poHttpClient, poNetworkService, poSchemaDefinitionService, poSchemaService) {
1761
+ this.poEventSourcingService = poEventSourcingService;
1762
+ this.poHttpClient = poHttpClient;
1763
+ this.poNetworkService = poNetworkService;
1764
+ this.poSchemaDefinitionService = poSchemaDefinitionService;
1765
+ this.poSchemaService = poSchemaService;
1766
+ this.models = [];
1767
+ this.finishSyncSubject = new Subject();
1768
+ this.isSyncEnabled = true;
1769
+ this.syncing = false;
1770
+ }
1771
+ /**
1772
+ * Destrói todas as chaves do *storage* referentes ao `po-sync`, ou seja,
1773
+ * as definições dos *schemas*, os registros de cada *schema* e a fila
1774
+ * de eventos que estão para ser enviados ao servidor *(EventSourcing)*.
1775
+ *
1776
+ * > Para que não venham ocorrer erros em ações que dependam das definições dos *schemas*,
1777
+ * recomenda-se utilizar o método `prepare()` em seguida.
1778
+ *
1779
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Alterando as definições dos schemas](/guides/sync-fundamentals).
1780
+ *
1781
+ * @returns {Promise<any>} Promessa que é resolvida quando as chaves referentes ao `po-sync` forem destruídas.
1782
+ */
1783
+ destroy() {
1784
+ return __awaiter(this, void 0, void 0, function* () {
1785
+ const destroyFunction = () => __awaiter(this, void 0, void 0, function* () {
1786
+ yield this.poSchemaService.destroySchemasRecords();
1787
+ yield this.poSchemaDefinitionService.destroy();
1788
+ yield this.poEventSourcingService.destroyEventSourcingQueue();
1789
+ });
1790
+ return this.poSchemaService.limitedCallWrap(destroyFunction);
1791
+ });
1792
+ }
1793
+ /**
1794
+ * Desabilita todos os tipos de sincronização de dados (periódica, reativa e manual).
1795
+ *
1796
+ * > Para habilitar novamente a sincronização utilize o método [`PoSyncService.enableSync()`](documentation/po-sync#enable-sync).
1797
+ */
1798
+ disableSync() {
1799
+ this.isSyncEnabled = false;
1800
+ if (this.timer && this.subscription) {
1801
+ this.subscription.unsubscribe();
1802
+ }
1803
+ }
1804
+ /**
1805
+ * <a id="enable-sync"></a>
1806
+ * Habilita todos os tipos de sincronização de dados (periódica, reativa e manual).
1807
+ *
1808
+ * Por padrão, sempre que se inicializa uma aplicação com PO Sync as sincronizações já estão habilitadas.
1809
+ */
1810
+ enableSync() {
1811
+ this.isSyncEnabled = true;
1812
+ this.createSubscribe();
1813
+ }
1814
+ /**
1815
+ * Método que disponibiliza a partir de sua inscrição o evento de retorno das operações da fila de eventos que
1816
+ * foram enviadas ao servidor. A cada operação enviada para o servidor, será disparado um evento para a inscrição
1817
+ * deste método.
1818
+ *
1819
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1820
+ *
1821
+ * @returns {Observable<PoSyncResponse>} Observable com um objeto do tipo `PoSyncResponse`.
1822
+ */
1823
+ getResponses() {
1824
+ return this.poEventSourcingService.responsesSubject();
1825
+ }
1826
+ /**
1827
+ * Retorna uma instância de `PoEntity` para um determinado *schema*.
1828
+ *
1829
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Manipulando os registros de um schema](/guides/sync-fundamentals).
1830
+ *
1831
+ * @param {string} schemaName Nome do *schema*.
1832
+ * @returns {PoEntity} Objeto para efetuar consultas e alterações nos dados.
1833
+ */
1834
+ getModel(schemaName) {
1835
+ const model = this.models[schemaName];
1836
+ if (!model) {
1837
+ throw new Error('Model not found: ' + schemaName);
1838
+ }
1839
+ return model;
1840
+ }
1841
+ /**
1842
+ * Insere uma requisição HTTP na fila de eventos do `po-sync`.
1843
+ *
1844
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Inserindo requisições HTTP na fila de eventos](/guides/sync-fundamentals).
1845
+ *
1846
+ * @param {PoHttpRequestData} poHttpRequestData Dados da requisição HTTP.
1847
+ * @param {string} customRequestId Identificador customizado da requisição HTTP.
1848
+ * @returns {Promise<number>} Promessa com o identificador da requisição HTTP criada.
1849
+ */
1850
+ insertHttpCommand(requestData, customRequestId) {
1851
+ validateParameter({ requestData });
1852
+ return this.poEventSourcingService.httpCommand(requestData, customRequestId);
1853
+ }
1854
+ /**
1855
+ * Efetua uma chamada na API do servidor para realizar a carga inicial dos dados. Deve ser chamado apenas uma vez
1856
+ * na aplicação, após a preparação dos *schemas* realizada através do método `PoSyncService.prepare()`.
1857
+ *
1858
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Carga inicial dos dados](/guides/sync-fundamentals).
1859
+ *
1860
+ * @returns {Observable<Array<{ entity: string, data: Array<any> }>>} Observable que notificará quando a
1861
+ * carga inicial for concluída.
1862
+ */
1863
+ loadData() {
1864
+ const loads = [];
1865
+ this.schemas.forEach(el => loads.push(this.loadEntityData(el)));
1866
+ return forkJoin(loads);
1867
+ }
1868
+ /**
1869
+ * Responsável por notificar sempre que houver sincronismo.
1870
+ *
1871
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Notificação pós-sincronização](/guides/sync-fundamentals).
1872
+ *
1873
+ * @returns {Observable<any>} Observable que é disparado a cada sincronismo realizado.
1874
+ */
1875
+ onSync() {
1876
+ if (!this.eventSub) {
1877
+ this.eventSub = Observable.create(e => {
1878
+ this.emitter = e;
1879
+ });
1880
+ }
1881
+ return this.eventSub;
1882
+ }
1883
+ /**
1884
+ * Prepara a aplicação criando os schemas e aplica as configurações.
1885
+ *
1886
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Preparando a aplicação](/guides/sync-fundamentals).
1887
+ *
1888
+ * @param {Array<PoSyncSchema>} schemas Lista de *schemas* a serem preparados.
1889
+ * @param {PoSyncConfig} config Configurações adicionais.
1890
+ * @returns {Promise<any>} Promessa que é resolvida quando a aplicação estiver preparada para a utilização do `po-sync`.
1891
+ */
1892
+ prepare(schemas, config) {
1893
+ validateArray({ schemas });
1894
+ const defaultSyncConfig = {
1895
+ type: this.poNetworkService.getConnectionStatus().type,
1896
+ period: 60,
1897
+ dataTransform: new PoDataMessage()
1898
+ };
1899
+ this.schemas = schemas;
1900
+ this.config = config || defaultSyncConfig;
1901
+ this.config.dataTransform = this.config.dataTransform || new PoDataMessage();
1902
+ this.poEventSourcingService.config = this.config;
1903
+ this.startTimer(this.config.period);
1904
+ this.reactiveSync();
1905
+ this.poEventSourcingService.onSaveData().subscribe(() => this.sync());
1906
+ return this.saveSchemas().then(() => {
1907
+ this.schemas.forEach(schema => {
1908
+ this.models[schema.name] = new PoEntity(this.poEventSourcingService, schema, this.poSchemaService);
1909
+ });
1910
+ return Promise.resolve();
1911
+ });
1912
+ }
1913
+ /**
1914
+ * Remove um item da fila de eventos que espera a sincronização.
1915
+ *
1916
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1917
+ *
1918
+ * @param {any} idEventSourcing Identificador do item da fila de eventos.
1919
+ * @returns {Promise<any>} Promessa que é resolvida quando o item da fila de eventos é removido.
1920
+ */
1921
+ removeItemOfSync(idEventSourcing) {
1922
+ return this.poEventSourcingService.removeEventSourcingItem(idEventSourcing);
1923
+ }
1924
+ /**
1925
+ * Reenvia os comandos pendentes na fila (inclusão, alteração e exclusão) e busca novos dados do servidor.
1926
+ *
1927
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Capturando respostas da sincronização](/guides/sync-fundamentals).
1928
+ *
1929
+ * @returns {Promise<any>} Promessa que resolve o sincronismo disparado.
1930
+ */
1931
+ resumeSync() {
1932
+ if (!this.canSync()) {
1933
+ const finishSyncSubscription = this.finishSyncSubject.asObservable().subscribe(() => {
1934
+ finishSyncSubscription.unsubscribe();
1935
+ return this.sync();
1936
+ });
1937
+ return Promise.resolve();
1938
+ }
1939
+ return this.sync();
1940
+ }
1941
+ /**
1942
+ * Dispara o sincronismo enviando os eventos pendentes (inclusão, alteração e exclusão) e buscando novos dados do servidor.
1943
+ *
1944
+ * O sincronismo somente será executado depois que o acesso a base de dados local do dispositivo for liberada.
1945
+ *
1946
+ * > Veja mais detalhes em [Fundamentos do PO Sync - Sincronização manual](/guides/sync-fundamentals).
1947
+ *
1948
+ * @returns {Promise<any>} Promessa que é resolvida quando o sincronismo for finalizado.
1949
+ */
1950
+ sync() {
1951
+ return __awaiter(this, void 0, void 0, function* () {
1952
+ if (this.canSync()) {
1953
+ this.startSync();
1954
+ try {
1955
+ yield this.poEventSourcingService.syncSend();
1956
+ yield this.poEventSourcingService.syncGet();
1957
+ if (this.emitter) {
1958
+ this.emitter.next();
1959
+ }
1960
+ this.finishSync();
1961
+ }
1962
+ catch (error) {
1963
+ this.syncError();
1964
+ }
1965
+ }
1966
+ });
1967
+ }
1968
+ canSync() {
1969
+ if (this.syncing || !this.isSyncEnabled) {
1970
+ return false;
1971
+ }
1972
+ else {
1973
+ const currentConnection = this.poNetworkService.getConnectionStatus();
1974
+ const isConfiguredConnection = this.config && currentConnection.type === this.config.type;
1975
+ const isConfigIncludesType = this.config && this.config.type instanceof Array && this.config.type.includes(currentConnection.type);
1976
+ return currentConnection.status && (!this.config || isConfiguredConnection || isConfigIncludesType);
1977
+ }
1978
+ }
1979
+ createSubscribe() {
1980
+ if (this.timer) {
1981
+ this.subscription = this.timer.subscribe(() => {
1982
+ this.sync().then(() => {
1983
+ this.subscription.unsubscribe();
1984
+ this.subscription = null;
1985
+ this.timer = null;
1986
+ this.startTimer(this.config.period);
1987
+ });
1988
+ });
1989
+ }
1990
+ }
1991
+ finishSync() {
1992
+ this.syncing = false;
1993
+ this.finishSyncSubject.next(null);
1994
+ }
1995
+ getOnePage(schema, page = 1) {
1996
+ const params = [];
1997
+ params.push(`${this.config.dataTransform.getPageSizeParamName()}=${schema.pageSize}`);
1998
+ params.push(`${this.config.dataTransform.getPageParamName()}=${page}`);
1999
+ const url = `${PoSchemaUtil.getUrl(schema, PoRequestType.GET)}?${params.join('&')}`;
2000
+ return this.poHttpClient.get(url).pipe(map(response => response.body), mergeMap(responseBody => {
2001
+ const now = new Date().getTime();
2002
+ responseBody[this.config.dataTransform.getItemsFieldName()].map(item => {
2003
+ item.SyncInsertedDateTime = now;
2004
+ item.SyncUpdatedDateTime = null;
2005
+ item.SyncExclusionDateTime = null;
2006
+ item.SyncDeleted = false;
2007
+ item.SyncStatus = 2;
2008
+ });
2009
+ return this.poSchemaService
2010
+ .updateAll(schema, responseBody[this.config.dataTransform.getItemsFieldName()])
2011
+ .then(() => responseBody);
2012
+ }));
2013
+ }
2014
+ loadEntityData(schema) {
2015
+ let page = 1;
2016
+ return this.getOnePage(schema, page).pipe(expand(data => {
2017
+ this.config.dataTransform.transform(data);
2018
+ const hasNext = this.config.dataTransform.hasNext();
2019
+ if (hasNext) {
2020
+ return this.getOnePage(schema, ++page);
2021
+ }
2022
+ else {
2023
+ return of();
2024
+ }
2025
+ }), reduce((acc, obj) => {
2026
+ acc.data = acc.data.concat(obj[this.config.dataTransform.getItemsFieldName()]);
2027
+ return acc;
2028
+ }, {
2029
+ entity: schema.name,
2030
+ data: []
2031
+ }));
2032
+ }
2033
+ reactiveSync() {
2034
+ this.poNetworkService.onChange().subscribe(networkStatus => {
2035
+ if (networkStatus.status) {
2036
+ this.startTimer(this.config.period);
2037
+ return this.sync();
2038
+ }
2039
+ if (this.subscription) {
2040
+ this.subscription.unsubscribe();
2041
+ }
2042
+ });
2043
+ }
2044
+ saveSchemas() {
2045
+ return __awaiter(this, void 0, void 0, function* () {
2046
+ const storageSchemas = yield this.poSchemaDefinitionService.getAll();
2047
+ this.schemas.forEach(schema => (schema.lastSync = PoSchemaUtil.getLastSync(storageSchemas, schema.name)));
2048
+ return this.poSchemaDefinitionService.saveAll(this.schemas);
2049
+ });
2050
+ }
2051
+ startSync() {
2052
+ this.syncing = true;
2053
+ }
2054
+ startTimer(period) {
2055
+ if (period && this.isSyncEnabled) {
2056
+ this.timer = timer(period * 1000);
2057
+ this.createSubscribe();
2058
+ }
2059
+ }
2060
+ syncError() {
2061
+ this.finishSync();
2062
+ }
2063
+ }
2064
+ PoSyncService.ɵfac = function PoSyncService_Factory(t) { return new (t || PoSyncService)(i0.ɵɵinject(PoEventSourcingService), i0.ɵɵinject(PoHttpClientService), i0.ɵɵinject(PoNetworkService), i0.ɵɵinject(PoSchemaDefinitionService), i0.ɵɵinject(PoSchemaService)); };
2065
+ PoSyncService.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable({ token: PoSyncService, factory: PoSyncService.ɵfac });
2066
+ (function () {
2067
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoSyncService, [{
2068
+ type: Injectable
2069
+ }], function () { return [{ type: PoEventSourcingService }, { type: PoHttpClientService }, { type: PoNetworkService }, { type: PoSchemaDefinitionService }, { type: PoSchemaService }]; }, null);
2070
+ })();
2070
2071
 
2071
- /**
2072
- * @description
2073
- *
2074
- * Módulo do componente PoSync responsável pela sincronia de dados com backends
2075
- */
2076
- class PoSyncModule {
2077
- }
2078
- PoSyncModule.decorators = [
2079
- { type: NgModule, args: [{
2080
- providers: [
2081
- PoEventSourcingService,
2082
- PoNetworkService,
2083
- PoSchemaDefinitionService,
2084
- PoSchemaService,
2085
- PoSyncService,
2086
- PoHttpClientService,
2087
- Network
2088
- ],
2089
- imports: [HttpClientModule]
2090
- },] }
2091
- ];
2072
+ /**
2073
+ * @description
2074
+ *
2075
+ * Módulo do componente PoSync responsável pela sincronia de dados com backends
2076
+ */
2077
+ class PoSyncModule {
2078
+ }
2079
+ PoSyncModule.ɵfac = function PoSyncModule_Factory(t) { return new (t || PoSyncModule)(); };
2080
+ PoSyncModule.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: PoSyncModule });
2081
+ PoSyncModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ providers: [
2082
+ PoEventSourcingService,
2083
+ PoNetworkService,
2084
+ PoSchemaDefinitionService,
2085
+ PoSchemaService,
2086
+ PoSyncService,
2087
+ PoHttpClientService,
2088
+ Network
2089
+ ], imports: [[HttpClientModule]] });
2090
+ (function () {
2091
+ (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PoSyncModule, [{
2092
+ type: NgModule,
2093
+ args: [{
2094
+ providers: [
2095
+ PoEventSourcingService,
2096
+ PoNetworkService,
2097
+ PoSchemaDefinitionService,
2098
+ PoSchemaService,
2099
+ PoSyncService,
2100
+ PoHttpClientService,
2101
+ Network
2102
+ ],
2103
+ imports: [HttpClientModule]
2104
+ }]
2105
+ }], null, null);
2106
+ })();
2107
+ (function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(PoSyncModule, { imports: [HttpClientModule] }); })();
2092
2108
 
2093
- /**
2094
- * Generated bundle index. Do not edit.
2109
+ /**
2110
+ * Generated bundle index. Do not edit.
2095
2111
  */
2096
2112
 
2097
- export { PoDataTransform, PoEntity, PoEventSourcingErrorResponse, PoEventSourcingService, PoHttpClientService, PoHttpRequestType, PoNetworkService, PoNetworkType, PoSyncModule, PoSyncService, PoEventSourcingService as ɵa, PoSchemaService as ɵb, PoSchemaDefinitionService as ɵc, PoSchemaService as ɵd };
2098
- //# sourceMappingURL=po-ui-ng-sync.js.map
2113
+ export { PoDataTransform, PoEntity, PoEventSourcingErrorResponse, PoEventSourcingService, PoHttpClientService, PoHttpRequestType, PoNetworkService, PoNetworkType, PoSyncModule, PoSyncService };
2114
+ //# sourceMappingURL=po-ui-ng-sync.mjs.map