@po-ui/ng-sync 15.15.0 → 16.0.0-next.2

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