ixc-orm 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,4 +1,6 @@
1
1
  # 🔄 CHANGELOG
2
+ - [v1.7.0 - 10 de outubro de 2025](#v170)
3
+ - [v1.6.0 - 16 de agosto de 2025](#v150)
2
4
  - [v1.5.0 - 16 de agosto de 2025](#v150)
3
5
  - [v1.4.4 - 15 de agosto de 2025](#v144)
4
6
  - [v1.4.3 - 15 de agosto de 2025](#v143)
@@ -6,6 +8,19 @@
6
8
 
7
9
  ## 🚀 Novidades
8
10
 
11
+ ### v1.7.0
12
+ * **Atualização:** Novas classes adiconadas, para simplificar a manipulação dos filtros de busca e das respostas da API do **IXC Provedor**.
13
+ * A nova classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/IxcOrm.ts">IxcOrm</a> pode substituir a classe `IXCCliente` e fornece uma maneira mais dinâmica de construir a query de busca, através dos métodos `where()`, `like()`, `exactly()`, `lessThan()`, `lessThanEquals()`, `greaterThan()` e `greaterThanEquals()`.
14
+ * Toda a lógica de manipulação das requisições HTTP foi movida para a nova classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/api/RequestEmitter.ts">RequestEmitter</a>, deixando a classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/IxcOrm.ts">IxcOrm</a> apenas com a lógica de manipulação da query de busca.
15
+ * Os dados da resposta recebida da API do IXC Provedor agora estão todos concentrados na classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/IxcResponse.ts">IxcResponse</a>, quando instanciada pelos métodos `GET()`, `POST()`, `PUT()` e `DELETE()`, da classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/api/RequestEmitter.ts">RequestEmitter</a>.
16
+ * A classe <a href="https://github.com/SousaFelipe/ixc-orm/blob/builders/src/IxcOrm.ts">IxcOrm</a> é uma subclasse de <a href="https://github.com/SousaFelipe/ixcorm/blob/builders/src/api/RequestEmitter.ts">RequestEmitter</a>.
17
+
18
+ ### v1.6.0
19
+ * **Melhoria**: Métodos específicos para chamadas de recursos da API do **IXC Provedor**
20
+ * `desbloqueioDeConfianca()`: Envia uma requisição para o recurso de desbloqueio de confiança de um contrato.
21
+ * `liberacaoTemporaria()`: Envia uma requisição para o recurso de liberação temporária de um contrato.
22
+ * `getArquivoBoleto()`: Recupera o arquivo de uma fatura, no formato PDF, codificado em <a href="https://en.wikipedia.org/wiki/Base64">Base64</a>.
23
+
9
24
  ### v1.5.0
10
25
  * **Melhoria:** A chamada de recursos da API agora pode ser feita de forma mais simplificada, através da função `RecursoIXC`:
11
26
  * Basta importar assim: `import { RecursoIXC } from 'ixc-orm'`;
@@ -21,4 +36,4 @@
21
36
  * **Correção:** Resolvido o bug de leitura das variáveis de ambiente no arquivo .env da pasta raiz do projeto.
22
37
  * **Melhoria:** Foram adicionados 3 dos 44 recursos da API do IXC: `get_boleto`, `liberacao_temporaria` e `desbloqueio_confianca`. (Futuramente novos recursos serão adicionados)
23
38
 
24
- > Consulte todos os recursos disponíveis: [Doc. API IXCSoft](https://wikiapiprovedor.ixcsoft.com.br/)
39
+ > Consulte todos os recursos disponíveis: [Doc. API IXCSoft](https://wikiapiprovedor.ixcsoft.com.br/)
package/README.md CHANGED
@@ -1,8 +1,16 @@
1
- # IXC-ORM [![npm](https://img.shields.io/npm/dt/ixc-orm.svg)](https://www.npmjs.com/package/ixc-orm)
1
+ <div align="center">
2
+
3
+ # IXC-ORM
2
4
 
3
- Este ORM visa facilitar o consumo de dados da API oficial do [IXC Provedor](https://ixcsoft.com/ixc-provedor).\
4
- Esta biblioteca não faz parte das bibliotecas oficiais da [IXCsoft](https://ixcsoft.com/) e foi desenvolvida de forma independente e sem fins lucrativos.
5
+ ![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?style=for-the-badge&logo=typescript&logoColor=white)
6
+ [![npm](https://img.shields.io/npm/dt/ixc-orm.svg?style=for-the-badge)](https://www.npmjs.com/package/ixc-orm)
7
+ ![Status](https://img.shields.io/badge/Status-Stable-brightgreen?style=for-the-badge)
8
+ ![NPM Version](https://img.shields.io/npm/v/ixc-orm?style=for-the-badge)
9
+
10
+ Esse ORM visa facilitar o consumo de dados da API oficial do [IXC Provedor](https://ixcsoft.com/ixc-provedor).\
11
+ Essa biblioteca não faz parte das bibliotecas oficiais da [IXCsoft](https://ixcsoft.com/) e foi desenvolvida de forma independente e sem fins lucrativos.
5
12
 
13
+ </div>
6
14
 
7
15
 
8
16
  ## Instalação
@@ -16,10 +24,24 @@ yarn add ixc-orm
16
24
  ```
17
25
 
18
26
 
27
+ ## Como utilizar
19
28
 
20
- ## Usando a biblioteca
29
+ As classes que representarão as tabelas dentro do banco de dados do seu servidor IXC, deverão herdar da classe `IxcOrm` (nova versão), como no exemplo a seguir:
21
30
 
22
- > As classes que representarão as tabelas dentro do banco de dados do seu servidor IXC, deverão herdar da classe `IXCClient`, como no exemplo a seguir:
31
+ > [!NOTE]\
32
+ > Versão 1.7.0 `stable`
33
+
34
+ ```typescript
35
+ import { IxcOrm } from 'ixc-orm';
36
+
37
+ class Contrato extends IxcOrm {
38
+ constructor() {
39
+ super('cliente_contrato');
40
+ }
41
+ }
42
+ ```
43
+
44
+ > Versão 1.6.0 ou anterior
23
45
 
24
46
  ```typescript
25
47
  import { IXCClient } 'ixc-orm';
@@ -31,7 +53,26 @@ class Contrato extends IXCClient {
31
53
  }
32
54
  ```
33
55
 
34
- > Após instanciar um objeto com o tipo que você criou (`Contrato, como no exemplo a cima`), você poderá acessar os métodos `where`, `orderBy`, `get`, `post` e `put`.
56
+ Após instanciar um objeto com o tipo que você criou (`Contrato, como no exemplo a cima`), você poderá acessar os métodos de construção da query de busca.
57
+
58
+ > [!NOTE]\
59
+ > Versão 1.7.0 `stable`
60
+
61
+ ```typescript
62
+ import { IxcResponse, Sort } from 'ixc-orm';
63
+
64
+ const contrato = new Contrato();
65
+
66
+ IxcResponse response = await contrato
67
+ .where('data_ativacao')
68
+ .greaterThanEquals('2024-09-24')
69
+ .orderBy('data_ativacao', Sort.DESC)
70
+ .GET();
71
+
72
+ const contratos = response.registros();
73
+ ```
74
+
75
+ > Versão 1.6.0 ou anterior
35
76
 
36
77
  ```typescript
37
78
  const contrato = new Contrato();
@@ -45,6 +86,9 @@ const contratos = await contrato
45
86
 
46
87
  Ou quando você já possui o ID do registro que procura, a opção mais simples será utilizar o método `find()`. Este método também está implementado na classe `IXCClient`
47
88
 
89
+ > [!NOTE]
90
+ > Método disponível apenas para as subclasses de `IXCClient`.
91
+
48
92
  ```typescript
49
93
  const contrato = new Contrato();
50
94
 
@@ -54,7 +98,6 @@ const contratos = await contrato.find(id_contrato)
54
98
  ```
55
99
 
56
100
 
57
-
58
101
  ## Recursos da API do IXC Provedor
59
102
 
60
103
  Existem alguns `endpoints` que a API do IXC disponibiliza, a fim de "encurtar o caminho" para chegar até algumas informações. Como por exemplo, obter o arquivo PDF de uma fatura.\
@@ -74,15 +117,38 @@ const response = await Recurso.desbloqueioDeConfianca(id_contrato);
74
117
  > Obs: Os nomes dos recursos estão de acordo com a API do **IXC Provedor** a fim de facilitar o estudo de sua documentação oficial.
75
118
 
76
119
 
77
-
78
120
  ## Variáveis de Ambiente
79
121
 
80
122
  Para configurar a comunicação da biblioteca com seu servidor IXC, é necessário adicionar as seguintes variáveis de ambiente a um arquivo `.env`, que esteja localizado no diretório raiz do seu projeto.
81
123
 
82
- > **IXC_HOST** A url do seu servidor IXC\
83
- > **IXC_TOKEN** Um token de API gerado dentro do próprio **IXC Provedor**
124
+ > [!NOTE]\
125
+ > Versão 1.7.0 `stable`
126
+
127
+ - **IXC_ACCESS_TOKEN** Um token de API gerado dentro do IXC Provedor.
128
+ - **IXC_SERVER_DOMAIN** O domínio do seu servidor IXC Provedor.
129
+
130
+ ```ini
131
+ IXC_ACCESS_TOKEN=conteúdo-do-token-gerado-dentro-do-ixC
132
+ IXC_SERVER_DOMAIN=www.dominio-do-seu-servidor-ixc.com.br
133
+ ```
134
+
135
+
136
+ > Versão 1.6.0 ou anterior:
137
+
138
+ - **IXC_HOST** A url do seu servidor **IXC Provedor**.
139
+ - **IXC_TOKEN** Um token de API gerado dentro do **IXC Provedor**.
84
140
 
85
141
  ```ini
86
142
  IXC_HOST="https://dominiodoservidorixc.com.br/webservice/v1"
87
143
  IXC_TOKEN="8:k4n8wk1946j7mimthei869cq1zz2u940f2gqobqg081y2oefl80mzhtq2wud3gqp"
88
144
  ```
145
+
146
+
147
+ # Contribuições
148
+
149
+ Contribuições são sempre bem-vindas!\
150
+ Se você conhece uma maneira melhor de fazer algo, por favor, me avise!
151
+ Caso contrário, é sempre melhor fazer um PR na branch main.
152
+
153
+ At.te,\
154
+ <b>Felipe S. Carmo</b>.
@@ -0,0 +1,81 @@
1
+ import { Sort } from './api/Ordering';
2
+ import RequestEmitter from './api/RequestEmitter';
3
+ export default abstract class IxcOrm extends RequestEmitter {
4
+ private ordering;
5
+ private pagination;
6
+ private parameters;
7
+ private parameterStub;
8
+ /**
9
+ * Método construtor da classe.
10
+ *
11
+ * @param table Representa o o nome da tabela que será manipulada, no IXC Provedor.
12
+ */
13
+ protected constructor(table: string);
14
+ /**
15
+ * Inicia um novo objeto de parâmetro de busca do filtro da grid.
16
+ *
17
+ * @param column O nome da coluna onde o filtro de busca será executado.
18
+ * @returns A própria instância.
19
+ */
20
+ where(column: string): IxcOrm;
21
+ /**
22
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**L**) = LIKE.
23
+ *
24
+ * @param value O valor a ser filtrado.
25
+ * @returns A própria instância.
26
+ */
27
+ like(value: string | number): IxcOrm;
28
+ /**
29
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**=**) = EQUALS.
30
+ *
31
+ * @param value O valor a ser filtrado.
32
+ * @returns A própria instância.
33
+ */
34
+ exactly(value: string | number): IxcOrm;
35
+ /**
36
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**<**) = LESS_THAN.
37
+ *
38
+ * @param value O valor a ser filtrado.
39
+ * @returns A própria instância.
40
+ */
41
+ lessThan(value: string | number): IxcOrm;
42
+ /**
43
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**<=**) = LESS_THAN_EQUALS.
44
+ *
45
+ * @param value O valor a ser filtrado.
46
+ * @returns A própria instância.
47
+ */
48
+ lessThanEquals(value: string | number): IxcOrm;
49
+ /**
50
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**>**) = GREATER_THAN.
51
+ *
52
+ * @param value O valor a ser filtrado.
53
+ * @returns A própria instância.
54
+ */
55
+ greaterThan(value: string | number): IxcOrm;
56
+ /**
57
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**>=**) = GREATER_THAN_EQUALS.
58
+ *
59
+ * @param value O valor a ser filtrado.
60
+ * @returns A própria instância.
61
+ */
62
+ greaterThanEquals(value: string | number): IxcOrm;
63
+ /**
64
+ * Define o número da página e a quantidade de registros por página que serão retornados pelo IXc Provedor.
65
+ *
66
+ * @param page A página a ser buscada.
67
+ * @param rows A quantidade de registros por página.
68
+ * @returns A própria instância.
69
+ */
70
+ paginate(page: number, rows: number): this;
71
+ /**
72
+ * Define o tipo de ordenação dos registros retornados pela API do IXC Provedor.
73
+ *
74
+ * @param sort **ASC** ou **DESC**.
75
+ * @param column A coluna que será utilizada para ordenar os registros.
76
+ * @returns A própria instância.
77
+ */
78
+ orderBy(column: string, sort: Sort): this;
79
+ private createQueryObject;
80
+ private addParamToGridAndResetStub;
81
+ }
package/dist/IxcOrm.js ADDED
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const Operators_1 = __importDefault(require("./api/Operators"));
40
+ const Ordering_1 = __importStar(require("./api/Ordering"));
41
+ const Pagination_1 = __importDefault(require("./api/Pagination"));
42
+ const Parameter_1 = __importDefault(require("./api/Parameter"));
43
+ const RequestEmitter_1 = __importDefault(require("./api/RequestEmitter"));
44
+ class IxcOrm extends RequestEmitter_1.default {
45
+ /**
46
+ * Método construtor da classe.
47
+ *
48
+ * @param table Representa o o nome da tabela que será manipulada, no IXC Provedor.
49
+ */
50
+ constructor(table) {
51
+ super(table);
52
+ this.ordering = Ordering_1.default.ascBy(table, "id");
53
+ this.pagination = Pagination_1.default.defaults();
54
+ this.parameters = [];
55
+ this.parameterStub = new Parameter_1.default(table);
56
+ }
57
+ /**
58
+ * Inicia um novo objeto de parâmetro de busca do filtro da grid.
59
+ *
60
+ * @param column O nome da coluna onde o filtro de busca será executado.
61
+ * @returns A própria instância.
62
+ */
63
+ where(column) {
64
+ this.parameterStub.withType(column);
65
+ return this;
66
+ }
67
+ /**
68
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**L**) = LIKE.
69
+ *
70
+ * @param value O valor a ser filtrado.
71
+ * @returns A própria instância.
72
+ */
73
+ like(value) {
74
+ this.parameterStub.withOperator(Operators_1.default.LIKE);
75
+ this.parameterStub.withValue(value);
76
+ this.addParamToGridAndResetStub();
77
+ super.setupQuery(this.createQueryObject());
78
+ return this;
79
+ }
80
+ /**
81
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**=**) = EQUALS.
82
+ *
83
+ * @param value O valor a ser filtrado.
84
+ * @returns A própria instância.
85
+ */
86
+ exactly(value) {
87
+ this.parameterStub.withOperator(Operators_1.default.EQUALS);
88
+ this.parameterStub.withValue(value);
89
+ this.addParamToGridAndResetStub();
90
+ super.setupQuery(this.createQueryObject());
91
+ return this;
92
+ }
93
+ /**
94
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**<**) = LESS_THAN.
95
+ *
96
+ * @param value O valor a ser filtrado.
97
+ * @returns A própria instância.
98
+ */
99
+ lessThan(value) {
100
+ this.parameterStub.withOperator(Operators_1.default.LESS_THAN);
101
+ this.parameterStub.withValue(value);
102
+ this.addParamToGridAndResetStub();
103
+ super.setupQuery(this.createQueryObject());
104
+ return this;
105
+ }
106
+ /**
107
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**<=**) = LESS_THAN_EQUALS.
108
+ *
109
+ * @param value O valor a ser filtrado.
110
+ * @returns A própria instância.
111
+ */
112
+ lessThanEquals(value) {
113
+ this.parameterStub.withOperator(Operators_1.default.LESS_THAN_EQUALS);
114
+ this.parameterStub.withValue(value);
115
+ this.addParamToGridAndResetStub();
116
+ super.setupQuery(this.createQueryObject());
117
+ return this;
118
+ }
119
+ /**
120
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**>**) = GREATER_THAN.
121
+ *
122
+ * @param value O valor a ser filtrado.
123
+ * @returns A própria instância.
124
+ */
125
+ greaterThan(value) {
126
+ this.parameterStub.withOperator(Operators_1.default.GREATER_THAN);
127
+ this.parameterStub.withValue(value);
128
+ this.addParamToGridAndResetStub();
129
+ super.setupQuery(this.createQueryObject());
130
+ return this;
131
+ }
132
+ /**
133
+ * Adiciona, ao último objeto de parâmetro iniciado, um valor a ser filtrado com o operador (**>=**) = GREATER_THAN_EQUALS.
134
+ *
135
+ * @param value O valor a ser filtrado.
136
+ * @returns A própria instância.
137
+ */
138
+ greaterThanEquals(value) {
139
+ this.parameterStub.withOperator(Operators_1.default.GREATER_THAN_EQUALS);
140
+ this.parameterStub.withValue(value);
141
+ this.addParamToGridAndResetStub();
142
+ super.setupQuery(this.createQueryObject());
143
+ return this;
144
+ }
145
+ /**
146
+ * Define o número da página e a quantidade de registros por página que serão retornados pelo IXc Provedor.
147
+ *
148
+ * @param page A página a ser buscada.
149
+ * @param rows A quantidade de registros por página.
150
+ * @returns A própria instância.
151
+ */
152
+ paginate(page, rows) {
153
+ this.pagination = new Pagination_1.default(page, rows);
154
+ return this;
155
+ }
156
+ /**
157
+ * Define o tipo de ordenação dos registros retornados pela API do IXC Provedor.
158
+ *
159
+ * @param sort **ASC** ou **DESC**.
160
+ * @param column A coluna que será utilizada para ordenar os registros.
161
+ * @returns A própria instância.
162
+ */
163
+ orderBy(column, sort) {
164
+ this.ordering = (sort === Ordering_1.Sort.ASC)
165
+ ? Ordering_1.default.ascBy(super.getTable(), column)
166
+ : Ordering_1.default.descBy(super.getTable(), column);
167
+ return this;
168
+ }
169
+ createQueryObject() {
170
+ return {
171
+ qtype: super.getTable(),
172
+ query: "",
173
+ oper: "",
174
+ page: this.pagination.getPage(),
175
+ rp: this.pagination.getRows(),
176
+ sortname: this.ordering.getSortName(),
177
+ sortorder: this.ordering.getSortOrder().toString(),
178
+ grid_param: JSON.stringify(this.parameters)
179
+ };
180
+ }
181
+ addParamToGridAndResetStub() {
182
+ this.parameters.push(this.parameterStub.toJsonObject());
183
+ this.parameterStub = new Parameter_1.default(super.getTable());
184
+ }
185
+ }
186
+ exports.default = IxcOrm;
@@ -0,0 +1,44 @@
1
+ export default class IxcResponse {
2
+ private data;
3
+ /**
4
+ * Cria um novo objeto no formato de uma resposta padrão do IXC Provedor.
5
+ *
6
+ * @param error Uma exceção capturada por um bloco try-catch.
7
+ * @returns Um objeto de resposta do IXC Provedor.
8
+ */
9
+ static createPropsWithError(error: any): string;
10
+ /**
11
+ * Método construtor da classe.
12
+ *
13
+ * @param text O conteúdo da resposta do IXc Provedor, no formato de texto.
14
+ */
15
+ constructor(text: string);
16
+ /**
17
+ * Obtém a quantidade total dos registros encontrados no banco de dados, além dos retornados na página atual.
18
+ *
19
+ * @returns O total de registros encontrados.
20
+ */
21
+ total(): number;
22
+ /**
23
+ * Obtém o número da página atual dos registros retornados.
24
+ *
25
+ * @returns O valor numérico da página.
26
+ */
27
+ page(): number;
28
+ /**
29
+ * Obtém uma mensagem retornada pelo IXC quando a requisição falha.
30
+ *
31
+ * @returns Uma mensagem de falha.
32
+ */
33
+ message(): string;
34
+ /**
35
+ * Obtém a lista de registros retornados por uma consulta à API do IXC Provedor.
36
+ *
37
+ * @returns Uma lista de objetos.
38
+ */
39
+ registros(): Array<{
40
+ [key: string]: any;
41
+ }>;
42
+ private parseDataFromText;
43
+ private parseDataFromHTML;
44
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const jsdom_1 = require("jsdom");
4
+ class IxcResponse {
5
+ /**
6
+ * Cria um novo objeto no formato de uma resposta padrão do IXC Provedor.
7
+ *
8
+ * @param error Uma exceção capturada por um bloco try-catch.
9
+ * @returns Um objeto de resposta do IXC Provedor.
10
+ */
11
+ static createPropsWithError(error) {
12
+ var _a;
13
+ const response = {
14
+ type: 'error',
15
+ page: 0,
16
+ total: 0,
17
+ registros: [],
18
+ message: ((_a = error.response) === null || _a === void 0 ? void 0 : _a.statusText) || error.message || 'Erro desconhecido'
19
+ };
20
+ return JSON.stringify(response);
21
+ }
22
+ /**
23
+ * Método construtor da classe.
24
+ *
25
+ * @param text O conteúdo da resposta do IXc Provedor, no formato de texto.
26
+ */
27
+ constructor(text) {
28
+ this.data = this.parseDataFromText(text);
29
+ }
30
+ /**
31
+ * Obtém a quantidade total dos registros encontrados no banco de dados, além dos retornados na página atual.
32
+ *
33
+ * @returns O total de registros encontrados.
34
+ */
35
+ total() {
36
+ var _a;
37
+ if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.total)) {
38
+ return 0;
39
+ }
40
+ return this.data.total;
41
+ }
42
+ /**
43
+ * Obtém o número da página atual dos registros retornados.
44
+ *
45
+ * @returns O valor numérico da página.
46
+ */
47
+ page() {
48
+ var _a;
49
+ if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.page)) {
50
+ return 0;
51
+ }
52
+ return this.data.page;
53
+ }
54
+ /**
55
+ * Obtém uma mensagem retornada pelo IXC quando a requisição falha.
56
+ *
57
+ * @returns Uma mensagem de falha.
58
+ */
59
+ message() {
60
+ var _a;
61
+ if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.message)) {
62
+ return '';
63
+ }
64
+ return this.data.message;
65
+ }
66
+ /**
67
+ * Obtém a lista de registros retornados por uma consulta à API do IXC Provedor.
68
+ *
69
+ * @returns Uma lista de objetos.
70
+ */
71
+ registros() {
72
+ var _a;
73
+ if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.registros)) {
74
+ return [];
75
+ }
76
+ return this.data.registros;
77
+ }
78
+ parseDataFromText(text) {
79
+ const isValidHTML = (text === null || text === void 0 ? void 0 : text.length) && text.includes('<div style=');
80
+ if (isValidHTML) {
81
+ return this.parseDataFromHTML(text);
82
+ }
83
+ return JSON.parse(text);
84
+ }
85
+ parseDataFromHTML(html) {
86
+ const dom = new jsdom_1.JSDOM(html);
87
+ return {
88
+ type: 'error',
89
+ page: 0,
90
+ total: 0,
91
+ message: dom.window.document.body.textContent
92
+ };
93
+ }
94
+ }
95
+ exports.default = IxcResponse;
@@ -0,0 +1,11 @@
1
+ export default class Environment {
2
+ private static instance;
3
+ private domain;
4
+ private token;
5
+ static getInstance(): Environment;
6
+ private constructor();
7
+ getDomain(): string;
8
+ getToken(): string;
9
+ setDomain(domain?: string): void;
10
+ setToken(token?: string): void;
11
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class Environment {
4
+ static getInstance() {
5
+ if (!Environment.instance) {
6
+ Environment.instance = new Environment();
7
+ }
8
+ return Environment.instance;
9
+ }
10
+ constructor() { }
11
+ getDomain() {
12
+ return this.domain;
13
+ }
14
+ getToken() {
15
+ return this.token;
16
+ }
17
+ setDomain(domain) {
18
+ var _a;
19
+ const newDomainIsValid = !(!(domain === null || domain === void 0 ? void 0 : domain.length));
20
+ const oldDomainIsValid = !((_a = this.domain) === null || _a === void 0 ? void 0 : _a.length);
21
+ if (newDomainIsValid && oldDomainIsValid) {
22
+ this.domain = domain;
23
+ }
24
+ }
25
+ setToken(token) {
26
+ var _a;
27
+ const newTokenIsValid = !(!(token === null || token === void 0 ? void 0 : token.length));
28
+ const oldTokenisValid = !((_a = this.token) === null || _a === void 0 ? void 0 : _a.length);
29
+ if (newTokenIsValid && oldTokenisValid) {
30
+ this.token = token;
31
+ }
32
+ }
33
+ }
34
+ exports.default = Environment;
@@ -0,0 +1,9 @@
1
+ declare enum Operators {
2
+ EQUALS = "=",
3
+ LIKE = "L",
4
+ LESS_THAN = "<",
5
+ LESS_THAN_EQUALS = "<=",
6
+ GREATER_THAN = ">",
7
+ GREATER_THAN_EQUALS = ">="
8
+ }
9
+ export default Operators;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var Operators;
4
+ (function (Operators) {
5
+ Operators["EQUALS"] = "=";
6
+ Operators["LIKE"] = "L";
7
+ Operators["LESS_THAN"] = "<";
8
+ Operators["LESS_THAN_EQUALS"] = "<=";
9
+ Operators["GREATER_THAN"] = ">";
10
+ Operators["GREATER_THAN_EQUALS"] = ">=";
11
+ })(Operators || (Operators = {}));
12
+ ;
13
+ exports.default = Operators;
@@ -0,0 +1,13 @@
1
+ export declare enum Sort {
2
+ ASC = "asc",
3
+ DESC = "desc"
4
+ }
5
+ export default class Ordering {
6
+ private sortName;
7
+ private sortOrder;
8
+ static ascBy(table: string, column: string): Ordering;
9
+ static descBy(table: string, column: string): Ordering;
10
+ constructor(sortName: string, sortOrder: Sort);
11
+ getSortName(): string;
12
+ getSortOrder(): Sort;
13
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Sort = void 0;
7
+ const Utils_1 = __importDefault(require("./Utils"));
8
+ var Sort;
9
+ (function (Sort) {
10
+ Sort["ASC"] = "asc";
11
+ Sort["DESC"] = "desc";
12
+ })(Sort || (exports.Sort = Sort = {}));
13
+ ;
14
+ class Ordering {
15
+ static ascBy(table, column) {
16
+ const normalizedTable = Utils_1.default.Text.normalize(table);
17
+ const normalizedColumn = Utils_1.default.Text.normalize(column);
18
+ return new Ordering(`${normalizedTable}.${normalizedColumn}`, Sort.ASC);
19
+ }
20
+ static descBy(table, column) {
21
+ const normalizedTable = Utils_1.default.Text.normalize(table);
22
+ const normalizedColumn = Utils_1.default.Text.normalize(column);
23
+ return new Ordering(`${normalizedTable}.${normalizedColumn}`, Sort.DESC);
24
+ }
25
+ constructor(sortName, sortOrder) {
26
+ this.sortName = sortName;
27
+ this.sortOrder = sortOrder;
28
+ this.sortName = sortName;
29
+ this.sortOrder = sortOrder;
30
+ }
31
+ getSortName() {
32
+ var _a;
33
+ return (_a = this.sortName) !== null && _a !== void 0 ? _a : 'id';
34
+ }
35
+ getSortOrder() {
36
+ var _a;
37
+ return (_a = this.sortOrder) !== null && _a !== void 0 ? _a : Sort.ASC;
38
+ }
39
+ }
40
+ exports.default = Ordering;
@@ -0,0 +1,8 @@
1
+ export default class Pagination {
2
+ private page;
3
+ private rows;
4
+ static defaults(): Pagination;
5
+ constructor(page: number, rows: number);
6
+ getPage(): number;
7
+ getRows(): number;
8
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class Pagination {
4
+ static defaults() {
5
+ return new Pagination(1, 20);
6
+ }
7
+ constructor(page, rows) {
8
+ this.page = page;
9
+ this.rows = rows;
10
+ this.page = page;
11
+ this.rows = rows;
12
+ }
13
+ getPage() {
14
+ var _a;
15
+ return (_a = this.page) !== null && _a !== void 0 ? _a : 1;
16
+ }
17
+ getRows() {
18
+ var _a;
19
+ return (_a = this.rows) !== null && _a !== void 0 ? _a : 20;
20
+ }
21
+ }
22
+ exports.default = Pagination;
@@ -0,0 +1,18 @@
1
+ import Operators from './Operators';
2
+ export type ParameterProps = {
3
+ TB: string;
4
+ OP: string;
5
+ P: string | number;
6
+ };
7
+ export default class Parameter {
8
+ private readonly table;
9
+ private operator;
10
+ private type;
11
+ private value;
12
+ constructor(table: string);
13
+ withType(type: string): this;
14
+ withOperator(operator: Operators): this;
15
+ withValue(value: string | number): this;
16
+ toJsonObject(): ParameterProps;
17
+ toJsonString(): string;
18
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const Operators_1 = __importDefault(require("./Operators"));
7
+ const Utils_1 = __importDefault(require("./Utils"));
8
+ class Parameter {
9
+ constructor(table) {
10
+ this.table = Utils_1.default.Text.normalize(table);
11
+ this.operator = Operators_1.default.EQUALS;
12
+ this.type = this.table;
13
+ this.value = '';
14
+ }
15
+ withType(type) {
16
+ const normalizedType = Utils_1.default.Text.normalize(type);
17
+ this.type = `${this.table}.${normalizedType}`;
18
+ return this;
19
+ }
20
+ withOperator(operator) {
21
+ this.operator = !(!operator) ? operator : Operators_1.default.EQUALS;
22
+ return this;
23
+ }
24
+ withValue(value) {
25
+ if (value) {
26
+ this.value = value;
27
+ }
28
+ return this;
29
+ }
30
+ toJsonObject() {
31
+ return {
32
+ TB: this.type,
33
+ OP: this.operator,
34
+ P: this.value
35
+ };
36
+ }
37
+ toJsonString() {
38
+ return JSON.stringify(this.toJsonObject());
39
+ }
40
+ }
41
+ exports.default = Parameter;
@@ -0,0 +1,84 @@
1
+ import IxcResponse from '../IxcResponse';
2
+ export default class RequestEmitter {
3
+ private readonly table;
4
+ private headers;
5
+ private query;
6
+ private uri;
7
+ /**
8
+ * Método construtor da classe.
9
+ *
10
+ * @param table Representa o endpoint do IXC Provedor para o qual será enviada a requisição.
11
+ */
12
+ protected constructor(table: string);
13
+ /**
14
+ * Envia uma requisição HTTP para a API do IXC Provedor, para listar registros, filtrando-os pela query de busca
15
+ * definida por **setQuery(String query)**.
16
+ * A requisição é do tipo POST, o que define que ela irá executar uma listagem de registros é a presença do header:
17
+ * ["ixcsoft": "listar"].
18
+ *
19
+ * @returns Uma nova instância de um {@link IxcResponse}.
20
+ */
21
+ GET(): Promise<IxcResponse>;
22
+ /**
23
+ * Envia uma requisição HTTP para a API do IXC Provedor, para inserir um novo registro no banco de dados, na tabela
24
+ * definida pelo prâmetro **(String table)** no construtor.
25
+ *
26
+ * @returns Uma nova instância de um {@link IxcResponse}.
27
+ */
28
+ POST(record: any): Promise<IxcResponse>;
29
+ /**
30
+ * Envia uma requisição HTTP para a API do IXC Provedor, para atualizar um ou mais campos de um registro no banco
31
+ * de dados, na tabela definida pelo prâmetro **(String table)** no construtor.
32
+ *
33
+ * @param record O registro com os campos a serem atualizados no banco de dados.
34
+ * @return Um objeto {@link IxcResponse} contento o status da requisição e uma mensagem que pode ser de sucesso ou
35
+ * de erro, dependendo do status.
36
+ */
37
+ PUT(record: any): Promise<IxcResponse>;
38
+ /**
39
+ * Envia uma requisição HTTP para a API do IXC Provedor, para excluir um determinado registro do banco de dados.
40
+ *
41
+ * @param id Um {@link Integer} com o id do registro a ser removido do banco de dados do IXC Provedor.
42
+ * @return Um objeto {@link IxcResponse}.
43
+ */
44
+ DELETE(record: any): Promise<IxcResponse>;
45
+ /**
46
+ * Obtém o valor da tabela, definida no cosntrutor.
47
+ *
48
+ * @returns string
49
+ */
50
+ protected getTable(): string;
51
+ /**
52
+ * Define a query que será enviada no corpo de uma requisição de busca.
53
+ *
54
+ * @example
55
+ * {
56
+ * "qtype": "cliente",
57
+ * "query": "",
58
+ * "oper": "",
59
+ * "page": "1",
60
+ * "rg": 20,
61
+ * "sortname": "asc",
62
+ * "sortorder": "cliente.id",
63
+ * "grid_param": [
64
+ * {
65
+ * "TB": "cliente.razao",
66
+ * "OP": "L",
67
+ * "P": "nome do cliente (nesse caso)"
68
+ * }
69
+ * ]
70
+ * }
71
+ *
72
+ * @param query Um objeto no formato de uma query da API do IXC Provedor.
73
+ */
74
+ protected setupQuery(query: {
75
+ [key: string]: any;
76
+ }): void;
77
+ private loadCommonHeaders;
78
+ private getEncodedTokenFromContext;
79
+ private setupUri;
80
+ private enableIxcListingHeader;
81
+ private disableIxcListingHeader;
82
+ private sendRequest;
83
+ private createDefaultHeaders;
84
+ }
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ const Environment_1 = __importDefault(require("./Environment"));
27
+ const IxcResponse_1 = __importDefault(require("../IxcResponse"));
28
+ const Utils_1 = __importDefault(require("./Utils"));
29
+ class RequestEmitter {
30
+ /**
31
+ * Método construtor da classe.
32
+ *
33
+ * @param table Representa o endpoint do IXC Provedor para o qual será enviada a requisição.
34
+ */
35
+ constructor(table) {
36
+ this.table = Utils_1.default.Text.normalize(table);
37
+ this.headers = [];
38
+ this.query = '';
39
+ this.uri = '';
40
+ this.loadCommonHeaders();
41
+ }
42
+ /**
43
+ * Envia uma requisição HTTP para a API do IXC Provedor, para listar registros, filtrando-os pela query de busca
44
+ * definida por **setQuery(String query)**.
45
+ * A requisição é do tipo POST, o que define que ela irá executar uma listagem de registros é a presença do header:
46
+ * ["ixcsoft": "listar"].
47
+ *
48
+ * @returns Uma nova instância de um {@link IxcResponse}.
49
+ */
50
+ GET() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ this.setupUri();
53
+ this.enableIxcListingHeader();
54
+ const responseText = yield this.sendRequest('POST', this.query);
55
+ return new IxcResponse_1.default(responseText);
56
+ });
57
+ }
58
+ /**
59
+ * Envia uma requisição HTTP para a API do IXC Provedor, para inserir um novo registro no banco de dados, na tabela
60
+ * definida pelo prâmetro **(String table)** no construtor.
61
+ *
62
+ * @returns Uma nova instância de um {@link IxcResponse}.
63
+ */
64
+ POST(record) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ this.setupUri();
67
+ this.disableIxcListingHeader();
68
+ const responseText = yield this.sendRequest('POST', record);
69
+ return new IxcResponse_1.default(responseText);
70
+ });
71
+ }
72
+ /**
73
+ * Envia uma requisição HTTP para a API do IXC Provedor, para atualizar um ou mais campos de um registro no banco
74
+ * de dados, na tabela definida pelo prâmetro **(String table)** no construtor.
75
+ *
76
+ * @param record O registro com os campos a serem atualizados no banco de dados.
77
+ * @return Um objeto {@link IxcResponse} contento o status da requisição e uma mensagem que pode ser de sucesso ou
78
+ * de erro, dependendo do status.
79
+ */
80
+ PUT(record) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const { id } = record, rest = __rest(record, ["id"]);
83
+ this.setupUri(id);
84
+ this.disableIxcListingHeader();
85
+ const responseText = yield this.sendRequest('PUT', rest);
86
+ return new IxcResponse_1.default(responseText);
87
+ });
88
+ }
89
+ /**
90
+ * Envia uma requisição HTTP para a API do IXC Provedor, para excluir um determinado registro do banco de dados.
91
+ *
92
+ * @param id Um {@link Integer} com o id do registro a ser removido do banco de dados do IXC Provedor.
93
+ * @return Um objeto {@link IxcResponse}.
94
+ */
95
+ DELETE(record) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ const { id } = record, rest = __rest(record, ["id"]);
98
+ this.setupUri(id);
99
+ this.disableIxcListingHeader();
100
+ const responseText = yield this.sendRequest('DELETE', rest);
101
+ return new IxcResponse_1.default(responseText);
102
+ });
103
+ }
104
+ /**
105
+ * Obtém o valor da tabela, definida no cosntrutor.
106
+ *
107
+ * @returns string
108
+ */
109
+ getTable() {
110
+ return this.table;
111
+ }
112
+ /**
113
+ * Define a query que será enviada no corpo de uma requisição de busca.
114
+ *
115
+ * @example
116
+ * {
117
+ * "qtype": "cliente",
118
+ * "query": "",
119
+ * "oper": "",
120
+ * "page": "1",
121
+ * "rg": 20,
122
+ * "sortname": "asc",
123
+ * "sortorder": "cliente.id",
124
+ * "grid_param": [
125
+ * {
126
+ * "TB": "cliente.razao",
127
+ * "OP": "L",
128
+ * "P": "nome do cliente (nesse caso)"
129
+ * }
130
+ * ]
131
+ * }
132
+ *
133
+ * @param query Um objeto no formato de uma query da API do IXC Provedor.
134
+ */
135
+ setupQuery(query) {
136
+ this.query = query;
137
+ }
138
+ loadCommonHeaders() {
139
+ const encodedToken = this.getEncodedTokenFromContext();
140
+ this.headers.push({ 'Authorization': `Basic ${encodedToken}` });
141
+ this.headers.push({ 'Content-Type': 'application/json' });
142
+ this.headers.push({ 'ixcsoft': '' });
143
+ }
144
+ getEncodedTokenFromContext() {
145
+ const token = Environment_1.default.getInstance().getToken();
146
+ return Buffer.from(token !== null && token !== void 0 ? token : '').toString('base64');
147
+ }
148
+ setupUri(id) {
149
+ const host = Environment_1.default.getInstance().getDomain();
150
+ const pathId = id ? `/${id}` : '';
151
+ this.uri = `https://${host}/webservice/v1/${this.table}${pathId}`;
152
+ }
153
+ enableIxcListingHeader() {
154
+ const headerIndex = this.headers.findIndex(h => Object.keys(h).includes('ixcsoft'));
155
+ if (headerIndex > -1) {
156
+ this.headers[headerIndex]['ixcsoft'] = 'listar';
157
+ }
158
+ }
159
+ disableIxcListingHeader() {
160
+ const headerIndex = this.headers.findIndex(h => Object.keys(h).includes('ixcsoft'));
161
+ if (headerIndex > -1) {
162
+ this.headers[headerIndex]['ixcsoft'] = '';
163
+ }
164
+ }
165
+ sendRequest(method, body) {
166
+ return __awaiter(this, void 0, void 0, function* () {
167
+ const headers = this.createDefaultHeaders();
168
+ try {
169
+ const response = yield fetch(this.uri, {
170
+ method,
171
+ headers,
172
+ body: body ? JSON.stringify(body) : undefined
173
+ });
174
+ return yield response.text();
175
+ }
176
+ catch (error) {
177
+ return IxcResponse_1.default.createPropsWithError(error);
178
+ }
179
+ });
180
+ }
181
+ createDefaultHeaders() {
182
+ return this.headers.reduce((accumulator, current) => {
183
+ Object.keys(current).forEach(currentKey => {
184
+ if (!Object.keys(accumulator).includes(currentKey)) {
185
+ accumulator[currentKey] = '';
186
+ }
187
+ accumulator[currentKey] = current[currentKey];
188
+ });
189
+ return accumulator;
190
+ }, {});
191
+ }
192
+ }
193
+ exports.default = RequestEmitter;
@@ -0,0 +1,7 @@
1
+ declare class TextUtils {
2
+ static normalize(text: string): string;
3
+ }
4
+ declare const Utils: {
5
+ Text: typeof TextUtils;
6
+ };
7
+ export default Utils;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class TextUtils {
4
+ static normalize(text) {
5
+ return text.replace(/[^a-z0-9_]/gi, '').trim();
6
+ }
7
+ }
8
+ const Utils = {
9
+ Text: TextUtils
10
+ };
11
+ exports.default = Utils;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import IXCClient from './IXCClient';
2
2
  import RecursoIXC, { Recurso } from './recursos';
3
+ import Environment from './api/Environment';
4
+ import IxcOrm from './IxcOrm';
5
+ import IxcResponse from './IxcResponse';
6
+ import Operators from './api/Operators';
7
+ import Ordering from './api/Ordering';
3
8
  import { IXCOperator, IXCOptions, IXCQuery, IXCRequest, IXCRequestMethods, IXCResponse, IXCSortOrder } from './types';
4
- export { IXCClient, IXCOperator, IXCOptions, IXCQuery, IXCRequest, IXCRequestMethods, IXCResponse, IXCSortOrder, Recurso,
9
+ export { IXCClient, IXCOperator, IXCOptions, IXCQuery, IXCRequest, IXCRequestMethods, IXCResponse, IXCSortOrder, Recurso, Environment, IxcOrm, IxcResponse, Operators, Ordering,
5
10
  /**
6
11
  * @property RecursoIXC
7
12
  * @deprecated Acesse os recursos através da constante {@link Recurso}
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.RecursoIXC = exports.Recurso = exports.IXCSortOrder = exports.IXCRequestMethods = exports.IXCOperator = exports.IXCClient = void 0;
39
+ exports.RecursoIXC = exports.Ordering = exports.Operators = exports.IxcResponse = exports.IxcOrm = exports.Environment = exports.Recurso = exports.IXCSortOrder = exports.IXCRequestMethods = exports.IXCOperator = exports.IXCClient = void 0;
40
40
  const path_1 = __importDefault(require("path"));
41
41
  const dotenv_1 = __importDefault(require("dotenv"));
42
42
  const IXCClient_1 = __importDefault(require("./IXCClient"));
@@ -44,15 +44,30 @@ exports.IXCClient = IXCClient_1.default;
44
44
  const recursos_1 = __importStar(require("./recursos"));
45
45
  exports.RecursoIXC = recursos_1.default;
46
46
  Object.defineProperty(exports, "Recurso", { enumerable: true, get: function () { return recursos_1.Recurso; } });
47
+ const Environment_1 = __importDefault(require("./api/Environment"));
48
+ exports.Environment = Environment_1.default;
49
+ const IxcOrm_1 = __importDefault(require("./IxcOrm"));
50
+ exports.IxcOrm = IxcOrm_1.default;
51
+ const IxcResponse_1 = __importDefault(require("./IxcResponse"));
52
+ exports.IxcResponse = IxcResponse_1.default;
53
+ const Operators_1 = __importDefault(require("./api/Operators"));
54
+ exports.Operators = Operators_1.default;
55
+ const Ordering_1 = __importDefault(require("./api/Ordering"));
56
+ exports.Ordering = Ordering_1.default;
47
57
  const types_1 = require("./types");
48
58
  Object.defineProperty(exports, "IXCOperator", { enumerable: true, get: function () { return types_1.IXCOperator; } });
49
59
  Object.defineProperty(exports, "IXCRequestMethods", { enumerable: true, get: function () { return types_1.IXCRequestMethods; } });
50
60
  Object.defineProperty(exports, "IXCSortOrder", { enumerable: true, get: function () { return types_1.IXCSortOrder; } });
51
61
  const root = (__dirname.includes('\\node_modules\\'))
52
62
  ? path_1.default.join(__dirname, '../../../.env')
53
- : path_1.default.join(__dirname, '../../.env');
54
- const env = dotenv_1.default.config({ path: root });
63
+ : path_1.default.join(__dirname, '../.env');
64
+ const env = dotenv_1.default.config({
65
+ quiet: true,
66
+ path: path_1.default.resolve(root)
67
+ });
55
68
  if (env.error) {
56
69
  console.error(env.error);
57
- process.exit(-1);
70
+ process.exit(1);
58
71
  }
72
+ Environment_1.default.getInstance().setToken(process.env.IXC_ACCESS_TOKEN);
73
+ Environment_1.default.getInstance().setDomain(process.env.IXC_SERVER_DOMAIN);
@@ -48,6 +48,8 @@ export declare const Recurso: {
48
48
  liberacaoTemporaria: typeof cliente_contrato_btn_lib_temp_24722;
49
49
  };
50
50
  /**
51
+ * *ATENÇÃO:* Esta função desá descontinuada
52
+ *
51
53
  * @deprecated Acesse os recursos através da constante {@link Recurso}
52
54
  */
53
55
  export default function RecursoIXC<T extends keyof Recursos>(recurso: T, args: Parameters<Recursos[T]>[0]): Promise<import("..").IXCResponse | import("../types").IXCRecursoResponse>;
@@ -63,6 +63,8 @@ exports.Recurso = {
63
63
  liberacaoTemporaria: cliente_contrato_btn_lib_temp_24722_1.default,
64
64
  };
65
65
  /**
66
+ * *ATENÇÃO:* Esta função desá descontinuada
67
+ *
66
68
  * @deprecated Acesse os recursos através da constante {@link Recurso}
67
69
  */
68
70
  function RecursoIXC(recurso, args) {
package/dist/types.d.ts CHANGED
@@ -40,6 +40,7 @@ export interface IXCRequest {
40
40
  }
41
41
  export interface IXCResponse {
42
42
  error?: boolean | object;
43
+ type?: string;
43
44
  message?: string;
44
45
  id?: string | number;
45
46
  page: number | string;
package/jest.config.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type {Config} from 'jest';
2
+
3
+
4
+ const config: Config = {
5
+
6
+ clearMocks: true,
7
+ collectCoverage: true,
8
+ coverageDirectory: 'coverage',
9
+ coverageProvider: 'v8',
10
+
11
+ transform: {
12
+ '^.+\\.(ts|tsx)$': 'ts-jest'
13
+ },
14
+
15
+ coverageReporters: [
16
+ 'json'
17
+ ],
18
+
19
+ setupFiles: [
20
+ "dotenv/config"
21
+ ],
22
+
23
+ setupFilesAfterEnv: [
24
+ './tests/jest.setup.ts'
25
+ ],
26
+
27
+ testMatch: [
28
+ '<rootDir>/tests/**/*.test.ts'
29
+ ]
30
+ };
31
+
32
+
33
+ export default config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ixc-orm",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "MIT",
@@ -8,7 +8,8 @@
8
8
  "scripts": {
9
9
  "declare": "tsc --declaration",
10
10
  "build": "tsc --build",
11
- "dev": "nodemon --watch \"src//\" --exec \"ts-node src/index.ts\" -e ts"
11
+ "dev": "nodemon --watch \"src//\" --exec \"ts-node src/index.ts\" -e ts",
12
+ "test": "jest"
12
13
  },
13
14
  "repository": {
14
15
  "type": "git",
@@ -17,11 +18,12 @@
17
18
  "keywords": [
18
19
  "IXCSoft API",
19
20
  "IXCsoft",
20
- "IXC API"
21
+ "IXC API",
22
+ "IXC Provedor"
21
23
  ],
22
24
  "author": {
23
25
  "name": "Felipe Sousa",
24
- "email": "flpssdocarmo@gmail.com",
26
+ "email": "fscarmo@proton.me",
25
27
  "url": "https://github.com/SousaFelipe"
26
28
  },
27
29
  "bugs": {
@@ -29,11 +31,17 @@
29
31
  },
30
32
  "dependencies": {
31
33
  "axios": "^1.12.2",
32
- "dotenv": "^17.2.2"
34
+ "dotenv": "^17.2.2",
35
+ "jsdom": "^27.0.0"
33
36
  },
34
37
  "devDependencies": {
38
+ "@jest/globals": "^30.2.0",
39
+ "@types/jest": "^30.0.0",
40
+ "@types/jsdom": "^27.0.0",
35
41
  "@types/node": "^24.5.2",
42
+ "jest": "^30.2.0",
36
43
  "nodemon": "^3.1.10",
44
+ "ts-jest": "^29.4.5",
37
45
  "ts-node": "^10.9.2",
38
46
  "typescript": "^5.9.2"
39
47
  }
package/tsconfig.json CHANGED
@@ -3,14 +3,22 @@
3
3
  "target": "es6",
4
4
  "module": "commonjs",
5
5
  "outDir": "./dist",
6
+ "rootDir": "./src",
6
7
  "strict": true,
7
8
  "declaration": true,
8
9
  "noUnusedLocals": true,
9
10
  "noUnusedParameters": true,
10
11
  "noImplicitReturns": true,
11
12
  "noFallthroughCasesInSwitch": true,
12
- "esModuleInterop": true
13
+ "esModuleInterop": true,
14
+ "skipLibCheck": true
13
15
  },
14
- "include": ["src/**/*"],
15
- "exclude": ["node_modules", "**/*.test.ts"]
16
+ "include": [
17
+ "src/**/*"
18
+ ],
19
+ "exclude": [
20
+ "node_modules",
21
+ "**/*.test.ts",
22
+ "jest.config.ts"
23
+ ]
16
24
  }
@@ -0,0 +1 @@
1
+ {"root":["./src/ixcclient.ts","./src/ixcorm.ts","./src/ixcresponse.ts","./src/index.ts","./src/request.ts","./src/response.ts","./src/types.ts","./src/api/environment.ts","./src/api/operators.ts","./src/api/ordering.ts","./src/api/pagination.ts","./src/api/parameter.ts","./src/api/requestemitter.ts","./src/api/utils.ts","./src/recursos/cliente_contrato_btn_lib_temp_24722.ts","./src/recursos/desbloqueio_confianca.ts","./src/recursos/get_boleto.ts","./src/recursos/index.ts","./src/recursos/recurso.ts"],"version":"5.9.2"}
@@ -1 +0,0 @@
1
- {"root":["../src/ixcclient.ts","../src/index.ts","../src/request.ts","../src/response.ts","../src/types.ts","../src/recursos/cliente_contrato_btn_lib_temp_24722.ts","../src/recursos/desbloqueio_confianca.ts","../src/recursos/get_boleto.ts","../src/recursos/index.ts","../src/recursos/recurso.ts"],"version":"5.9.2"}