ixc-orm 1.0.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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Felipe Sousa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # IXC-ORM
2
+
3
+ Este ORM simples, visa facilitar o consumo de dados da API oficial do IXCsoft.\
4
+ Esta biblioteca não faz parte das bibliotecas oficiais da IXCsoft e foi desenvolvida de forma independente e sem fins lucrativos.
5
+
6
+
7
+ ## Instalação
8
+ ```bash
9
+ npm install ixc-orm
10
+ ```
11
+ ou
12
+ ```bash
13
+ yarn add ixc-orm
14
+ ```
15
+
16
+
17
+ ## Usando a biblioteca
18
+
19
+ > As classes que representarão as tabelas dentro do banco de dados do seu servidor IXC, deverão herdar da classe `IXCClient`.
20
+
21
+ ```typescript
22
+ import { IXCClient } 'ixc-orm';
23
+
24
+ class Contrato extends IXCClient {
25
+
26
+ constructor() {
27
+ super('cliente_contrato');
28
+ }
29
+ }
30
+ ```
31
+
32
+ > 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`.
33
+
34
+ ```typescript
35
+ const contrato = new Contrato();
36
+
37
+ contrato
38
+ .where('id', 240)
39
+ .where(['data_ativacao', '>=', '2024-09-24 00:45:00'])
40
+ .orderBy('data_ativacao', 'desc')
41
+ .get();
42
+ ```
43
+
44
+
45
+ ## Variáveis de Ambiente
46
+
47
+ 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.
48
+
49
+ `IXC_HOST`
50
+
51
+ `IXC_TOKEN`
@@ -0,0 +1,55 @@
1
+ import { AxiosError } from 'axios';
2
+ import { IXCOptions, IXCQuery, IXCResponse, IXCSortOrder } from './types';
3
+ export default abstract class IXCClient {
4
+ protected table: string;
5
+ protected params: IXCQuery[];
6
+ protected options: IXCOptions;
7
+ /**
8
+ *
9
+ * @param table O nome da tabela dentro do banco de dados do seu servidor IXC
10
+ * @see {@link https://wikiapiprovedor.ixcsoft.com.br/index.php}
11
+ */
12
+ constructor(table: string);
13
+ /**
14
+ *
15
+ * @param whereClauses Um array de strings, no formato [coluna, operador, valor]
16
+ * Obs: se você passar um array no formato [coluna, valor] o operador será considerado como '='
17
+ *
18
+ * Operadores: =, !=, >, <, >=, <=, LIKE
19
+ *
20
+ * @returns
21
+ */
22
+ where(whereClauses: string[]): IXCClient;
23
+ /**
24
+ *
25
+ * @param column A coluna que será usada para ordenar a busca
26
+ * @param order A ordem da busca ('asc'ou 'desc')
27
+ * @returns A própria instância
28
+ */
29
+ orderBy(column: string, order: keyof typeof IXCSortOrder): IXCClient;
30
+ /**
31
+ *
32
+ * @param pg O número da página que será solicitada ao IXC
33
+ * @param rows A quantidade de linhas (registros) por página
34
+ * @returns Promise<null | IXCResponse | AxiosError>
35
+ */
36
+ get(pg?: number, rows?: number): Promise<null | IXCResponse | AxiosError>;
37
+ /**
38
+ *
39
+ * @param body Um objeto no formado "chave/valor" contendo as informações do novo registro
40
+ * a ser inserido no banco de dados do seu servidor IXC
41
+ * @returns Promise<null | IXCResponse | AxiosError>
42
+ */
43
+ post(body?: {
44
+ [key: string]: any;
45
+ }): Promise<null | IXCResponse | AxiosError>;
46
+ /**
47
+ *
48
+ * @param id O id do registro que será alterado
49
+ * @param body Um objeto no formado "chave/valor" contendo as colunas que serão alteradas
50
+ * @returns Promise<null | IXCResponse | AxiosError>
51
+ */
52
+ put(id: number, body?: {
53
+ [key: string]: any;
54
+ }): Promise<null | IXCResponse | AxiosError>;
55
+ }
@@ -0,0 +1,155 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ const axios_1 = require("axios");
24
+ const request_1 = require("./request");
25
+ class IXCClient {
26
+ /**
27
+ *
28
+ * @param table O nome da tabela dentro do banco de dados do seu servidor IXC
29
+ * @see {@link https://wikiapiprovedor.ixcsoft.com.br/index.php}
30
+ */
31
+ constructor(table) {
32
+ this.table = table;
33
+ this.params = [];
34
+ this.options = {
35
+ page: 1,
36
+ rowsPerPage: 20,
37
+ sortName: 'id',
38
+ sortOrder: 'asc'
39
+ };
40
+ }
41
+ /**
42
+ *
43
+ * @param whereClauses Um array de strings, no formato [coluna, operador, valor]
44
+ * Obs: se você passar um array no formato [coluna, valor] o operador será considerado como '='
45
+ *
46
+ * Operadores: =, !=, >, <, >=, <=, LIKE
47
+ *
48
+ * @returns
49
+ */
50
+ where(whereClauses) {
51
+ const [column, operatorOrValue, valueOrUndefined] = whereClauses;
52
+ this.params.push({
53
+ TB: column,
54
+ OP: valueOrUndefined ? operatorOrValue : '=',
55
+ P: valueOrUndefined ? valueOrUndefined : operatorOrValue
56
+ });
57
+ return this;
58
+ }
59
+ /**
60
+ *
61
+ * @param column A coluna que será usada para ordenar a busca
62
+ * @param order A ordem da busca ('asc'ou 'desc')
63
+ * @returns A própria instância
64
+ */
65
+ orderBy(column, order) {
66
+ this.options.sortName = column;
67
+ this.options.sortOrder = order;
68
+ return this;
69
+ }
70
+ /**
71
+ *
72
+ * @param pg O número da página que será solicitada ao IXC
73
+ * @param rows A quantidade de linhas (registros) por página
74
+ * @returns Promise<null | IXCResponse | AxiosError>
75
+ */
76
+ get(pg, rows) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ const _a = this.options, { page, rowsPerPage } = _a, rest = __rest(_a, ["page", "rowsPerPage"]);
79
+ const opts = Object.assign({ page: pg !== null && pg !== void 0 ? pg : page, rowsPerPage: rows !== null && rows !== void 0 ? rows : rowsPerPage }, rest);
80
+ const axios = (0, request_1.createAxiosInstance)('GET');
81
+ const payload = (0, request_1.createRequestPayload)(this.table, this.params, opts);
82
+ try {
83
+ const response = yield axios.get(this.table, { data: payload });
84
+ return response.data;
85
+ }
86
+ catch (error) {
87
+ console.error(error);
88
+ if (error instanceof axios_1.AxiosError) {
89
+ return error;
90
+ }
91
+ return null;
92
+ }
93
+ finally {
94
+ this.params = [];
95
+ this.options = {
96
+ page: 1,
97
+ rowsPerPage: 20,
98
+ sortName: 'id',
99
+ sortOrder: 'asc'
100
+ };
101
+ }
102
+ });
103
+ }
104
+ /**
105
+ *
106
+ * @param body Um objeto no formado "chave/valor" contendo as informações do novo registro
107
+ * a ser inserido no banco de dados do seu servidor IXC
108
+ * @returns Promise<null | IXCResponse | AxiosError>
109
+ */
110
+ post(body) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const axios = (0, request_1.createAxiosInstance)('POST');
113
+ try {
114
+ const response = yield axios.post(this.table, { data: body });
115
+ return response.data;
116
+ }
117
+ catch (error) {
118
+ console.error(error);
119
+ if (error instanceof axios_1.AxiosError) {
120
+ return error;
121
+ }
122
+ return null;
123
+ }
124
+ finally {
125
+ this.params = [];
126
+ }
127
+ });
128
+ }
129
+ /**
130
+ *
131
+ * @param id O id do registro que será alterado
132
+ * @param body Um objeto no formado "chave/valor" contendo as colunas que serão alteradas
133
+ * @returns Promise<null | IXCResponse | AxiosError>
134
+ */
135
+ put(id, body) {
136
+ return __awaiter(this, void 0, void 0, function* () {
137
+ const axios = (0, request_1.createAxiosInstance)('PUT');
138
+ try {
139
+ const response = yield axios.put(`${this.table}/${id}`, { data: body });
140
+ return response.data;
141
+ }
142
+ catch (error) {
143
+ console.error(error);
144
+ if (error instanceof axios_1.AxiosError) {
145
+ return error;
146
+ }
147
+ return null;
148
+ }
149
+ finally {
150
+ this.params = [];
151
+ }
152
+ });
153
+ }
154
+ }
155
+ exports.default = IXCClient;
@@ -0,0 +1,5 @@
1
+ import IXCClient from './IXCClient';
2
+ declare const _default: {
3
+ readonly IXCClient: typeof IXCClient;
4
+ };
5
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
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 path_1 = __importDefault(require("path"));
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ const IXCClient_1 = __importDefault(require("./IXCClient"));
9
+ const env = dotenv_1.default.config({
10
+ path: path_1.default.join(__dirname, `../.env`)
11
+ });
12
+ if (env.error) {
13
+ console.error(env.error);
14
+ process.exit(-1);
15
+ }
16
+ exports.default = {
17
+ IXCClient: IXCClient_1.default
18
+ };
@@ -0,0 +1,16 @@
1
+ import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import { IXCOptions, IXCQuery, IXCRequest, IXCRequestMethods } from './types';
3
+ /**
4
+ *
5
+ * @param method GET | POST | PUT
6
+ * @returns A instânxia de um objeto do tipo AxiosInstance, pre-confugurado com os cabeçalhos necessários
7
+ */
8
+ export declare function createAxiosInstance(method?: keyof typeof IXCRequestMethods): AxiosInstance;
9
+ /**
10
+ *
11
+ * @param table Nome da tabelado IXC onde será feita a busca, atualização, inserção ou remoção
12
+ * @param params Parâmetros da busca (desconciderado em cadastros de novos registros)
13
+ * @param options Parâmetros de formatação dos dados da responsta (página, ítens por página e ordenação)
14
+ * @returns
15
+ */
16
+ export declare function createRequestPayload(table: string, params: IXCQuery | IXCQuery[], options?: IXCOptions): AxiosRequestConfig<IXCRequest>;
@@ -0,0 +1,69 @@
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.createAxiosInstance = createAxiosInstance;
7
+ exports.createRequestPayload = createRequestPayload;
8
+ const axios_1 = __importDefault(require("axios"));
9
+ /**
10
+ *
11
+ * @param method GET | POST | PUT
12
+ * @returns A instânxia de um objeto do tipo AxiosInstance, pre-confugurado com os cabeçalhos necessários
13
+ */
14
+ function createAxiosInstance(method = 'GET') {
15
+ const host = process.env.IXC_HOST;
16
+ const token = process.env.IXC_TOKEN;
17
+ return axios_1.default.create({
18
+ method: method,
19
+ baseURL: host !== null && host !== void 0 ? host : 'http://127.0.0.1:3000/webservice/v1',
20
+ headers: {
21
+ 'ixcsoft': (method === 'GET') ? 'listar' : '',
22
+ 'Content-Type': 'application/json',
23
+ 'Authorization': `Basic ${Buffer.from(token !== null && token !== void 0 ? token : '').toString('base64')}`
24
+ }
25
+ });
26
+ }
27
+ /**
28
+ *
29
+ * @param table Nome da tabelado IXC onde será feita a busca, atualização, inserção ou remoção
30
+ * @param params Parâmetros da busca (desconciderado em cadastros de novos registros)
31
+ * @param options Parâmetros de formatação dos dados da responsta (página, ítens por página e ordenação)
32
+ * @returns
33
+ */
34
+ function createRequestPayload(table, params, options) {
35
+ var _a, _b, _c, _d;
36
+ const page = (_a = options === null || options === void 0 ? void 0 : options.page) !== null && _a !== void 0 ? _a : 1;
37
+ const rowsPerPage = (_b = options === null || options === void 0 ? void 0 : options.rowsPerPage) !== null && _b !== void 0 ? _b : 20;
38
+ const sortName = (_c = options === null || options === void 0 ? void 0 : options.sortName) !== null && _c !== void 0 ? _c : 'id';
39
+ const sortOrder = (_d = options === null || options === void 0 ? void 0 : options.sortOrder) !== null && _d !== void 0 ? _d : 'asc';
40
+ if (Array.isArray(params)) {
41
+ let grid_param = [];
42
+ params.forEach(p => {
43
+ grid_param.push({
44
+ TB: `${table}.${p.TB}`,
45
+ OP: p.OP || '=',
46
+ P: p.P
47
+ });
48
+ });
49
+ return { data: {
50
+ qtype: table,
51
+ query: '',
52
+ oper: '',
53
+ page: page,
54
+ rp: rowsPerPage,
55
+ sortname: `${table}.${sortName}`,
56
+ sortorder: sortOrder,
57
+ grid_param: JSON.stringify(grid_param)
58
+ } };
59
+ }
60
+ return { data: {
61
+ qtype: `${table}.${params.TB}`,
62
+ query: params.P,
63
+ oper: params.OP || '=',
64
+ page: page,
65
+ rp: rowsPerPage,
66
+ sortname: `${table}.${sortName}`,
67
+ sortorder: sortOrder
68
+ } };
69
+ }
@@ -0,0 +1,50 @@
1
+ export declare const IXCOperator: {
2
+ '=': string;
3
+ '>': string;
4
+ '<': string;
5
+ '>=': string;
6
+ '<=': string;
7
+ '!=': string;
8
+ LIKE: string;
9
+ };
10
+ export declare const IXCSortOrder: {
11
+ asc: string;
12
+ desc: string;
13
+ };
14
+ export declare const IXCRequestMethods: {
15
+ GET: string;
16
+ POST: string;
17
+ PUT: string;
18
+ DELETE: string;
19
+ };
20
+ export interface IXCOptions {
21
+ page: number;
22
+ rowsPerPage?: number;
23
+ sortName?: string;
24
+ sortOrder?: keyof typeof IXCSortOrder;
25
+ }
26
+ export interface IXCQuery {
27
+ TB: string;
28
+ OP?: string;
29
+ P: string;
30
+ }
31
+ export interface IXCRequest {
32
+ qtype: string;
33
+ query: string;
34
+ oper: string;
35
+ page: number;
36
+ rp: number;
37
+ sortname: string;
38
+ sortorder: string;
39
+ grid_param?: string;
40
+ }
41
+ export interface IXCResponse {
42
+ error?: boolean | object;
43
+ message?: string | null;
44
+ id?: string | number;
45
+ page: number | string;
46
+ total: number;
47
+ registros: Array<{
48
+ [key: string]: any;
49
+ }>;
50
+ }
package/dist/types.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IXCRequestMethods = exports.IXCSortOrder = exports.IXCOperator = void 0;
4
+ exports.IXCOperator = {
5
+ '=': '=',
6
+ '>': '>',
7
+ '<': '<',
8
+ '>=': '>=',
9
+ '<=': '<=',
10
+ '!=': '!=',
11
+ 'LIKE': 'L'
12
+ };
13
+ exports.IXCSortOrder = {
14
+ asc: 'asc',
15
+ desc: 'desc'
16
+ };
17
+ exports.IXCRequestMethods = {
18
+ GET: 'GET',
19
+ POST: 'POST',
20
+ PUT: 'PUT',
21
+ DELETE: 'DELETE'
22
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "ixc-orm",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "license": "MIT",
7
+ "description": "ORM para consumo de dados da API oficial do IXCsoft",
8
+ "scripts": {
9
+ "declare": "tsc --declaration",
10
+ "build": "tsc --build",
11
+ "dev": "nodemon --watch \"src//\" --exec \"ts-node src/index.ts\" -e ts"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/SousaFelipe/ixc-orm.git"
16
+ },
17
+ "keywords": [
18
+ "IXCSoft API",
19
+ "IXCsoft",
20
+ "IXC API"
21
+ ],
22
+ "author": {
23
+ "name": "Felipe Sousa",
24
+ "email": "flpssdocarmo@gmail.com",
25
+ "url": "https://github.com/SousaFelipe"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/SousaFelipe/ixc-orm/issues"
29
+ },
30
+ "dependencies": {
31
+ "axios": "^1.7.5",
32
+ "dotenv": "^16.4.5"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.5.0",
36
+ "nodemon": "^3.1.4",
37
+ "ts-node": "^10.9.2",
38
+ "typescript": "^5.5.4"
39
+ }
40
+ }
@@ -0,0 +1,172 @@
1
+ import { AxiosError } from 'axios';
2
+ import { createAxiosInstance, createRequestPayload } from './request';
3
+ import { IXCOptions, IXCQuery, IXCResponse, IXCSortOrder } from './types';
4
+
5
+
6
+
7
+ export default abstract class IXCClient {
8
+
9
+
10
+ protected table: string;
11
+ protected params: IXCQuery[];
12
+ protected options: IXCOptions;
13
+
14
+
15
+ /**
16
+ *
17
+ * @param table O nome da tabela dentro do banco de dados do seu servidor IXC
18
+ * @see {@link https://wikiapiprovedor.ixcsoft.com.br/index.php}
19
+ */
20
+ constructor(table: string) {
21
+
22
+ this.table = table;
23
+ this.params = [];
24
+
25
+ this.options = {
26
+ page: 1,
27
+ rowsPerPage: 20,
28
+ sortName: 'id',
29
+ sortOrder: 'asc'
30
+ };
31
+ }
32
+
33
+
34
+ /**
35
+ *
36
+ * @param whereClauses Um array de strings, no formato [coluna, operador, valor]
37
+ * Obs: se você passar um array no formato [coluna, valor] o operador será considerado como '='
38
+ *
39
+ * Operadores: =, !=, >, <, >=, <=, LIKE
40
+ *
41
+ * @returns
42
+ */
43
+ where(whereClauses: string[]) : IXCClient {
44
+
45
+ const [
46
+ column,
47
+ operatorOrValue,
48
+ valueOrUndefined
49
+ ] = whereClauses;
50
+
51
+ this.params.push({
52
+ TB: column,
53
+ OP: valueOrUndefined ? operatorOrValue : '=',
54
+ P: valueOrUndefined ? valueOrUndefined : operatorOrValue
55
+ });
56
+
57
+ return this
58
+ }
59
+
60
+
61
+ /**
62
+ *
63
+ * @param column A coluna que será usada para ordenar a busca
64
+ * @param order A ordem da busca ('asc'ou 'desc')
65
+ * @returns A própria instância
66
+ */
67
+ orderBy(column: string, order: keyof typeof IXCSortOrder) : IXCClient {
68
+ this.options.sortName = column;
69
+ this.options.sortOrder = order;
70
+ return this;
71
+ }
72
+
73
+
74
+ /**
75
+ *
76
+ * @param pg O número da página que será solicitada ao IXC
77
+ * @param rows A quantidade de linhas (registros) por página
78
+ * @returns Promise<null | IXCResponse | AxiosError>
79
+ */
80
+ async get(pg?: number, rows?: number) : Promise<null | IXCResponse | AxiosError> {
81
+
82
+ const { page, rowsPerPage, ...rest } = this.options;
83
+
84
+ const opts = {
85
+ page: pg ?? page,
86
+ rowsPerPage: rows ?? rowsPerPage,
87
+ ...rest
88
+ };
89
+
90
+ const axios = createAxiosInstance('GET');
91
+ const payload = createRequestPayload(this.table, this.params, opts);
92
+
93
+ try {
94
+ const response = await axios.get<IXCResponse>(this.table, { data: payload });
95
+ return response.data;
96
+ }
97
+ catch (error: any) {
98
+ console.error(error);
99
+
100
+ if (error instanceof AxiosError) {
101
+ return error;
102
+ }
103
+
104
+ return null;
105
+ }
106
+ finally {
107
+ this.params = [];
108
+ this.options = {
109
+ page: 1,
110
+ rowsPerPage: 20,
111
+ sortName: 'id',
112
+ sortOrder: 'asc'
113
+ };
114
+ }
115
+ }
116
+
117
+
118
+ /**
119
+ *
120
+ * @param body Um objeto no formado "chave/valor" contendo as informações do novo registro
121
+ * a ser inserido no banco de dados do seu servidor IXC
122
+ * @returns Promise<null | IXCResponse | AxiosError>
123
+ */
124
+ async post(body?: { [key: string]: any }) : Promise<null | IXCResponse | AxiosError> {
125
+ const axios = createAxiosInstance('POST');
126
+
127
+ try {
128
+ const response = await axios.post<IXCResponse>(this.table, { data: body });
129
+ return response.data;
130
+ }
131
+ catch (error: any) {
132
+ console.error(error);
133
+
134
+ if (error instanceof AxiosError) {
135
+ return error;
136
+ }
137
+
138
+ return null;
139
+ }
140
+ finally {
141
+ this.params = [];
142
+ }
143
+ }
144
+
145
+
146
+ /**
147
+ *
148
+ * @param id O id do registro que será alterado
149
+ * @param body Um objeto no formado "chave/valor" contendo as colunas que serão alteradas
150
+ * @returns Promise<null | IXCResponse | AxiosError>
151
+ */
152
+ async put(id: number, body?: { [key: string]: any }) : Promise<null | IXCResponse | AxiosError> {
153
+ const axios = createAxiosInstance('PUT');
154
+
155
+ try {
156
+ const response = await axios.put<IXCResponse>(`${ this.table }/${ id }`, { data: body });
157
+ return response.data;
158
+ }
159
+ catch (error: any) {
160
+ console.error(error);
161
+
162
+ if (error instanceof AxiosError) {
163
+ return error;
164
+ }
165
+
166
+ return null;
167
+ }
168
+ finally {
169
+ this.params = [];
170
+ }
171
+ }
172
+ }
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ import path from 'path';
2
+ import dotenv from 'dotenv';
3
+
4
+ import IXCClient from './IXCClient';
5
+
6
+
7
+
8
+ const env = dotenv.config({
9
+ path: path.join(__dirname, `../.env`)
10
+ });
11
+
12
+ if (env.error) {
13
+ console.error(env.error);
14
+ process.exit(-1);
15
+ }
16
+
17
+
18
+
19
+ export default {
20
+
21
+ IXCClient
22
+
23
+ } as const;
package/src/request.ts ADDED
@@ -0,0 +1,79 @@
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import { IXCOptions, IXCQuery, IXCRequest, IXCRequestMethods } from './types';
3
+
4
+
5
+ /**
6
+ *
7
+ * @param method GET | POST | PUT
8
+ * @returns A instânxia de um objeto do tipo AxiosInstance, pre-confugurado com os cabeçalhos necessários
9
+ */
10
+ export function createAxiosInstance(
11
+ method: keyof typeof IXCRequestMethods = 'GET'
12
+ ) : AxiosInstance {
13
+
14
+ const host = process.env.IXC_HOST;
15
+ const token = process.env.IXC_TOKEN;
16
+
17
+ return axios.create({
18
+ method: method,
19
+ baseURL: host ?? 'http://127.0.0.1:3000/webservice/v1',
20
+ headers: {
21
+ 'ixcsoft': (method === 'GET') ? 'listar' : '',
22
+ 'Content-Type': 'application/json',
23
+ 'Authorization': `Basic ${ Buffer.from(token ?? '').toString('base64') }`
24
+ }
25
+ });
26
+ }
27
+
28
+
29
+ /**
30
+ *
31
+ * @param table Nome da tabelado IXC onde será feita a busca, atualização, inserção ou remoção
32
+ * @param params Parâmetros da busca (desconciderado em cadastros de novos registros)
33
+ * @param options Parâmetros de formatação dos dados da responsta (página, ítens por página e ordenação)
34
+ * @returns
35
+ */
36
+ export function createRequestPayload(
37
+ table: string,
38
+ params: IXCQuery | IXCQuery[],
39
+ options?: IXCOptions
40
+ ) : AxiosRequestConfig<IXCRequest> {
41
+
42
+ const page = options?.page ?? 1;
43
+ const rowsPerPage = options?.rowsPerPage ?? 20;
44
+ const sortName = options?.sortName ?? 'id';
45
+ const sortOrder = options?.sortOrder ?? 'asc';
46
+
47
+ if (Array.isArray(params)) {
48
+ let grid_param: object[] = [];
49
+
50
+ params.forEach(p => {
51
+ grid_param.push({
52
+ TB: `${table}.${p.TB}`,
53
+ OP: p.OP || '=',
54
+ P: p.P
55
+ });
56
+ });
57
+
58
+ return { data: {
59
+ qtype: table,
60
+ query: '',
61
+ oper: '',
62
+ page: page,
63
+ rp: rowsPerPage,
64
+ sortname: `${table}.${sortName}`,
65
+ sortorder: sortOrder,
66
+ grid_param: JSON.stringify(grid_param)
67
+ }};
68
+ }
69
+
70
+ return { data: {
71
+ qtype: `${table}.${params.TB}`,
72
+ query: params.P,
73
+ oper: params.OP || '=',
74
+ page: page,
75
+ rp: rowsPerPage,
76
+ sortname: `${table}.${sortName}`,
77
+ sortorder: sortOrder
78
+ }};
79
+ }
package/src/types.ts ADDED
@@ -0,0 +1,61 @@
1
+
2
+
3
+
4
+ export const IXCOperator = {
5
+ '=': '=',
6
+ '>': '>',
7
+ '<': '<',
8
+ '>=': '>=',
9
+ '<=': '<=',
10
+ '!=': '!=',
11
+ 'LIKE': 'L'
12
+ }
13
+
14
+ export const IXCSortOrder = {
15
+ asc: 'asc',
16
+ desc: 'desc'
17
+ }
18
+
19
+ export const IXCRequestMethods = {
20
+ GET: 'GET',
21
+ POST: 'POST',
22
+ PUT: 'PUT',
23
+ DELETE: 'DELETE'
24
+ }
25
+
26
+
27
+ export interface IXCOptions {
28
+ page: number,
29
+ rowsPerPage?: number,
30
+ sortName?: string,
31
+ sortOrder?: keyof typeof IXCSortOrder
32
+ }
33
+
34
+
35
+ export interface IXCQuery {
36
+ TB: string,
37
+ OP?: string,
38
+ P: string
39
+ }
40
+
41
+
42
+ export interface IXCRequest {
43
+ qtype: string,
44
+ query: string,
45
+ oper: string,
46
+ page: number,
47
+ rp: number,
48
+ sortname: string,
49
+ sortorder: string,
50
+ grid_param?: string
51
+ }
52
+
53
+
54
+ export interface IXCResponse {
55
+ error?: boolean | object,
56
+ message?: string | null,
57
+ id?: string | number,
58
+ page: number | string,
59
+ total: number,
60
+ registros: Array<{ [key: string]: any }>
61
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6",
4
+ "module": "commonjs",
5
+ "outDir": "./dist",
6
+ "strict": true,
7
+ "noUnusedLocals": true,
8
+ "noUnusedParameters": true,
9
+ "noImplicitReturns": true,
10
+ "noFallthroughCasesInSwitch": true,
11
+ "esModuleInterop": true
12
+ },
13
+ "include": ["src/**/*"],
14
+ "exclude": ["node_modules", "**/*.test.ts"]
15
+ }