@apia/api 2.0.11 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/apiaApi.d.ts DELETED
@@ -1,156 +0,0 @@
1
- import { TModify } from '@apia/util';
2
- import { AxiosResponse } from 'axios';
3
- import QueryString from 'qs';
4
- import { IApiaApiRequestConfig, TApiaApiResult } from './types.js';
5
-
6
- declare function getConfig<LoadType>(outerBehaveConfig?: IApiaApiRequestConfig<LoadType>): IApiaApiRequestConfig<unknown> & IApiaApiRequestConfig<LoadType> & Partial<IApiaApiRequestConfig<unknown>>;
7
- type TApiaApiAxiosResponse<LoadType> = AxiosResponse<LoadType | null> & {
8
- hasError: boolean;
9
- hasMessages: boolean;
10
- };
11
- /**
12
- * IMPORTANT!! The ApiaApi is programmed under the slogan that
13
- * **should never throw an exception**. **Errors** coming from
14
- * connectivity or exceptions on the server **will be handled
15
- * automatically** by ApiaApi, using the notification system
16
- * of the application. It is possible to determine in what context they should
17
- * be thrown those exceptions (global, main, modal) using the
18
- * alertsCategory configuration properties **(see errorsHandling.md)**.
19
- *
20
- * @param url String, the url you want to call
21
- * @param config interface IApiaApiRequestConfig<DataType>;
22
- *
23
- * @throws Nothing
24
- *
25
- * @example
26
- *
27
- * ApiaApi.post<ResponseType>('url...', {
28
- axiosConfig?: AxiosRequestConfig;
29
-
30
- // Configuración de postData
31
- postData? unknown;
32
- postDataTreatement?: 'stringify' | undefined;
33
-
34
- // Configuración de queryString
35
- queryData?: string | Record<string, unknown>;
36
- stringifyOptions?: QueryString.IStringifyOptions;
37
-
38
- // Response validator,
39
- // If it returns true, everything continues correctly
40
- // If it returns false, the ApiaApi throws a standard error.
41
- // If it returns string, ApiaApi throws the error returned in the string.
42
- validateResponse?: (
43
- response: AxiosResponse<DataType | null>,
44
- ) => boolean | string;
45
-
46
- // Configuración de alertas
47
- alertsImportance?: TAlertImportance;
48
-
49
- // Configuración de ApiaApiHandler, falta documentar
50
- handleLoad?: boolean;
51
- eventsHandler?: IEventsHandler;
52
-
53
- // other configuration
54
- colors?: TColors;
55
- debug?: boolean;
56
- }
57
- * @returns The type of the return value depends on the type passed when calling the function. If there was an error it returns null.
58
- */
59
- declare function post<LoadType extends Record<string, unknown> = Record<string, unknown>, DataType = unknown>(url: string | TModify<IApiaApiRequestConfig<LoadType>, {
60
- postData?: DataType;
61
- postDataTreatement?: 'stringify';
62
- }>, config?: TModify<IApiaApiRequestConfig<LoadType>, {
63
- postData?: DataType;
64
- postDataTreatement?: 'stringify';
65
- }>): TApiaApiResult<LoadType>;
66
- declare function post<LoadType extends Record<string, unknown> = Record<string, unknown>, DataType = unknown>(config: TModify<IApiaApiRequestConfig<LoadType>, {
67
- postData?: DataType;
68
- postDataTreatement?: 'stringify';
69
- }>): TApiaApiResult<LoadType>;
70
- /**
71
- * IMPORTANTE!! El ApiaApi está programado bajo la consigna de que
72
- * **no debe tirar núnca una excepción**. **Los errores** provenientes
73
- * de la conectividad o de excepciones en el servidor **serán manejados
74
- * automáticamente** por el ApiaApi utilizando el sistema de notificaciones
75
- * de la aplicación. Es posible determinar en qué contexto deben
76
- * ser lanzadas esas excepciones (global, main, modal) utilizando las
77
- * propiedades de configuración alertsCategory **(ver errorsHandling.md)**.
78
- *
79
- * @param url String, el url al que se desea llamar
80
- * @param config interface IApiaApiRequestConfig<DataType>;
81
- *
82
- * @throws Nothing
83
- *
84
- * @example
85
- *
86
- * ApiaApi.get<TipoDeRespuesta>('url...', {
87
- axiosConfig?: AxiosRequestConfig;
88
-
89
- // Configuración de queryString
90
- queryData?: string | Record<string, unknown>;
91
- stringifyOptions?: QueryString.IStringifyOptions;
92
-
93
- // Validador de respuesta,
94
- // Si devuelve true, todo sigue correctamente
95
- // Si devuelve false, el ApiaApi tira un error estándar.
96
- // Si devuelve string, el ApiaApi tira el error devuelto en el string.
97
- validateResponse?: (
98
- response: AxiosResponse<DataType | null>,
99
- ) => boolean | string;
100
-
101
- // Configuración de alertas
102
- alertsImportance?: TAlertImportance;
103
-
104
- // Configuración de ApiaApiHandler, falta documentar
105
- handleLoad?: boolean;
106
- eventsHandler?: IEventsHandler;
107
-
108
- // Otra configuración
109
- colors?: TColors;
110
- debug?: boolean;
111
- }
112
- * @returns El tipo del valor devuelto depende del tipo pasado al llamar a la función. Si hubo un error devuelve null
113
- */
114
- declare function get<LoadType extends Record<string, unknown> = Record<string, unknown>>(url: string | IApiaApiRequestConfig<LoadType>, config?: IApiaApiRequestConfig<LoadType>): TApiaApiResult<LoadType>;
115
- declare function get<LoadType extends Record<string, unknown> = Record<string, unknown>>(config: IApiaApiRequestConfig<LoadType>): TApiaApiResult<LoadType>;
116
- declare const ApiaApi: {
117
- get: typeof get;
118
- getConfig: typeof getConfig;
119
- post: typeof post;
120
- };
121
- /**
122
- * Creates an url based on the general requirements of Apia.
123
- * If the ajaxUrl property is not passed, it will use the
124
- * window.URL_REQUEST_AJAX. Its use is very simple, just pass the objects you
125
- * want to appear in the query string.
126
- *
127
- * @example makeApiaUrl({
128
- * ajaxUrl: 'the.endpoint.you.want',
129
- * queryString: 'an=existent&query=string',
130
- * action: 'theAction',
131
- * anotherProp: 15
132
- * })
133
- *
134
- * @returns the well formed url, in the example, the response url is:
135
- * /context/the.endpoint.you.want?an=existent&query=string&anotherProp=15&tabId=...&tokenId=...&action=theAction
136
- */
137
- declare function makeApiaUrl(props?: {
138
- action?: string;
139
- ajaxUrl?: string;
140
- queryString?: string;
141
- stringifyOptions?: QueryString.IStringifyOptions;
142
- tabId?: string | number;
143
- preventAsXmlParameter?: boolean;
144
- avoidTabId?: boolean;
145
- [key: string]: unknown;
146
- }): string;
147
- declare global {
148
- interface Window {
149
- TAB_ID_REQUEST: string;
150
- CONTEXT: string;
151
- URL_REQUEST_AJAX: string;
152
- }
153
- }
154
-
155
- export { type TApiaApiAxiosResponse, ApiaApi as default, makeApiaUrl };
156
- //# sourceMappingURL=apiaApi.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"apiaApi.d.ts","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/apiaApi.js DELETED
@@ -1,458 +0,0 @@
1
- import axios from 'axios';
2
- import merge from 'lodash-es/merge';
3
- import QueryString from 'qs';
4
- import { session } from '@apia/session';
5
- import { debugDispatcher, parseXmlAsync, EventEmitter, arrayOrArray } from '@apia/util';
6
- import { notify, getNotificationMessageObj, dispatchNotifications } from '@apia/notifications';
7
- import { handle } from './ApiaApiHandler.js';
8
-
9
- debugDispatcher.on(
10
- "parseXml",
11
- async ([text]) => {
12
- const result = await parseXmlAsync(text);
13
- console.info(result);
14
- },
15
- "Acepta un par\xE1metro de tipo string y realiza un parseo como si fuera xml, convirti\xE9ndolo a objeto javascript."
16
- );
17
- const defaultConfig = {
18
- debug: false,
19
- colors: {
20
- exception: "red",
21
- alert: "yellow",
22
- message: "lightgreen"
23
- },
24
- handleLoad: false
25
- };
26
- const STORED_CONFIG = "ApiaApiConfig";
27
- let forcedConfig = {};
28
- const storedConfig = localStorage.getItem(STORED_CONFIG);
29
- if (storedConfig)
30
- forcedConfig = JSON.parse(storedConfig);
31
- function getConfig(outerBehaveConfig) {
32
- return merge({}, defaultConfig, outerBehaveConfig, forcedConfig);
33
- }
34
- function makeUrl(url, queryData, stringifyOptions) {
35
- let finalUrl = url;
36
- const questionMarkIndex = finalUrl.indexOf("?");
37
- if (questionMarkIndex === -1)
38
- finalUrl += "?";
39
- else if (questionMarkIndex !== finalUrl.length - 1 && !finalUrl.endsWith("&"))
40
- finalUrl += "&";
41
- let parsedUrl = `${finalUrl}${queryData ? QueryString.stringify(queryData, stringifyOptions) : ""}`;
42
- if (parsedUrl.endsWith("&") || parsedUrl.endsWith("?")) {
43
- parsedUrl = parsedUrl.slice(0, parsedUrl.length - 1);
44
- }
45
- return parsedUrl;
46
- }
47
- const getURLActionName = (url) => {
48
- const actionIdx = url.match(/action=(\w+)/)?.[1];
49
- return actionIdx ?? "noAction";
50
- };
51
- class ApiaActionsClass extends EventEmitter {
52
- }
53
- const ApiaActions = new ApiaActionsClass();
54
- function getColor(color, colors = defaultConfig.colors ?? {
55
- exception: "red",
56
- alert: "yellow",
57
- message: "green"
58
- }) {
59
- return colors[color];
60
- }
61
- const handleWrongResponse = (error) => {
62
- let errorMessage;
63
- if (typeof error !== "string") {
64
- if (error.message)
65
- errorMessage = error.message;
66
- else
67
- errorMessage = error.toString();
68
- } else
69
- errorMessage = error;
70
- notify({
71
- type: "danger",
72
- message: error.message.replaceAll("AxiosError", "Error")
73
- });
74
- console.log("%c ", "font-size:10vh");
75
- console.log("%cError in ApiaApi", "color:red;font-size:2em;font-weight:bold");
76
- console.log(`red/${errorMessage}`, { error });
77
- console.log("%c ", "font-size:10vh");
78
- };
79
- function isJsonResponse(response) {
80
- return response.headers["content-type"].match("application/json");
81
- }
82
- function isXmlResponse(response) {
83
- return response.headers["content-type"].match(
84
- /(?:application|text)?\/xml/
85
- );
86
- }
87
- function isHtmlResponse(response) {
88
- return response.headers["content-type"].match(
89
- /(?:application|text)?\/html/
90
- );
91
- }
92
- function handleActions(actions) {
93
- if (actions) {
94
- if (getConfig().debug)
95
- console.log(
96
- "%cHandled actions: ",
97
- `color: ${getConfig().colors?.message ?? "green"}`,
98
- { actions }
99
- );
100
- const actionsArray = arrayOrArray(actions.action);
101
- actionsArray.forEach((action) => {
102
- ApiaActions.emit("action", {
103
- ...action,
104
- param: arrayOrArray(action.param)
105
- });
106
- });
107
- }
108
- }
109
- function handleOnClose({
110
- exceptions,
111
- onClose,
112
- sysExceptions,
113
- sysMessages
114
- }) {
115
- try {
116
- import(
117
- /* webpackChunkName: "api-[request]" */
118
- `/api/onClose/${onClose}.ts`
119
- ).then(
120
- (func) => {
121
- if (exceptions || sysExceptions || sysMessages) {
122
- const notificationsObject = getNotificationMessageObj({
123
- exceptions,
124
- onClose,
125
- sysExceptions,
126
- sysMessages
127
- });
128
- if (notificationsObject)
129
- notificationsObject.forEach((notification) => {
130
- notify({
131
- ...notification,
132
- onClose: func.default
133
- });
134
- });
135
- else
136
- func.default();
137
- } else
138
- func.default();
139
- },
140
- (e) => {
141
- notify({
142
- message: `onClose action not found: ${String(e)}`,
143
- type: "danger"
144
- });
145
- }
146
- );
147
- } catch (e) {
148
- parseMessages({ exceptions, sysExceptions, sysMessages });
149
- console.error("Error while handling onClose");
150
- console.error(e);
151
- }
152
- }
153
- function parseMessages(response) {
154
- if (!response)
155
- return;
156
- const { exceptions, sysMessages, sysExceptions } = response;
157
- if (exceptions || sysExceptions || sysMessages) {
158
- try {
159
- dispatchNotifications({
160
- exceptions,
161
- sysExceptions,
162
- sysMessages
163
- });
164
- } catch (e) {
165
- handleWrongResponse(new Error(e));
166
- }
167
- }
168
- }
169
- const parseSuccessfulResponse = async (response, currentUrl, outerBehaveConfig = defaultConfig) => {
170
- const behaveConfig = getConfig(outerBehaveConfig);
171
- let parsedObj = void 0;
172
- if (isJsonResponse(response)) {
173
- if (typeof response.data === "string")
174
- parsedObj = JSON.parse(
175
- response.data.trim()
176
- );
177
- else if (typeof response.data === "object" && response.data)
178
- parsedObj = response.data;
179
- } else if (isXmlResponse(response)) {
180
- parsedObj = await parseXmlAsync(response.data).catch(
181
- (e) => {
182
- handleWrongResponse(new Error(e));
183
- }
184
- );
185
- } else if (isHtmlResponse(response)) {
186
- console.error(
187
- "El contenido devuelto es Html, no se esperaba esa respuesta"
188
- );
189
- return null;
190
- }
191
- if (behaveConfig.validateResponse) {
192
- const validateResult = await behaveConfig.validateResponse({
193
- ...response,
194
- data: parsedObj?.load ?? parsedObj
195
- });
196
- if (typeof validateResult === "string")
197
- throw new Error(`Validation error: ${validateResult}`);
198
- else if (!validateResult) {
199
- throw new Error("Error");
200
- }
201
- }
202
- if (parsedObj) {
203
- const {
204
- actions,
205
- onClose,
206
- exceptions,
207
- sysExceptions,
208
- sysMessages,
209
- load,
210
- ...rest
211
- } = parsedObj;
212
- if (rest.code === "-1" && exceptions) {
213
- session.invalidate();
214
- return null;
215
- }
216
- if (exceptions && behaveConfig.debug) {
217
- console.log(
218
- `%cparseSuccessfulResponse`,
219
- `color: ${getColor("exception", behaveConfig.colors)}`,
220
- {
221
- exceptions
222
- }
223
- );
224
- }
225
- if (sysExceptions && behaveConfig.debug) {
226
- console.log(
227
- `%cparseSuccessfulResponse`,
228
- `color: ${getColor("exception", behaveConfig.colors)}`,
229
- {
230
- sysExceptions
231
- }
232
- );
233
- }
234
- if (sysMessages && behaveConfig.debug) {
235
- console.log(
236
- `%cparseSuccessfulResponse`,
237
- `color: ${getColor("alert", behaveConfig.colors)}`,
238
- {
239
- sysMessages
240
- }
241
- );
242
- }
243
- handleActions(actions);
244
- if (behaveConfig.handleLoad && onClose)
245
- handleOnClose({
246
- exceptions,
247
- onClose,
248
- sysExceptions,
249
- sysMessages
250
- });
251
- else
252
- parseMessages({ exceptions, sysExceptions, sysMessages });
253
- if (load) {
254
- if (behaveConfig.handleLoad) {
255
- console.log(
256
- `%chandleLoad`,
257
- `color: ${getColor("message", behaveConfig.colors)}`,
258
- {
259
- load
260
- }
261
- );
262
- if (!handle(load, currentUrl, {
263
- methodsPath: outerBehaveConfig.methodsPath,
264
- modalConfiguration: {
265
- ...behaveConfig.modalConfiguration,
266
- onClose: () => {
267
- if (onClose)
268
- handleOnClose({
269
- exceptions,
270
- onClose,
271
- sysExceptions,
272
- sysMessages
273
- });
274
- if (behaveConfig.modalConfiguration?.onClose)
275
- behaveConfig.modalConfiguration?.onClose();
276
- }
277
- }
278
- })) {
279
- console.log(
280
- `%cunhandledLoad -> There is no handler defined`,
281
- `color: ${getColor("exception", behaveConfig.colors)}`,
282
- {
283
- load
284
- }
285
- );
286
- }
287
- }
288
- return { ...load, sysMessages, exceptions, sysExceptions };
289
- }
290
- return { ...rest, sysMessages, exceptions, sysExceptions };
291
- }
292
- return null;
293
- };
294
- async function handleResponse(result, currentUrl, outerBehaveConfig = defaultConfig) {
295
- const behaveConfig = getConfig(outerBehaveConfig);
296
- try {
297
- if (!result || result.data === void 0) {
298
- if (behaveConfig.debug)
299
- console.log(
300
- `%cApiaApi wrong response`,
301
- `color: ${getColor("alert", behaveConfig.colors)}`
302
- );
303
- } else {
304
- const parsedResponse = await parseSuccessfulResponse(
305
- result,
306
- currentUrl,
307
- behaveConfig
308
- );
309
- const action = getURLActionName(currentUrl);
310
- if (behaveConfig.debug)
311
- console.log(
312
- `%c <- ApiaApi.${result.config.method ?? ""} ${action} `,
313
- `color: ${getColor("message", behaveConfig.colors)}`,
314
- {
315
- data: parsedResponse
316
- }
317
- );
318
- return {
319
- ...result,
320
- data: parsedResponse,
321
- hasError: !!parsedResponse?.exceptions || !!parsedResponse?.sysExceptions,
322
- hasMessages: !!parsedResponse?.sysMessages
323
- };
324
- }
325
- } catch (e) {
326
- handleWrongResponse(new Error(e));
327
- return null;
328
- }
329
- return null;
330
- }
331
- async function post(par1, par2) {
332
- const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
333
- const configParameter = typeof par1 === "string" ? par2 ?? defaultConfig : par1;
334
- const behaveConfig = {
335
- ...getConfig(configParameter),
336
- postData: configParameter.postDataTreatement === "stringify" ? QueryString.stringify(
337
- configParameter.postData,
338
- configParameter.stringifyOptions
339
- ) : configParameter.postData
340
- };
341
- const parsedUrl = makeUrl(
342
- actualUrl,
343
- behaveConfig.queryData,
344
- behaveConfig.stringifyOptions
345
- );
346
- if (behaveConfig.debug) {
347
- const queryString = actualUrl.split("&");
348
- const action = getURLActionName(actualUrl);
349
- console.log(
350
- `%cApiaApi.post ${action}`,
351
- `color: ${getColor("message", behaveConfig.colors)}`,
352
- {
353
- url: parsedUrl,
354
- queryDataInURL: [...queryString],
355
- queryData: behaveConfig.queryData,
356
- formData: behaveConfig.postData,
357
- stringifyOptiopns: behaveConfig.stringifyOptions
358
- }
359
- );
360
- }
361
- const response = await axios.post(parsedUrl, behaveConfig.postData, behaveConfig.axiosConfig).catch((e) => {
362
- handleWrongResponse(new Error(e));
363
- });
364
- if (response) {
365
- const result = handleResponse(response, actualUrl, behaveConfig);
366
- return result;
367
- }
368
- return null;
369
- }
370
- async function get(par1, par2) {
371
- const actualUrl = typeof par1 !== "string" ? makeApiaUrl() : par1;
372
- const behaveConfig = getConfig(
373
- typeof par1 === "string" ? par2 ?? defaultConfig : par1
374
- );
375
- const parsedUrl = makeUrl(
376
- actualUrl,
377
- behaveConfig.queryData,
378
- behaveConfig.stringifyOptions
379
- );
380
- if (behaveConfig.debug)
381
- console.log(
382
- `%cApiaApi.get`,
383
- `color: ${getColor("message", behaveConfig.colors)}`,
384
- {
385
- url: parsedUrl
386
- }
387
- );
388
- const response = await axios.get(parsedUrl, behaveConfig.axiosConfig).catch((e) => {
389
- handleWrongResponse(new Error(e));
390
- });
391
- if (response) {
392
- const result = await handleResponse(
393
- response,
394
- actualUrl,
395
- behaveConfig
396
- );
397
- return result;
398
- }
399
- return null;
400
- }
401
- const ApiaApi = {
402
- get,
403
- getConfig,
404
- post
405
- };
406
- function makeApiaUrl(props) {
407
- let actualQueryData = {};
408
- if (props) {
409
- const {
410
- ajaxUrl,
411
- queryString: queryString2,
412
- stringifyOptions,
413
- shouldAvoidTabId,
414
- preventAsXmlParameter,
415
- avoidTabId,
416
- tabId: outerTabId,
417
- ...rest
418
- } = props;
419
- actualQueryData = { ...rest };
420
- }
421
- const queryString = QueryString.stringify(
422
- actualQueryData,
423
- props?.stringifyOptions ?? {
424
- arrayFormat: "repeat",
425
- encodeValuesOnly: false
426
- }
427
- );
428
- let actualAjaxUrl = props?.ajaxUrl ?? window.URL_REQUEST_AJAX;
429
- if (actualAjaxUrl.indexOf("?") === actualAjaxUrl.length - 1) {
430
- actualAjaxUrl = actualAjaxUrl.slice(0, actualAjaxUrl.length - 1);
431
- }
432
- if (!actualAjaxUrl.startsWith("/")) {
433
- actualAjaxUrl = `/${actualAjaxUrl}`;
434
- }
435
- const match = window.TAB_ID_REQUEST.match(/tokenId=(\w+)/);
436
- const currentTokenId = (match ?? [])[1];
437
- let tabId = (props?.tabId ? `&tabId=${props.tabId}&tokenId=${currentTokenId}` : window.TAB_ID_REQUEST).slice(1);
438
- if (props?.avoidTabId) {
439
- tabId = "";
440
- }
441
- let { CONTEXT } = window;
442
- if (CONTEXT?.endsWith("/")) {
443
- CONTEXT += CONTEXT.slice(0, CONTEXT.length - 1);
444
- }
445
- let timestamp = `timestamp=${Date.now()}&`;
446
- if (props?.queryString && props.queryString.includes("timestamp=") || queryString?.includes("timestamp=")) {
447
- timestamp = "";
448
- }
449
- const contextWord = CONTEXT.replaceAll("/", "");
450
- actualAjaxUrl = actualAjaxUrl.match(
451
- new RegExp(`^(?:(?:/?${contextWord})?/)?(.+)$`)
452
- )?.[1];
453
- return `${contextWord ? "/" : ""}${contextWord}/${actualAjaxUrl}?${timestamp}${!props?.preventAsXmlParameter ? "asXml=true&" : ""}${props?.queryString ? `${props.queryString}&` : ""}${queryString ? `${queryString}&` : ""}${tabId}`;
454
- }
455
- var ApiaApi$1 = ApiaApi;
456
-
457
- export { ApiaActions, ApiaApi$1 as default, isHtmlResponse, isJsonResponse, isXmlResponse, makeApiaUrl, parseMessages, parseSuccessfulResponse };
458
- //# sourceMappingURL=apiaApi.js.map