sysone-api-mapper 1.0.136 → 1.0.138

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +2 -1
  2. package/src/mapper/Mapper.js +101 -183
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sysone-api-mapper",
3
- "version": "1.0.136",
3
+ "version": "1.0.138",
4
4
  "description": "Paquete mapper para portal de productores",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -17,6 +17,7 @@
17
17
  "@babel/plugin-proposal-class-properties": "^7.18.6",
18
18
  "@babel/preset-env": "^7.20.2",
19
19
  "@babel/preset-react": "^7.18.6",
20
+ "@sysone/components": "^1.0.166-dev",
20
21
  "antd": "^4.21.4",
21
22
  "axios": "^1.6.0",
22
23
  "babel-loader": "^9.1.2",
@@ -1,109 +1,43 @@
1
1
  import axiosInstance from "../../axiosInstance";
2
2
  import { methods, tenantsConfig } from "./endpointsConfig";
3
3
 
4
- const getApiMapperConfig = () => {
5
- // 1. Intentar desde variables de entorno compiladas (Webpack DefinePlugin)
6
- if (process.env.API_MAPPER) {
7
- try {
8
- // Si es un string, parsearlo
9
- const parsed = typeof process.env.API_MAPPER === 'string'
10
- ? JSON.parse(process.env.API_MAPPER)
11
- : process.env.API_MAPPER;
12
-
13
- if (parsed && Object.keys(parsed).length > 0) {
14
- console.log("✅ Usando API_MAPPER de process.env", parsed);
15
- return parsed;
16
- }
17
- } catch (error) {
18
- console.error("❌ Error parseando API_MAPPER de process.env:", error);
19
- }
20
- }
21
4
 
22
- // 2. Intentar desde variable global inyectada
23
- if (window.__API_MAPPER__ && Object.keys(window.__API_MAPPER__).length > 0) {
24
- console.log("✅ Usando API_MAPPER de window");
25
- return window.__API_MAPPER__;
26
- }
27
-
28
- console.error("❌ No se pudo cargar API_MAPPER desde ninguna fuente");
29
- return null;
30
- };
5
+ let apiConfig = null;
31
6
 
32
- const getSalesAgent = () => {
33
- return localStorage.getItem("sales-agent") ||
34
- window.__INTERMEDIARY_CODE__ ||
35
- null;
36
- };
7
+ export const configureApiMapper = (config) => {
8
+ if (!config?.baseURL) {
9
+ throw new Error("apiMapper requires baseURL");
10
+ }
37
11
 
38
- const getSalesChannel = () => {
39
- return localStorage.getItem("sales-channel") ||
40
- window.__INTERMEDIARY_CODE__ ||
41
- null;
12
+ apiConfig = {
13
+ baseURL: config.baseURL,
14
+ headers: config.headers || {},
15
+ };
42
16
  };
43
17
 
44
- const getDynamicHeaders = (tenant) => {
45
- if (tenant === "cnp") {
46
- // Intenta obtener el X-Agent de localStorage (inyectado desde el front)
47
- const xAgent = localStorage.getItem("intermediaryCode") ||
48
- window.__INTERMEDIARY_CODE__ ||
49
- configs.cnp.headers["X-Agent"];
50
-
51
- const salesCode = getSalesAgent();
52
- const salesChannel = getSalesChannel();
53
-
54
- return {
55
- "X-Agent": xAgent,
56
- "X-Sales-Channel": salesChannel || xAgent,
57
- "X-Sales-Agent": salesCode || xAgent
58
- };
18
+ const getConfig = () => {
19
+ if (!apiConfig) {
20
+ throw new Error(
21
+ "apiMapper not configured. Call configureApiMapper() first."
22
+ );
59
23
  }
60
- return {};
24
+ return apiConfig;
61
25
  };
62
26
 
63
- const API_MAPPER = getApiMapperConfig();
64
-
65
- if (!API_MAPPER) {
66
- console.error("⚠️ API_MAPPER no está configurado");
67
- }
68
-
69
- const configs = {
70
- default: {
71
- baseURL: API_MAPPER?.default?.baseURL || '',
72
- headers: {
73
- ["X-Tenant"]: API_MAPPER?.default?.headers?.["X-Tenant"] || '',
74
- ["X-User"]: API_MAPPER?.default?.headers?.["X-User"] || '',
75
- ["X-Api-Key"]: API_MAPPER?.default?.headers?.["X-Api-Key"] || '',
76
- ["X-Origin"]: "sysone-api-mapper"
77
- },
78
- },
79
- cnp: {
80
- baseURL: API_MAPPER?.cnp?.baseURL || '',
81
- headers: {
82
- ["X-Channel"]: API_MAPPER?.cnp?.headers?.["X-Channel"] || '',
83
- ["X-Agent"]: API_MAPPER?.cnp?.headers?.["X-Agent"] || '',
84
- ["X-Client"]: API_MAPPER?.cnp?.headers?.["X-Client"] || '',
85
- ["Ocp-Apim-Subscription-Key"]: API_MAPPER?.cnp?.headers?.["Ocp-Apim-Subscription-Key"] || '',
86
- ["X-Origin"]: "sysone-api-mapper",
87
- ["X-Sales-Agent"]: API_MAPPER?.cnp?.headers?.["X-Agent"] || '',
88
- ["X-Sales-Channel"]: API_MAPPER?.cnp?.headers?.["X-Agent"] || '',
89
- },
90
- },
27
+ /**
28
+ * Normaliza tenant (ej: "cnp/foo" → "cnp")
29
+ */
30
+ const normalizeTenant = (tenant) => {
31
+ if (!tenant || typeof tenant !== "string") return tenant;
32
+ return tenant.split("/")[0];
91
33
  };
92
34
 
93
35
  const getUrl = (serviceUrl, routeParams) => {
94
36
  if (!routeParams || routeParams.length === 0) return serviceUrl;
95
- return serviceUrl.replace(/{(\d+)}/g, function (match, routeParamNumber) {
96
- return routeParams[routeParamNumber]
97
- ? routeParams[routeParamNumber]
98
- : match;
99
- });
100
- };
101
37
 
102
- const normalizeTenant = (tenant) => {
103
- if (!tenant || typeof tenant !== "string") return tenant;
104
-
105
- // Toma solo lo que está antes del primer "/"
106
- return tenant.split("/")[0];
38
+ return serviceUrl.replace(/{(\d+)}/g, (match, index) =>
39
+ routeParams[index] !== undefined ? routeParams[index] : match
40
+ );
107
41
  };
108
42
 
109
43
 
@@ -114,110 +48,94 @@ export const apiMapper = async (
114
48
  params = null,
115
49
  additionalHeaders = {}
116
50
  ) => {
117
- try {
118
- const configData = tenantsConfig[endpointCode];
119
- const normalizedTenant = normalizeTenant(tenant);
120
- if (!configData)
121
- throw new Error(`Endpoint no configurado: ${endpointCode}`);
51
+ /* -------- Endpoint config -------- */
122
52
 
123
- const endpointData = configData[normalizedTenant] ?? configData.default;
53
+ const configData = tenantsConfig[endpointCode];
54
+ if (!configData) {
55
+ throw new Error(`Endpoint no configurado: ${endpointCode}`);
56
+ }
124
57
 
125
- if (endpointData === null) {
126
- console.warn(`⚠️ No hay configuración para el endpoint ${endpointCode} y tenant ${tenant}, y no existe configuración por defecto.`);
127
- throw new Error(`No hay configuración para el endpoint ${endpointCode} y tenant ${tenant}`);
128
- }
58
+ const normalizedTenant = normalizeTenant(tenant);
129
59
 
130
- let config;
60
+ const endpointData =
61
+ configData[normalizedTenant] ?? configData.default;
131
62
 
132
- if (!configs) {
133
- throw new Error("No se pudo cargar la configuración del API Mapper");
134
- }
63
+ if (!endpointData) {
64
+ throw new Error(
65
+ `No hay configuración para endpoint ${endpointCode} y tenant ${normalizedTenant}`
66
+ );
67
+ }
68
+
69
+ /* -------- Axios config -------- */
135
70
 
136
- const dynamicHeaders = getDynamicHeaders(normalizedTenant);
71
+ const { baseURL, headers } = getConfig();
137
72
 
138
- if (normalizedTenant === "cnp") {
139
- config = {
140
- ...configs.cnp,
73
+ const axiosConfig = {
74
+ baseURL,
75
+ headers: {
76
+ ...headers,
77
+ ...additionalHeaders,
78
+ },
79
+ validateStatus: (s) => s < 500,
80
+ };
81
+
82
+ const url = getUrl(endpointData.url, routeParams);
83
+
84
+ /* -------- Request -------- */
85
+
86
+ switch (endpointData.method) {
87
+ case methods.GET: {
88
+ const {
89
+ mappedParams,
90
+ responseType,
91
+ headers: requestHeaders,
92
+ ...otherOptions
93
+ } = endpointData.requestMapper(params);
94
+
95
+ const response = await axiosInstance.get(url, {
96
+ ...axiosConfig,
97
+ params: mappedParams,
98
+ responseType,
141
99
  headers: {
142
- ...configs.cnp.headers,
143
- ...dynamicHeaders,
144
- ...additionalHeaders,
145
- }
146
- };
147
- } else {
148
- config = {
149
- ...configs.default,
100
+ ...axiosConfig.headers,
101
+ ...requestHeaders,
102
+ },
103
+ ...otherOptions,
104
+ });
105
+
106
+ return endpointData.responseMapper(response);
107
+ }
108
+
109
+ case methods.POST: {
110
+ const { mappedPostParams, mappedBody, headers: requestHeaders } =
111
+ endpointData.requestMapper(params);
112
+
113
+ const response = await axiosInstance.post(url, mappedBody, {
114
+ ...axiosConfig,
115
+ params: mappedPostParams,
150
116
  headers: {
151
- ...configs.default.headers,
152
- ["X-Tenant"]: normalizedTenant,
153
- ["X-User"]: normalizedTenant,
154
- ...additionalHeaders
117
+ ...axiosConfig.headers,
118
+ ...requestHeaders,
155
119
  },
156
- };
120
+ });
121
+
122
+ return endpointData.responseMapper(response.data);
123
+ }
124
+
125
+ case methods.PUT: {
126
+ const response = await axiosInstance.put(url, params, axiosConfig);
127
+ return endpointData.responseMapper(response.data);
157
128
  }
158
129
 
159
- config = {
160
- ...config,
161
- validateStatus: (status) => status < 500,
162
- };
163
-
164
- const urlWithParams = getUrl(endpointData.url, routeParams);
165
- const fullUrl = `${config.baseURL}${urlWithParams}`.replace(/([^:]\/)\/+/g, "$1");
166
-
167
- let response;
168
- let request;
169
-
170
- switch (endpointData.method) {
171
- case methods.GET:
172
- request = endpointData.requestMapper(params);
173
- const { mappedParams, responseType, headers: requestHeaders, ...otherOptions } = request;
174
-
175
- response = await axiosInstance.get(fullUrl, {
176
- ...config,
177
- params: mappedParams,
178
- responseType: responseType,
179
- headers: {
180
- ...config.headers,
181
- ...requestHeaders
182
- },
183
- validateStatus: config.validateStatus,
184
- ...otherOptions
185
- });
186
- return endpointData.responseMapper(response);
187
-
188
- case methods.POST:
189
- request = endpointData.requestMapper(params);
190
- const { mappedPostParams, mappedBody } = request;
191
- response = await axiosInstance.post(fullUrl, mappedBody, {
192
- params: mappedPostParams,
193
- headers: config.headers,
194
- validateStatus: config.validateStatus,
195
- });
196
- return endpointData.responseMapper(response.data);
197
-
198
- case methods.PUT:
199
- response = await axiosInstance.put(fullUrl, params, {
200
- headers: config.headers,
201
- validateStatus: config.validateStatus,
202
- });
203
- return endpointData.responseMapper(response.data);
204
-
205
- case methods.DELETE:
206
- response = await axiosInstance.delete(fullUrl, {
207
- data: params,
208
- headers: config.headers,
209
- validateStatus: config.validateStatus,
210
- });
211
- return endpointData.responseMapper(response.data);
212
-
213
- default:
214
- response = null;
215
- throw new Error(
216
- "Request error: Method not allowed. Only use GET, POST, PUT, DELETE"
217
- );
130
+ case methods.DELETE: {
131
+ const response = await axiosInstance.delete(url, {
132
+ ...axiosConfig,
133
+ data: params,
134
+ });
135
+ return endpointData.responseMapper(response.data);
218
136
  }
219
- } catch (e) {
220
- console.error("❌ Error en apiMapper:", e);
221
- throw e;
137
+
138
+ default:
139
+ throw new Error("HTTP method not supported");
222
140
  }
223
141
  };