@c-rex/core 0.0.6 → 0.0.8

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.
@@ -0,0 +1,30 @@
1
+ import { Method } from 'axios';
2
+ import { ConfigInterface } from '@c-rex/interfaces';
3
+
4
+ interface CallParams {
5
+ url: string;
6
+ method: Method;
7
+ body?: any;
8
+ headers?: any;
9
+ params?: any;
10
+ }
11
+ declare class CrexApi {
12
+ private config;
13
+ private apiClient;
14
+ private logger;
15
+ constructor(config: ConfigInterface, logger: any);
16
+ private manageToken;
17
+ private getToken;
18
+ execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
+ }
20
+
21
+ declare class CrexSDK {
22
+ api: CrexApi;
23
+ logger: any;
24
+ userAuthConfig: any;
25
+ customerConfig: ConfigInterface;
26
+ constructor();
27
+ static setConfig(config: ConfigInterface): void;
28
+ }
29
+
30
+ export { CrexApi, CrexSDK };
@@ -0,0 +1,30 @@
1
+ import { Method } from 'axios';
2
+ import { ConfigInterface } from '@c-rex/interfaces';
3
+
4
+ interface CallParams {
5
+ url: string;
6
+ method: Method;
7
+ body?: any;
8
+ headers?: any;
9
+ params?: any;
10
+ }
11
+ declare class CrexApi {
12
+ private config;
13
+ private apiClient;
14
+ private logger;
15
+ constructor(config: ConfigInterface, logger: any);
16
+ private manageToken;
17
+ private getToken;
18
+ execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
+ }
20
+
21
+ declare class CrexSDK {
22
+ api: CrexApi;
23
+ logger: any;
24
+ userAuthConfig: any;
25
+ customerConfig: ConfigInterface;
26
+ constructor();
27
+ static setConfig(config: ConfigInterface): void;
28
+ }
29
+
30
+ export { CrexApi, CrexSDK };
package/dist/index.js ADDED
@@ -0,0 +1,140 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _class;// src/requests.ts
2
+ var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);
3
+ var _constants = require('@c-rex/constants');
4
+ var _openidclient = require('openid-client');
5
+ var _utils = require('@c-rex/utils');
6
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
7
+ var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
+ var CrexApi = class {
9
+
10
+
11
+
12
+ constructor(config, logger) {
13
+ this.apiClient = _axios2.default.create({
14
+ baseURL: config.baseUrl,
15
+ headers: {
16
+ "content-Type": "application/json"
17
+ }
18
+ });
19
+ this.config = config;
20
+ this.logger = logger;
21
+ }
22
+ async manageToken() {
23
+ const headersAux = {};
24
+ if (this.config.OIDC.client.enabled) {
25
+ let token = _utils.getFromMemory.call(void 0, CREX_TOKEN_HEADER_KEY);
26
+ let tokenExpiry = _utils.getFromMemory.call(void 0, CREX_TOKEN_EXPIRY_HEADER_KEY);
27
+ const now = Math.floor(Date.now() / 1e3);
28
+ if (!(token && tokenExpiry > now + 60)) {
29
+ const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
30
+ token = tokenAux;
31
+ _utils.saveInMemory.call(void 0, token, CREX_TOKEN_HEADER_KEY);
32
+ _utils.saveInMemory.call(void 0, tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
33
+ }
34
+ headersAux["Authorization"] = `Bearer ${token}`;
35
+ }
36
+ return headersAux;
37
+ }
38
+ async getToken() {
39
+ let token = "";
40
+ let tokenExpiry = 0;
41
+ try {
42
+ const now = Math.floor(Date.now() / 1e3);
43
+ const issuer = await _openidclient.Issuer.discover(this.config.OIDC.client.issuer);
44
+ const client = new issuer.Client({
45
+ client_id: this.config.OIDC.client.id,
46
+ client_secret: this.config.OIDC.client.secret
47
+ });
48
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
+ token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
50
+ } catch (error) {
51
+ console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
52
+ }
53
+ return {
54
+ token,
55
+ tokenExpiry
56
+ };
57
+ }
58
+ async execute({
59
+ url,
60
+ method,
61
+ params,
62
+ body,
63
+ headers = {}
64
+ }) {
65
+ let response = void 0;
66
+ headers = {
67
+ ...headers,
68
+ ...await this.manageToken()
69
+ };
70
+ for (let retry = 0; retry < _constants.API.MAX_RETRY; retry++) {
71
+ try {
72
+ response = await this.apiClient.request({
73
+ url,
74
+ method,
75
+ data: body,
76
+ params,
77
+ headers
78
+ });
79
+ break;
80
+ } catch (error) {
81
+ console.log(
82
+ "error",
83
+ `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
84
+ );
85
+ if (retry === _constants.API.MAX_RETRY - 1) {
86
+ throw error;
87
+ }
88
+ }
89
+ }
90
+ if (response) {
91
+ return response.data;
92
+ }
93
+ throw new Error("API.execute error: Failed to retrieve a valid response");
94
+ }
95
+ };
96
+
97
+ // src/sdk.ts
98
+
99
+ var SDK_CONFIG_KEY = "crex-sdk-config";
100
+ var CrexSDK = (_class = class {
101
+
102
+
103
+ __init() {this.userAuthConfig = {}}
104
+
105
+ constructor() {;_class.prototype.__init.call(this);
106
+ const config = _utils.getFromMemory.call(void 0, SDK_CONFIG_KEY);
107
+ this.customerConfig = config;
108
+ this.api = new CrexApi(this.customerConfig, null);
109
+ const user = this.customerConfig.OIDC.user;
110
+ this.userAuthConfig = {
111
+ providers: [
112
+ {
113
+ id: "crex",
114
+ name: "CREX",
115
+ type: "oauth",
116
+ clientId: user.id,
117
+ wellKnown: user.issuer,
118
+ clientSecret: user.secret,
119
+ authorization: { params: { scope: user.scope } },
120
+ profile(profile) {
121
+ return {
122
+ id: profile.id || "fake Id",
123
+ name: profile.name || "Fake Name",
124
+ email: profile.email || "fake Email",
125
+ image: profile.image || "fake Image"
126
+ };
127
+ }
128
+ }
129
+ ]
130
+ };
131
+ }
132
+ static setConfig(config) {
133
+ _utils.saveInMemory.call(void 0, config, SDK_CONFIG_KEY);
134
+ }
135
+ }, _class);
136
+
137
+
138
+
139
+ exports.CrexApi = CrexApi; exports.CrexSDK = CrexSDK;
140
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","../src/requests.ts","../src/sdk.ts"],"names":[],"mappings":"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","file":"/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","sourcesContent":[null,"import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!,\n tokenExpiry = now + tokenSet.expires_at!\n } catch (error) {\n console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","import { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n }\n }\n\n public static setConfig(config: ConfigInterface) {\n saveInMemory(config, SDK_CONFIG_KEY);\n }\n}"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // src/requests.ts
2
+ import axios from "axios";
3
+ import { API } from "@c-rex/constants";
4
+ import { Issuer } from "openid-client";
5
+ import { getFromMemory, saveInMemory } from "@c-rex/utils";
6
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
7
+ var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
+ var CrexApi = class {
9
+ config;
10
+ apiClient;
11
+ logger;
12
+ constructor(config, logger) {
13
+ this.apiClient = axios.create({
14
+ baseURL: config.baseUrl,
15
+ headers: {
16
+ "content-Type": "application/json"
17
+ }
18
+ });
19
+ this.config = config;
20
+ this.logger = logger;
21
+ }
22
+ async manageToken() {
23
+ const headersAux = {};
24
+ if (this.config.OIDC.client.enabled) {
25
+ let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
26
+ let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
27
+ const now = Math.floor(Date.now() / 1e3);
28
+ if (!(token && tokenExpiry > now + 60)) {
29
+ const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
30
+ token = tokenAux;
31
+ saveInMemory(token, CREX_TOKEN_HEADER_KEY);
32
+ saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
33
+ }
34
+ headersAux["Authorization"] = `Bearer ${token}`;
35
+ }
36
+ return headersAux;
37
+ }
38
+ async getToken() {
39
+ let token = "";
40
+ let tokenExpiry = 0;
41
+ try {
42
+ const now = Math.floor(Date.now() / 1e3);
43
+ const issuer = await Issuer.discover(this.config.OIDC.client.issuer);
44
+ const client = new issuer.Client({
45
+ client_id: this.config.OIDC.client.id,
46
+ client_secret: this.config.OIDC.client.secret
47
+ });
48
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
+ token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
50
+ } catch (error) {
51
+ console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
52
+ }
53
+ return {
54
+ token,
55
+ tokenExpiry
56
+ };
57
+ }
58
+ async execute({
59
+ url,
60
+ method,
61
+ params,
62
+ body,
63
+ headers = {}
64
+ }) {
65
+ let response = void 0;
66
+ headers = {
67
+ ...headers,
68
+ ...await this.manageToken()
69
+ };
70
+ for (let retry = 0; retry < API.MAX_RETRY; retry++) {
71
+ try {
72
+ response = await this.apiClient.request({
73
+ url,
74
+ method,
75
+ data: body,
76
+ params,
77
+ headers
78
+ });
79
+ break;
80
+ } catch (error) {
81
+ console.log(
82
+ "error",
83
+ `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
84
+ );
85
+ if (retry === API.MAX_RETRY - 1) {
86
+ throw error;
87
+ }
88
+ }
89
+ }
90
+ if (response) {
91
+ return response.data;
92
+ }
93
+ throw new Error("API.execute error: Failed to retrieve a valid response");
94
+ }
95
+ };
96
+
97
+ // src/sdk.ts
98
+ import { getFromMemory as getFromMemory2, saveInMemory as saveInMemory2 } from "@c-rex/utils";
99
+ var SDK_CONFIG_KEY = "crex-sdk-config";
100
+ var CrexSDK = class {
101
+ api;
102
+ logger;
103
+ userAuthConfig = {};
104
+ customerConfig;
105
+ constructor() {
106
+ const config = getFromMemory2(SDK_CONFIG_KEY);
107
+ this.customerConfig = config;
108
+ this.api = new CrexApi(this.customerConfig, null);
109
+ const user = this.customerConfig.OIDC.user;
110
+ this.userAuthConfig = {
111
+ providers: [
112
+ {
113
+ id: "crex",
114
+ name: "CREX",
115
+ type: "oauth",
116
+ clientId: user.id,
117
+ wellKnown: user.issuer,
118
+ clientSecret: user.secret,
119
+ authorization: { params: { scope: user.scope } },
120
+ profile(profile) {
121
+ return {
122
+ id: profile.id || "fake Id",
123
+ name: profile.name || "Fake Name",
124
+ email: profile.email || "fake Email",
125
+ image: profile.image || "fake Image"
126
+ };
127
+ }
128
+ }
129
+ ]
130
+ };
131
+ }
132
+ static setConfig(config) {
133
+ saveInMemory2(config, SDK_CONFIG_KEY);
134
+ }
135
+ };
136
+ export {
137
+ CrexApi,
138
+ CrexSDK
139
+ };
140
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/requests.ts","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!,\n tokenExpiry = now + tokenSet.expires_at!\n } catch (error) {\n console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","import { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n }\n }\n\n public static setConfig(config: ConfigInterface) {\n saveInMemory(config, SDK_CONFIG_KEY);\n }\n}"],"mappings":";AAAA,OAAO,WAAqD;AAC5D,SAAS,WAAW;AACpB,SAAS,cAAc;AAEvB,SAAS,eAAe,oBAAoB;AAE5C,IAAM,wBAAwB;AAC9B,IAAM,+BAA+B;AAe9B,IAAM,UAAN,MAAc;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAED,YAAY,QAAyB,QAAa;AACrD,SAAK,YAAY,MAAM,OAAO;AAAA,MAC1B,SAAS,OAAO;AAAA,MAChB,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,IACJ,CAAC;AAED,SAAK,SAAS;AACd,SAAK,SAAS;AAAA,EAClB;AAAA,EAEA,MAAc,cAAc;AACxB,UAAM,aAAqC,CAAC;AAE5C,QAAI,KAAK,OAAO,KAAK,OAAO,SAAS;AACjC,UAAI,QAAQ,cAAc,qBAAqB;AAC/C,UAAI,cAAc,cAAc,4BAA4B;AAE5D,YAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAExC,UAAI,EAAE,SAAS,cAAc,MAAM,KAAK;AACpC,cAAM,EAAE,OAAO,UAAU,aAAa,eAAe,IAAI,MAAM,KAAK,SAAS;AAE7E,gBAAQ;AAER,qBAAa,OAAO,qBAAqB;AACzC,qBAAa,gBAAgB,4BAA4B;AAAA,MAC7D;AAEA,iBAAW,eAAe,IAAI,UAAU,KAAK;AAAA,IACjD;AAEA,WAAO;AAAA,EACX;AAAA,EAEA,MAAc,WAGX;AACC,QAAI,QAAQ;AACZ,QAAI,cAAc;AAElB,QAAI;AACA,YAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACxC,YAAM,SAAS,MAAM,OAAO,SAAS,KAAK,OAAO,KAAK,OAAO,MAAM;AACnE,YAAM,SAAS,IAAI,OAAO,OAAO;AAAA,QAC7B,WAAW,KAAK,OAAO,KAAK,OAAO;AAAA,QACnC,eAAe,KAAK,OAAO,KAAK,OAAO;AAAA,MAC3C,CAAC;AACD,YAAM,WAAW,MAAM,OAAO,MAAM,EAAE,YAAY,qBAAqB,CAAC;AAExE,cAAQ,SAAS,cACb,cAAc,MAAM,SAAS;AAAA,IACrC,SAAS,OAAO;AACZ,cAAQ,IAAI,SAAS,mCAAmC,KAAK,OAAO,KAAK,OAAO,MAAM,YAAY,KAAK,EAAE;AAAA,IAC7G;AAEA,WAAO;AAAA,MACH;AAAA,MACA;AAAA,IACJ;AAAA,EACJ;AAAA,EAEA,MAAM,QAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,CAAC;AAAA,EACf,GAA2B;AACvB,QAAI,WAA8C;AAElD,cAAU;AAAA,MACN,GAAG;AAAA,MACH,GAAG,MAAM,KAAK,YAAY;AAAA,IAC9B;AAEA,aAAS,QAAQ,GAAG,QAAQ,IAAI,WAAW,SAAS;AAChD,UAAI;AACA,mBAAW,MAAM,KAAK,UAAU,QAAQ;AAAA,UACpC;AAAA,UACA;AAAA,UACA,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACJ,CAAC;AAED;AAAA,MACJ,SAAS,OAAO;AACZ,gBAAQ;AAAA,UACJ;AAAA,UACA,eAAe,QAAQ,CAAC,2BAAwB,GAAG,YAAY,KAAK;AAAA,QACxE;AAEA,YAAI,UAAU,IAAI,YAAY,GAAG;AAC7B,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAEA,QAAI,UAAU;AACV,aAAO,SAAS;AAAA,IACpB;AAEA,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC5E;AACJ;;;ACpIA,SAAS,iBAAAA,gBAAe,gBAAAC,qBAAoB;AAE5C,IAAM,iBAAiB;AAEhB,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EACA,iBAAsB,CAAC;AAAA,EACvB;AAAA,EAEA,cAAc;AACjB,UAAM,SAASD,eAAc,cAAc;AAE3C,SAAK,iBAAiB;AACtB,SAAK,MAAM,IAAI,QAAQ,KAAK,gBAAgB,IAAI;AAEhD,UAAM,OAAO,KAAK,eAAe,KAAK;AACtC,SAAK,iBAAiB;AAAA,MAClB,WAAW;AAAA,QACP;AAAA,UACI,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,UACN,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB,cAAc,KAAK;AAAA,UACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,UAC/C,QAAQ,SAAc;AAClB,mBAAO;AAAA,cACH,IAAI,QAAQ,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAAA,EAEA,OAAc,UAAU,QAAyB;AAC7C,IAAAC,cAAa,QAAQ,cAAc;AAAA,EACvC;AACJ;","names":["getFromMemory","saveInMemory"]}
package/package.json CHANGED
@@ -1,24 +1,32 @@
1
1
  {
2
2
  "name": "@c-rex/core",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index.mjs",
6
+ "types": "dist/index.d.ts",
4
7
  "files": [
5
- "src"
8
+ "dist"
6
9
  ],
7
10
  "publishConfig": {
8
11
  "access": "public"
9
12
  },
10
13
  "exports": {
11
14
  ".": {
12
- "types": "./src/index.ts",
13
- "import": "./src/index.ts",
14
- "require": "./src/index.ts",
15
- "default": "./src/index.ts"
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.mjs",
17
+ "require": "./dist/index.js",
18
+ "default": "./dist/index.js"
16
19
  },
17
- "./package.json": "./package.json"
20
+ "./package.json": "./package.json",
21
+ "./logger.server": {
22
+ "import": "./dist/logger.server.mjs",
23
+ "require": "./dist/logger.server.cjs"
24
+ }
18
25
  },
26
+ "sideEffects": false,
19
27
  "scripts": {
20
- "dev": "echo 'Nothing to build using raw TypeScript files'",
21
- "build": "echo 'No build needed'",
28
+ "dev": "tsup src/index.ts --splitting --format cjs,esm --dts --watch",
29
+ "build": "tsup src/index.ts --splitting --format cjs,esm --dts",
22
30
  "test:watch": "jest --watch",
23
31
  "test": "jest"
24
32
  },
@@ -38,7 +46,10 @@
38
46
  "@c-rex/constants": "*",
39
47
  "@c-rex/interfaces": "*",
40
48
  "@c-rex/types": "*",
49
+ "@c-rex/utils": "*",
41
50
  "axios": "^1.8.4",
51
+ "next-auth": "^4.24.11",
52
+ "openid-client": "^5.7.1",
42
53
  "winston": "^3.17.0",
43
54
  "winston-graylog2": "^2.1.2"
44
55
  }
@@ -1,7 +0,0 @@
1
- import '../logger';
2
-
3
- describe('Force coverage inclusion', () => {
4
- it('Dummy', () => {
5
- expect(true).toBe(true);
6
- });
7
- });
@@ -1,91 +0,0 @@
1
- import { CrexApi } from '../requests';
2
- import { CrexLogger } from '../logger';
3
- import axios from 'axios';
4
-
5
- jest.mock('axios');
6
- jest.mock('../logger');
7
-
8
- describe('CrexApi', () => {
9
- const mockBaseUrl = 'http://api.test.com';
10
- const mockLogger = new CrexLogger({} as any);
11
- let api: CrexApi;
12
-
13
- beforeEach(() => {
14
- jest.clearAllMocks();
15
- (axios.create as jest.Mock).mockReturnValue({
16
- request: jest.fn()
17
- });
18
- api = new CrexApi(mockBaseUrl, mockLogger);
19
- });
20
-
21
- describe('execute', () => {
22
- it('should make a successful API request', async () => {
23
- const mockResponse = { data: { id: 1 }, status: 200 };
24
- const mockAxiosInstance = axios.create();
25
- (mockAxiosInstance.request as jest.Mock).mockResolvedValue(mockResponse);
26
-
27
- const result = await api.execute({
28
- url: '/test',
29
- method: 'GET',
30
- headers: { 'X-Test': 'test' }
31
- });
32
-
33
- expect(result).toEqual(mockResponse.data);
34
- expect(mockAxiosInstance.request).toHaveBeenCalledWith({
35
- url: '/test',
36
- method: 'GET',
37
- headers: { 'X-Test': 'test' },
38
- data: undefined,
39
- params: undefined
40
- });
41
- });
42
-
43
- it('should handle request with body and params', async () => {
44
- const mockResponse = { data: { success: true }, status: 200 };
45
- const mockAxiosInstance = axios.create();
46
- (mockAxiosInstance.request as jest.Mock).mockResolvedValue(mockResponse);
47
-
48
- await api.execute({
49
- url: '/test',
50
- method: 'POST',
51
- body: { name: 'test' },
52
- params: { id: 1 }
53
- });
54
-
55
- expect(mockAxiosInstance.request).toHaveBeenCalledWith({
56
- url: '/test',
57
- method: 'POST',
58
- data: { name: 'test' },
59
- params: { id: 1 },
60
- headers: undefined
61
- });
62
- });
63
-
64
- it('should retry failed requests', async () => {
65
- const mockError = new Error('Network error');
66
- const mockAxiosInstance = axios.create();
67
- (mockAxiosInstance.request as jest.Mock).mockRejectedValue(mockError);
68
-
69
- await expect(api.execute({
70
- url: '/test',
71
- method: 'GET'
72
- })).rejects.toThrow('Network error');
73
-
74
- expect(mockLogger.log).toHaveBeenCalledWith(
75
- 'error',
76
- expect.stringContaining('Network error')
77
- );
78
- expect(mockAxiosInstance.request).toHaveBeenCalledTimes(1);
79
- });
80
-
81
- it('should throw error when no valid response after retries', async () => {
82
- const mockAxiosInstance = axios.create();
83
- (mockAxiosInstance.request as jest.Mock).mockResolvedValue(undefined);
84
-
85
- await expect(api.execute({
86
- url: '/test',
87
- method: 'GET'
88
- })).rejects.toThrow('Failed to retrieve a valid response');
89
- });
90
- });
91
- });
@@ -1,82 +0,0 @@
1
- import { CrexSDK } from '../sdk';
2
- import { CrexLogger } from '../logger';
3
- import { CrexApi } from '../requests';
4
- import { ConfigInterface } from '@c-rex/interfaces';
5
-
6
- jest.mock('../logger');
7
- jest.mock('../requests');
8
-
9
- describe('CrexSDK', () => {
10
- const mockConfig: ConfigInterface = {
11
- projectName: 'test-project',
12
- baseUrl: 'http://test.com',
13
- search: {
14
- fields: [],
15
- tags: [],
16
- restrict: [],
17
- filter: [],
18
- sparqlWhere: ''
19
- },
20
- logs: {
21
- graylog: {
22
- silent: true,
23
- url: 'http://graylog.test',
24
- app: 'test-app',
25
- minimumLevel: 'info',
26
- categoriesLevel: ['Document']
27
- },
28
- matomo: {
29
- silent: false,
30
- url: '',
31
- app: '',
32
- minimumLevel: 'info',
33
- categoriesLevel: []
34
- },
35
- console: {
36
- silent: false,
37
- url: '',
38
- app: '',
39
- minimumLevel: 'info',
40
- categoriesLevel: []
41
- }
42
- }
43
- };
44
-
45
- beforeEach(() => {
46
- jest.clearAllMocks();
47
- // Reset the singleton instance
48
- (CrexSDK as any).instance = undefined;
49
- });
50
-
51
- describe('constructor', () => {
52
- it('should create a new instance with correct configuration', () => {
53
- const sdk = new CrexSDK(mockConfig);
54
-
55
- expect(sdk.customerConfig).toBe(mockConfig);
56
- expect(sdk.logger).toBeInstanceOf(CrexLogger);
57
- expect(sdk.api).toBeInstanceOf(CrexApi);
58
- expect(CrexLogger).toHaveBeenCalledWith(mockConfig);
59
- expect(CrexApi).toHaveBeenCalledWith(mockConfig.baseUrl, expect.any(CrexLogger));
60
- });
61
-
62
- it('should return existing instance if already initialized', () => {
63
- const firstInstance = new CrexSDK(mockConfig);
64
- const secondInstance = new CrexSDK(mockConfig);
65
-
66
- expect(secondInstance).toBe(firstInstance);
67
- });
68
- });
69
-
70
- describe('getInstance', () => {
71
- it('should return existing instance', () => {
72
- const sdk = new CrexSDK(mockConfig);
73
- const instance = CrexSDK.getInstance();
74
-
75
- expect(instance).toBe(sdk);
76
- });
77
-
78
- it('should throw error if instance not initialized', () => {
79
- expect(() => CrexSDK.getInstance()).toThrow('SDK not initialized');
80
- });
81
- });
82
- });
package/src/cli.ts DELETED
@@ -1,189 +0,0 @@
1
- /*
2
- import { execSync } from 'child_process';
3
- import { checkbox, confirm, input, select } from '@inquirer/prompts';
4
-
5
- import fs from 'fs';
6
- import path from 'path';
7
- import { FILTER_OPTIONS, LOG_CATEGORIES, LOG_LEVELS } from '../constants/log';
8
- import { RESULT_VIEW_OPTIONS } from '../constants/components';
9
-
10
- type Restriction = {
11
- key: string;
12
- value: string;
13
- operator: string;
14
- }
15
- const addRestriction = async (word: string): Promise<Restriction[]> => {
16
- const restrictions: any = []
17
-
18
- let aux = await confirm({
19
- message: `Do you want to add ${word}s to your search?`,
20
- default: false,
21
- });
22
-
23
- while (aux) {
24
- const restriction: Restriction = {
25
- key: "",
26
- value: '${value}',
27
- operator: ""
28
- }
29
-
30
- restriction.key = await input({
31
- message: `Type the ${word} key:`,
32
- });
33
-
34
- restriction.operator = await select({
35
- message: `Type the ${word} operator:`,
36
- choices: FILTER_OPTIONS.map(key => ({ value: key })),
37
- default: FILTER_OPTIONS[0]
38
- });
39
-
40
- const byValue = await confirm({
41
- message: `Do you want apply your ${word} using a fixed value?`,
42
- default: false
43
- });
44
-
45
- if (byValue) {
46
- restriction.value = await input({
47
- message: `Type the ${word} value:`,
48
- });
49
- }
50
-
51
- restrictions.push(restriction);
52
-
53
- aux = await confirm({
54
- message: `Do you want to add more ${word}s?`,
55
- default: false
56
- });
57
- }
58
-
59
- return restrictions;
60
- }
61
-
62
- const log = async (name: string): Promise<any> => {
63
- const log = {
64
- silent: false,
65
- logLevel: [],
66
- categoriesLevel: [],
67
- url: "",
68
- app: "",
69
- }
70
- log.silent = await confirm({
71
- message: `Do you want to silent ${name}?`,
72
- default: false
73
- });
74
-
75
- if (!log.silent) {
76
- log.url = await input({
77
- message: `Type the ${name} URL:`,
78
- });
79
- log.app = await input({
80
- message: `Type the ${name} app name:`,
81
- });
82
- const logLevel = await checkbox({
83
- message: `Select the log level to ${name}:`,
84
- choices: Object.keys(LOG_LEVELS).map(key => {
85
- return {
86
- value: key,
87
- checked: true,
88
- };
89
- }),
90
- });
91
- const categoriesLevel = await checkbox({
92
- message: `Select the categories level to ${name}:`,
93
- choices: LOG_CATEGORIES.map(key => {
94
- return {
95
- value: key,
96
- checked: true,
97
- };
98
- }),
99
- });
100
-
101
- log.logLevel = logLevel as any;
102
- log.categoriesLevel = categoriesLevel as any;
103
- }
104
-
105
- return log;
106
- }
107
-
108
- async function main() {
109
- try {
110
- const projectName = await input({
111
- message: 'Set the project name:',
112
- default: "c-rex.net"
113
- });
114
-
115
- const baseUrl = await input({
116
- message: 'Set the base URL:',
117
- default: "https://c-rex.net/ids/api/iirds/v1/"
118
- });
119
-
120
- const resultViewStyle = await select({
121
- message: 'Results should be shown as:',
122
- choices: Object.keys(RESULT_VIEW_OPTIONS).map(key => {
123
- return { value: key };
124
- }),
125
- default: RESULT_VIEW_OPTIONS.table
126
- });
127
-
128
- const searchFields = await input({
129
- message: 'Type the fields used in search separated by comma:',
130
- default: "titles,labels,languages"
131
- });
132
-
133
- const searchTags = await input({
134
- message: 'Type the tags used in search separated by comma:',
135
- default: ""
136
- });
137
-
138
- const restrictions = await addRestriction("restriction");
139
- const filters = await addRestriction("filter");
140
-
141
- const sparqlWhere = await input({
142
- message: 'Type the sparqlWhere string:',
143
- default: ""
144
- });
145
-
146
- const graylog = await log("Graylog");
147
- const matomo = await log("Matomo");
148
-
149
- const config = {
150
- projectName: projectName,
151
- baseUrl: baseUrl,
152
- search: {
153
- fields: searchFields.split(','),
154
- tags: searchTags.split(','),
155
- restrict: restrictions,
156
- filter: filters,
157
- sparqlWhere: sparqlWhere
158
- },
159
- resultViewStyle: resultViewStyle,
160
- logs: {
161
- graylog: graylog,
162
- matomo: matomo
163
- }
164
- }
165
-
166
- const configFilePath = path.join(process.cwd(), 'src', 'config', 'customerConfig.ts');
167
-
168
- const configFileContent = `
169
- import { ConfigInterface } from "@/interfaces/config";
170
- export const CUSTOMER_CONFIG: ConfigInterface = ${JSON.stringify(config, null, 4)};
171
- `;
172
-
173
- fs.writeFileSync(configFilePath, configFileContent);
174
-
175
- console.log('Installing dependencies...');
176
- execSync('npm install', { stdio: 'inherit' });
177
-
178
- console.log('Configuration completed successfully!');
179
- } catch (error: any) {
180
- if (error instanceof Error && error.name === 'ExitPromptError') {
181
- console.log('👋 until next time!');
182
- } else {
183
- console.error('Error during configuration:', error);
184
- }
185
- }
186
- }
187
-
188
- main();
189
- */
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- //export * from "./logger";
2
- export * from "./requests";
3
- export * from "./sdk";
package/src/logger.ts DELETED
@@ -1,24 +0,0 @@
1
- import { ConfigInterface } from "@c-rex/interfaces";
2
- import { LogCategoriesType, LogLevelType } from "@c-rex/types";
3
-
4
- export class CrexLogger {
5
- private customerConfig: ConfigInterface;
6
-
7
- constructor(config: ConfigInterface) {
8
- this.customerConfig = config;
9
- }
10
-
11
- async log(level: LogLevelType, message: string, category?: LogCategoriesType) {
12
- if (typeof window === "undefined") {
13
- const { LoggerServer } = await import("./logs/server");
14
- const serverLog = new LoggerServer(this.customerConfig);
15
- serverLog.log(level, message, category);
16
- } else {
17
- fetch("/api/log", {
18
- method: "POST",
19
- headers: { "Content-Type": "application/json" },
20
- body: JSON.stringify({ level, message, category }),
21
- }).catch((err) => console.error("Erro ao enviar log", err));
22
- }
23
- }
24
- }
@@ -1,97 +0,0 @@
1
- import winston from 'winston';
2
- import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
- import { ConfigInterface } from '@c-rex/interfaces';
4
- import { LoggerServer } from '../server';
5
- import { MatomoTransport } from '../../transports/matomo';
6
- import { GraylogTransport } from '../../transports/graylog';
7
-
8
- jest.mock('winston', () => {
9
- const actual = jest.requireActual('winston');
10
- return {
11
- ...actual,
12
- createLogger: jest.fn(),
13
- transports: {
14
- Console: jest.fn().mockImplementation(() => ({
15
- name: 'ConsoleTransport',
16
- })),
17
- },
18
- };
19
- });
20
-
21
- jest.mock('../../transports/matomo', () => ({
22
- MatomoTransport: jest.fn().mockImplementation(() => ({
23
- name: 'MatomoTransport',
24
- })),
25
- }));
26
-
27
- jest.mock('../../transports/graylog', () => ({
28
- GraylogTransport: jest.fn().mockImplementation(() => ({
29
- name: 'GraylogTransport',
30
- })),
31
- }));
32
-
33
- describe('LoggerServer', () => {
34
- const mockConfig: ConfigInterface = {
35
- logs: {
36
- console: {
37
- minimumLevel: 'info',
38
- silent: false,
39
- },
40
- graylog: {
41
- minimumLevel: 'error',
42
- silent: true,
43
- },
44
- matomo: {
45
- categoriesLevel: [],
46
- },
47
- },
48
- customerConfig: {
49
- logs: {
50
- matomo: {
51
- categoriesLevel: [],
52
- },
53
- },
54
- },
55
- } as unknown as ConfigInterface;
56
-
57
- const mockLogger = {
58
- log: jest.fn(),
59
- };
60
-
61
- beforeEach(() => {
62
- (winston.createLogger as jest.Mock).mockReturnValue(mockLogger);
63
- });
64
-
65
- afterEach(() => {
66
- jest.clearAllMocks();
67
- });
68
-
69
- it('deve criar o logger com os transports corretos', () => {
70
- new LoggerServer(mockConfig);
71
-
72
- expect(winston.transports.Console).toHaveBeenCalledWith({
73
- level: 'info',
74
- silent: false,
75
- });
76
-
77
- expect(MatomoTransport).toHaveBeenCalledWith({
78
- level: 'info',
79
- silent: false,
80
- });
81
-
82
- expect(GraylogTransport).toHaveBeenCalledWith({
83
- level: 'error',
84
- silent: true,
85
- });
86
-
87
- expect(winston.createLogger).toHaveBeenCalled();
88
- });
89
-
90
- it('deve chamar logger.log com os parâmetros corretos', () => {
91
- const loggerServer = new LoggerServer(mockConfig);
92
-
93
- loggerServer.log('info' as LogLevelType, 'mensagem de teste', 'analytics' as LogCategoriesType);
94
-
95
- expect(mockLogger.log).toHaveBeenCalledWith('info', 'mensagem de teste', 'analytics');
96
- });
97
- });
@@ -1,38 +0,0 @@
1
- import winston from "winston"
2
- import { LOG_LEVELS } from "@c-rex/constants";
3
- import { MatomoTransport } from "../transports/matomo"
4
- import { GraylogTransport } from "../transports/graylog"
5
- import { LogLevelType, LogCategoriesType } from "@c-rex/types";
6
- import { ConfigInterface } from "@c-rex/interfaces";
7
-
8
- const logger = (config: ConfigInterface) => {
9
- return winston.createLogger({
10
- levels: LOG_LEVELS,
11
- transports: [
12
- new winston.transports.Console({
13
- level: config.logs.console.minimumLevel as string,
14
- silent: config.logs.console.silent,
15
- }),
16
- new MatomoTransport({
17
- level: config.logs.console.minimumLevel,
18
- silent: config.logs.console.silent,
19
- }),
20
- new GraylogTransport({
21
- level: config.logs.graylog.minimumLevel,
22
- silent: config.logs.graylog.silent,
23
- }),
24
- ],
25
- });
26
- }
27
-
28
- export class LoggerServer {
29
- logger: winston.Logger;
30
-
31
- constructor(config: ConfigInterface) {
32
- this.logger = logger(config);
33
- }
34
-
35
- log(level: LogLevelType, message: string, category?: LogCategoriesType) {
36
- this.logger.log(level, message, category);
37
- }
38
- }
package/src/requests.ts DELETED
@@ -1,62 +0,0 @@
1
- import axios, { AxiosResponse, Method, AxiosInstance } from "axios";
2
- import { API } from "@c-rex/constants";
3
- import { CrexLogger } from "./logger";
4
-
5
- interface APIGenericResponse<T> extends AxiosResponse {
6
- data: T;
7
- statusCode: number;
8
- }
9
-
10
- interface CallParams {
11
- url: string;
12
- method: Method;
13
- body?: any;
14
- headers?: any;
15
- params?: any;
16
- }
17
-
18
- export class CrexApi {
19
- private apiClient: AxiosInstance;
20
- private logger: CrexLogger;
21
-
22
- public constructor(baseUrl: string, logger: CrexLogger) {
23
- this.apiClient = axios.create({
24
- baseURL: baseUrl,
25
- headers: {
26
- "content-Type": "application/json",
27
- },
28
- });
29
- this.logger = logger;
30
- }
31
-
32
- async execute<T>({
33
- url,
34
- method,
35
- params,
36
- body,
37
- headers,
38
- }: CallParams): Promise<any> {
39
- let response: APIGenericResponse<T> | undefined = undefined;
40
-
41
- for (let retry = 0; retry < API.MAX_RETRY; retry++) {
42
- try {
43
- response = await this.apiClient.request({
44
- url,
45
- method,
46
- data: body,
47
- params,
48
- headers,
49
- });
50
- } catch (error) {
51
- this.logger.log("error", `API.execute error when request ${url}. Error: ${error}`);
52
- throw error;
53
- }
54
- }
55
-
56
- if (response) {
57
- return response.data
58
- }
59
-
60
- throw new Error("API.execute error: Failed to retrieve a valid response");
61
- }
62
- }
package/src/sdk.ts DELETED
@@ -1,29 +0,0 @@
1
- import { CrexApi } from "./requests";
2
- import { CrexLogger } from "./logger";
3
- import { ConfigInterface } from "@c-rex/interfaces";
4
-
5
- export class CrexSDK {
6
- private static instance: CrexSDK;
7
- public customerConfig!: ConfigInterface;
8
- public logger!: CrexLogger;
9
- public api!: CrexApi;
10
-
11
- public constructor(config: ConfigInterface) {
12
- if (CrexSDK.instance) {
13
- return CrexSDK.instance;
14
- }
15
-
16
- this.customerConfig = config;
17
- this.logger = new CrexLogger(this.customerConfig);
18
- this.api = new CrexApi(this.customerConfig.baseUrl, this.logger);
19
-
20
- CrexSDK.instance = this;
21
- }
22
-
23
- public static getInstance(): CrexSDK {
24
- if (!CrexSDK.instance) {
25
- throw new Error("SDK not initialized");
26
- }
27
- return CrexSDK.instance;
28
- }
29
- }
@@ -1,63 +0,0 @@
1
- import { GraylogTransport } from '../graylog';
2
- import { CrexSDK } from '../..';
3
- import Transport from 'winston-transport';
4
- import { LogCategoriesType, LogLevelType } from '@c-rex/types';
5
-
6
- jest.mock('../..', () => ({
7
- CrexSDK: {
8
- getInstance: jest.fn()
9
- }
10
- }));
11
-
12
- describe('GraylogTransport', () => {
13
- let transport: GraylogTransport;
14
- let mockLogFn: jest.Mock;
15
- const mockSDK = {
16
- customerConfig: {
17
- logs: {
18
- graylog: {
19
- categoriesLevel: ['Document']
20
- }
21
- }
22
- }
23
- };
24
-
25
- beforeEach(() => {
26
- mockLogFn = jest.fn();
27
-
28
- jest.clearAllMocks();
29
- (CrexSDK.getInstance as jest.Mock).mockReturnValue(mockSDK);
30
-
31
- transport = new GraylogTransport({});
32
- transport.graylogTransport.log = mockLogFn;
33
- });
34
-
35
- it('should initialize with transport options', () => {
36
- const transport = new GraylogTransport({ level: 'info' });
37
- expect(transport).toBeInstanceOf(Transport);
38
- });
39
-
40
- it('should log when category matches configured categories', () => {
41
- const logInfo = {
42
- level: 'info' as LogLevelType,
43
- message: 'teste',
44
- category: 'Document' as LogCategoriesType,
45
- };
46
-
47
- const callback = jest.fn();
48
- transport.log(logInfo, callback);
49
- expect(mockLogFn).toHaveBeenCalledWith(logInfo, callback);
50
- });
51
-
52
- it('should not log when category does not match', () => {
53
- const logInfo = {
54
- level: 'info' as LogLevelType,
55
- message: 'teste',
56
- category: 'UnmatchedCategory' as LogCategoriesType,
57
- };
58
-
59
- const callback = jest.fn();
60
- transport.log(logInfo, callback);
61
- expect(mockLogFn).not.toHaveBeenCalled();
62
- });
63
- });
@@ -1,64 +0,0 @@
1
- import { MatomoTransport } from '../matomo';
2
- import { CrexSDK } from '../..';
3
- import Transport from 'winston-transport';
4
- import { LogCategoriesType } from '@c-rex/types';
5
- import { LogLevelType } from '@c-rex/types';
6
-
7
- jest.mock('../..', () => ({
8
- CrexSDK: {
9
- getInstance: jest.fn()
10
- }
11
- }));
12
-
13
- describe('MatomoTransport', () => {
14
- let transport: MatomoTransport;
15
- let mockLogFn: jest.Mock;
16
- const mockSDK = {
17
- customerConfig: {
18
- logs: {
19
- matomo: {
20
- categoriesLevel: ['Document']
21
- }
22
- }
23
- }
24
- };
25
-
26
- beforeEach(() => {
27
- mockLogFn = jest.fn();
28
-
29
- jest.clearAllMocks();
30
- (CrexSDK.getInstance as jest.Mock).mockReturnValue(mockSDK);
31
-
32
- transport = new MatomoTransport({});
33
- transport.matomoTransport.log = mockLogFn;
34
- });
35
-
36
- it('should initialize with transport options', () => {
37
- const transport = new MatomoTransport({ level: 'info' });
38
- expect(transport).toBeInstanceOf(Transport);
39
- });
40
-
41
- it('should log when category matches configured categories', () => {
42
- const logInfo = {
43
- level: 'info' as LogLevelType,
44
- message: 'teste',
45
- category: 'Document' as LogCategoriesType,
46
- };
47
-
48
- const callback = jest.fn();
49
- transport.log(logInfo, callback);
50
- expect(mockLogFn).toHaveBeenCalledWith(logInfo, callback);
51
- });
52
-
53
- it('should not log when category does not match', () => {
54
- const logInfo = {
55
- level: 'info' as LogLevelType,
56
- message: 'teste',
57
- category: 'UnmatchedCategory' as LogCategoriesType,
58
- };
59
-
60
- const callback = jest.fn();
61
- transport.log(logInfo, callback);
62
- expect(mockLogFn).not.toHaveBeenCalled();
63
- });
64
- });
@@ -1,34 +0,0 @@
1
- import Transport from "winston-transport";
2
- import Graylog2Transport from "winston-graylog2";
3
- import { CrexSDK } from "..";
4
- import { LogCategoriesType, LogLevelType } from "@c-rex/types";
5
- import { ALL } from "@c-rex/constants";
6
-
7
- export class GraylogTransport extends Transport {
8
- public graylogTransport: any;
9
-
10
- constructor(opts: any) {
11
- super(opts);
12
-
13
- this.graylogTransport = new Graylog2Transport({
14
- name: "Periotto-TEST",
15
- silent: false,
16
- handleExceptions: false,
17
- graylog: {
18
- servers: [{ host: "localhost", port: 12201 }],
19
- },
20
- });
21
- }
22
-
23
- log(
24
- info: { level: LogLevelType, message: string, category: LogCategoriesType },
25
- callback: () => void,
26
- ): void {
27
- const SDK = CrexSDK.getInstance();
28
- const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel
29
-
30
- if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
31
- this.graylogTransport.log(info, callback);
32
- }
33
- }
34
- }
@@ -1,27 +0,0 @@
1
- import Transport from "winston-transport";
2
- import { CrexSDK } from "..";
3
- import { LogCategoriesType, LogLevelType } from "@c-rex/types";
4
- import { ALL } from "@c-rex/constants";
5
-
6
- export class MatomoTransport extends Transport {
7
- public matomoTransport: any;
8
-
9
- constructor(opts: any) {
10
- super(opts);
11
-
12
- this.matomoTransport = new Transport();
13
- }
14
-
15
- log(
16
- info: { level: LogLevelType, message: string, category: LogCategoriesType },
17
- callback: () => void,
18
- ): void {
19
- const SDK = CrexSDK.getInstance();
20
- const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel
21
-
22
- if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
23
-
24
- this.matomoTransport.log(info, callback);
25
- }
26
- }
27
- }