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