@zauru-sdk/services 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENCE.md +11 -0
- package/dist/common.server.d.ts +55 -0
- package/dist/common.server.js +179 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/sessions/sessions.server.d.ts +2 -0
- package/dist/sessions/sessions.server.js +13 -0
- package/dist/sessions/upstash.server.d.ts +1 -0
- package/dist/sessions/upstash.server.js +52 -0
- package/dist/zauru/httpGraphQL.server.d.ts +2 -0
- package/dist/zauru/httpGraphQL.server.js +37 -0
- package/dist/zauru/httpOauth.server.d.ts +2 -0
- package/dist/zauru/httpOauth.server.js +37 -0
- package/dist/zauru/httpZauru.server.d.ts +14 -0
- package/dist/zauru/httpZauru.server.js +51 -0
- package/dist/zauru/zauru-agencies.server.d.ts +9 -0
- package/dist/zauru/zauru-agencies.server.js +21 -0
- package/dist/zauru/zauru-profiles.server.d.ts +167 -0
- package/dist/zauru/zauru-profiles.server.js +68 -0
- package/package.json +31 -0
- package/src/common.server.ts +293 -0
- package/src/index.ts +11 -0
- package/src/sessions/sessions.server.ts +17 -0
- package/src/sessions/upstash.server.ts +55 -0
- package/src/zauru/httpGraphQL.server.ts +55 -0
- package/src/zauru/httpOauth.server.ts +55 -0
- package/src/zauru/httpZauru.server.ts +78 -0
- package/src/zauru/zauru-agencies.server.ts +35 -0
- package/src/zauru/zauru-profiles.server.ts +243 -0
- package/tsconfig.json +24 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Change Log
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
+
|
|
6
|
+
## [1.0.4](https://github.com/intuitiva/zauru-typescript-sdk/compare/v1.0.3...v1.0.4) (2024-03-15)
|
|
7
|
+
|
|
8
|
+
**Note:** Version bump only for package @zauru-sdk/services
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
## [1.0.3](https://github.com/intuitiva/zauru-typescript-sdk/compare/v1.0.2...v1.0.3) (2024-03-15)
|
|
15
|
+
|
|
16
|
+
**Note:** Version bump only for package @zauru-sdk/services
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## [1.0.2](https://github.com/intuitiva/zauru-typescript-sdk/compare/v1.0.1...v1.0.2) (2024-03-15)
|
|
23
|
+
|
|
24
|
+
**Note:** Version bump only for package @zauru-sdk/services
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## 1.0.1 (2024-03-15)
|
|
31
|
+
|
|
32
|
+
**Note:** Version bump only for package @zauru-sdk/services
|
package/LICENCE.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Released under MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2013 Mark Otto.
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2017 Andrew Fong.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
8
|
+
|
|
9
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { Session } from "@remix-run/node";
|
|
2
|
+
import { AxiosRequestHeaders } from "axios";
|
|
3
|
+
import { AxiosUtilsResponse } from "./zauru/httpZauru.server.js";
|
|
4
|
+
import { Agency, OauthProfile, ProfileResponse } from "./zauru/zauru-profiles.server.js";
|
|
5
|
+
import { EmployeeGraphQL } from "@zauru-sdk/graphql";
|
|
6
|
+
/**
|
|
7
|
+
* loginWebApp
|
|
8
|
+
* @param session
|
|
9
|
+
* @param codeValue
|
|
10
|
+
* @param cookie
|
|
11
|
+
* @returns
|
|
12
|
+
*/
|
|
13
|
+
export declare const loginWebApp: (session: Session, codeValue: string, cookie: string) => Promise<AxiosUtilsResponse<{
|
|
14
|
+
headers: any;
|
|
15
|
+
oauthProfile: OauthProfile;
|
|
16
|
+
employeeProfile: EmployeeGraphQL;
|
|
17
|
+
userProfile: ProfileResponse;
|
|
18
|
+
agencyProfile: Agency;
|
|
19
|
+
}>>;
|
|
20
|
+
export type GraphQLToken = {
|
|
21
|
+
status: number;
|
|
22
|
+
message: string;
|
|
23
|
+
token: string;
|
|
24
|
+
expires: string;
|
|
25
|
+
expiresMsg: string;
|
|
26
|
+
graphqlUrl: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Obtiene los headers que se usan en todos los endpoints de zauru
|
|
30
|
+
* @param cookie
|
|
31
|
+
* @param _session La session es opcional, se envía sólo si ya se tiene a la mano, para ya no volverla a consultar.
|
|
32
|
+
* @returns
|
|
33
|
+
*/
|
|
34
|
+
export declare const getHeaders: (cookie: string | null, _session?: Session | null, config?: {
|
|
35
|
+
token: string;
|
|
36
|
+
username: string;
|
|
37
|
+
} | null, extraConfig?: {
|
|
38
|
+
withOutContentType: string;
|
|
39
|
+
}) => Promise<{
|
|
40
|
+
[key: string]: string;
|
|
41
|
+
}>;
|
|
42
|
+
/**
|
|
43
|
+
* getGraphQLAPIHeaders
|
|
44
|
+
* @param session
|
|
45
|
+
* @returns
|
|
46
|
+
*/
|
|
47
|
+
export declare const getGraphQLAPIHeaders: (session: Session) => Promise<AxiosRequestHeaders>;
|
|
48
|
+
export type SessionMessage = {
|
|
49
|
+
id: string;
|
|
50
|
+
title: string;
|
|
51
|
+
message: string;
|
|
52
|
+
};
|
|
53
|
+
export declare const saveSessionMessage: (session: Session, info: SessionMessage) => Promise<void>;
|
|
54
|
+
export declare const deleteSessionMessage: (session: Session, id: string) => Promise<boolean>;
|
|
55
|
+
export declare function generateDistinctCode(prefix: string): string;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { redirect } from "@remix-run/node";
|
|
2
|
+
import { commitSession, getSession } from "./sessions/sessions.server.js";
|
|
3
|
+
import chalk from "chalk";
|
|
4
|
+
import httpZauru, { handlePossibleAxiosErrors, } from "./zauru/httpZauru.server.js";
|
|
5
|
+
import { getAgencyInfo, getEmployeeInfo, getOauthUserInfo, getProfileInformation, } from "./zauru/zauru-profiles.server.js";
|
|
6
|
+
/**
|
|
7
|
+
* loginWebApp
|
|
8
|
+
* @param session
|
|
9
|
+
* @param codeValue
|
|
10
|
+
* @param cookie
|
|
11
|
+
* @returns
|
|
12
|
+
*/
|
|
13
|
+
export const loginWebApp = async (session, codeValue, cookie) => {
|
|
14
|
+
return handlePossibleAxiosErrors(async () => {
|
|
15
|
+
const userInfoResponse = await getOauthUserInfo(codeValue ?? "");
|
|
16
|
+
if (userInfoResponse.error) {
|
|
17
|
+
throw new Error(userInfoResponse.userMsg);
|
|
18
|
+
}
|
|
19
|
+
const userInfo = userInfoResponse.data;
|
|
20
|
+
session.set("username", userInfo?.username);
|
|
21
|
+
session.set("token", userInfo?.api_key);
|
|
22
|
+
session.set("code", codeValue);
|
|
23
|
+
session.set("name", userInfo?.name);
|
|
24
|
+
session.set("email", userInfo?.email);
|
|
25
|
+
session.set("employee_id", userInfo?.employee_id);
|
|
26
|
+
const headers = await getHeaders(cookie, session, {
|
|
27
|
+
token: userInfo?.api_key ?? "",
|
|
28
|
+
username: userInfo?.username ?? "",
|
|
29
|
+
});
|
|
30
|
+
const res_emp = await getEmployeeInfo(userInfo?.employee_id ?? 0, headers);
|
|
31
|
+
if (res_emp.error) {
|
|
32
|
+
throw new Error(res_emp.userMsg);
|
|
33
|
+
}
|
|
34
|
+
const empInfo = res_emp.data;
|
|
35
|
+
session.set("agency_id", empInfo?.agency_id);
|
|
36
|
+
session.set("email", empInfo?.email);
|
|
37
|
+
session.set("selectedEntity", empInfo?.entity_id);
|
|
38
|
+
const profileInfoResponse = await getProfileInformation(headers);
|
|
39
|
+
if (profileInfoResponse.error) {
|
|
40
|
+
throw new Error(profileInfoResponse.userMsg);
|
|
41
|
+
}
|
|
42
|
+
const profileInfo = profileInfoResponse.data;
|
|
43
|
+
if (!profileInfo?.memberships?.length) {
|
|
44
|
+
throw new Error("El usuario no tiene suscripciones...");
|
|
45
|
+
}
|
|
46
|
+
const membership = profileInfo?.memberships?.filter((member) => member?.entity?.id === empInfo?.entity_id);
|
|
47
|
+
if (!membership) {
|
|
48
|
+
throw new Error("No se encontró una suscripción para este usuario en la entidad asignada.");
|
|
49
|
+
}
|
|
50
|
+
if (membership?.length)
|
|
51
|
+
session.set("entityName", membership[0]?.entity?.name);
|
|
52
|
+
const agencyInfoResponse = await getAgencyInfo(headers, session);
|
|
53
|
+
if (agencyInfoResponse.error) {
|
|
54
|
+
throw new Error(agencyInfoResponse.userMsg);
|
|
55
|
+
}
|
|
56
|
+
session.set("agency_name", agencyInfoResponse.data?.name);
|
|
57
|
+
return {
|
|
58
|
+
headers,
|
|
59
|
+
oauthProfile: userInfo,
|
|
60
|
+
employeeProfile: empInfo,
|
|
61
|
+
userProfile: profileInfo,
|
|
62
|
+
agencyProfile: agencyInfoResponse.data,
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Obtiene los headers que se usan en todos los endpoints de zauru
|
|
68
|
+
* @param cookie
|
|
69
|
+
* @param _session La session es opcional, se envía sólo si ya se tiene a la mano, para ya no volverla a consultar.
|
|
70
|
+
* @returns
|
|
71
|
+
*/
|
|
72
|
+
export const getHeaders = async (cookie, _session, config, extraConfig) => {
|
|
73
|
+
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Session and Header Info<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
|
74
|
+
const session = _session ?? (await getSession(cookie));
|
|
75
|
+
if (!session.has("username") && !config) {
|
|
76
|
+
redirect("/");
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
const headers = {
|
|
80
|
+
"X-User-Email": config?.username ?? session.get("username"),
|
|
81
|
+
"X-User-Token": config?.token ?? session.get("token"),
|
|
82
|
+
"Content-type": "application/json",
|
|
83
|
+
Accept: "application/json",
|
|
84
|
+
};
|
|
85
|
+
if (extraConfig?.withOutContentType) {
|
|
86
|
+
delete headers["Content-type"];
|
|
87
|
+
}
|
|
88
|
+
return headers;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* getGraphQLToken
|
|
92
|
+
* @param session
|
|
93
|
+
* @returns
|
|
94
|
+
*/
|
|
95
|
+
async function getGraphQLToken(session) {
|
|
96
|
+
return handlePossibleAxiosErrors(async () => {
|
|
97
|
+
const token = (await session.get("graphqlToken"));
|
|
98
|
+
const headers = (await getHeaders(null, session));
|
|
99
|
+
const tokenHasExpired = token &&
|
|
100
|
+
token.expires &&
|
|
101
|
+
new Date(new Date().getTime() - 3 * 60 * 60 * 1000) >=
|
|
102
|
+
new Date(token.expires);
|
|
103
|
+
//Si no hay token, es la primera vez que se recibe, lo voy a traer de zauru
|
|
104
|
+
if (!token || tokenHasExpired) {
|
|
105
|
+
tokenHasExpired
|
|
106
|
+
? console.log(chalk.yellow(`=============== ⚠️ EL TOKEN GRAPHQL ESTÁ EXPIRADO ⚠️ ====================`))
|
|
107
|
+
: console.log(chalk.yellow(`=============== ⚠️ NO HAY UN TOKEN GRAPHQL GUARDADO ⚠️ ====================`));
|
|
108
|
+
const responseToken = await httpZauru.get("/apps/graphql.json", {
|
|
109
|
+
headers,
|
|
110
|
+
});
|
|
111
|
+
if (responseToken.data) {
|
|
112
|
+
session.set("graphqlToken", responseToken.data);
|
|
113
|
+
await commitSession(session);
|
|
114
|
+
console.log(chalk.green(`=============== ✅ TOKEN GRAPHQL GUARDADO EN SESION Y DEVUELTO ✅ ====================`));
|
|
115
|
+
return responseToken.data;
|
|
116
|
+
}
|
|
117
|
+
console.log(chalk.red(`=============== ❗ NO HAY INFORMACIÓN OBTENIDA DEL REQUEST A ZAURU - GET_TOKEN ❗ ====================`));
|
|
118
|
+
throw new Error("No viene información en la solicitud de getGraphQLToken a Zauru");
|
|
119
|
+
}
|
|
120
|
+
//Si ya está guardado un token en la sesión y aún no a expirado.
|
|
121
|
+
return token;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* getGraphQLAPIHeaders
|
|
126
|
+
* @param session
|
|
127
|
+
* @returns
|
|
128
|
+
*/
|
|
129
|
+
export const getGraphQLAPIHeaders = async (session) => {
|
|
130
|
+
const { data: token, error, userMsg } = await getGraphQLToken(session);
|
|
131
|
+
if (error) {
|
|
132
|
+
console.log(chalk.red(`=============== ❗ OCURRIÓ UN ERROR DEL REQUEST A ZAURU - GET_TOKEN ❗ ==================== ${userMsg}`));
|
|
133
|
+
return {
|
|
134
|
+
Authorization: `Bearer token_no_existe`,
|
|
135
|
+
"Content-Type": "application/json",
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
Authorization: `Bearer ${token?.token}`,
|
|
140
|
+
"Content-Type": "application/json",
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
export const saveSessionMessage = async (session, info) => {
|
|
144
|
+
const updateTasks = (session.get("sessionMessages") ??
|
|
145
|
+
[]);
|
|
146
|
+
session.set("updateTasks", [...updateTasks, info]);
|
|
147
|
+
await commitSession(session);
|
|
148
|
+
};
|
|
149
|
+
export const deleteSessionMessage = async (session, id) => {
|
|
150
|
+
let updateTasks = session.get("sessionMessages");
|
|
151
|
+
if (Array.isArray(updateTasks) &&
|
|
152
|
+
updateTasks.some((task) => task.id === id)) {
|
|
153
|
+
//La elimino de la lista
|
|
154
|
+
updateTasks = updateTasks.filter((task) => task.id !== id);
|
|
155
|
+
session.set("sessionMessages", updateTasks);
|
|
156
|
+
await commitSession(session);
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
return false;
|
|
160
|
+
};
|
|
161
|
+
function generarUUID() {
|
|
162
|
+
// Retorna un arreglo de 9 bytes con valores aleatorios
|
|
163
|
+
const array = new Uint8Array(9);
|
|
164
|
+
crypto.getRandomValues(array);
|
|
165
|
+
// Convertir Uint8Array a array normal
|
|
166
|
+
const normalArray = Array.from(array);
|
|
167
|
+
// Codificación en base 64
|
|
168
|
+
const base64 = btoa(String.fromCharCode.apply(null, normalArray))
|
|
169
|
+
.replace("+", "0") // Reemplaza caracteres no alfanuméricos
|
|
170
|
+
.replace("/", "1")
|
|
171
|
+
.substring(0, 11); // Acorta a 11 caracteres
|
|
172
|
+
return base64;
|
|
173
|
+
}
|
|
174
|
+
// Función para generar un código de producto a partir de un UUID
|
|
175
|
+
export function generateDistinctCode(prefix) {
|
|
176
|
+
const uuid = generarUUID();
|
|
177
|
+
const codigoProducto = `${prefix}-${uuid}`;
|
|
178
|
+
return codigoProducto;
|
|
179
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./common.server.js";
|
|
2
|
+
export * from "./sessions/sessions.server.js";
|
|
3
|
+
export * from "./sessions/upstash.server.js";
|
|
4
|
+
export * from "./zauru/httpGraphQL.server.js";
|
|
5
|
+
export * from "./zauru/httpOauth.server.js";
|
|
6
|
+
export * from "./zauru/httpZauru.server.js";
|
|
7
|
+
export * from "./zauru/zauru-agencies.server.js";
|
|
8
|
+
export * from "./zauru/zauru-profiles.server.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from "./common.server.js";
|
|
2
|
+
export * from "./sessions/sessions.server.js";
|
|
3
|
+
export * from "./sessions/upstash.server.js";
|
|
4
|
+
export * from "./zauru/httpGraphQL.server.js";
|
|
5
|
+
export * from "./zauru/httpOauth.server.js";
|
|
6
|
+
export * from "./zauru/httpZauru.server.js";
|
|
7
|
+
export * from "./zauru/zauru-agencies.server.js";
|
|
8
|
+
export * from "./zauru/zauru-profiles.server.js";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
declare const getSession: (cookieHeader?: string | null | undefined, options?: import("cookie").CookieParseOptions | undefined) => Promise<import("@remix-run/node").Session<import("@remix-run/node").SessionData, import("@remix-run/node").SessionData>>, commitSession: (session: import("@remix-run/node").Session<import("@remix-run/node").SessionData, import("@remix-run/node").SessionData>, options?: import("cookie").CookieSerializeOptions | undefined) => Promise<string>, destroySession: (session: import("@remix-run/node").Session<import("@remix-run/node").SessionData, import("@remix-run/node").SessionData>, options?: import("cookie").CookieSerializeOptions | undefined) => Promise<string>;
|
|
2
|
+
export { getSession, commitSession, destroySession };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createCookie } from "@remix-run/node";
|
|
2
|
+
import { createUpstashSessionStorage } from "./upstash.server.js";
|
|
3
|
+
const sessionCookie = createCookie("_rj_session", {
|
|
4
|
+
secrets: ["r3m1xr0ck1"],
|
|
5
|
+
path: "/",
|
|
6
|
+
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
|
7
|
+
httpOnly: true,
|
|
8
|
+
maxAge: 60 * 60 * 24,
|
|
9
|
+
//expires,
|
|
10
|
+
secure: process.env.NODE_ENV === "production",
|
|
11
|
+
});
|
|
12
|
+
const { getSession, commitSession, destroySession } = createUpstashSessionStorage({ cookie: sessionCookie });
|
|
13
|
+
export { getSession, commitSession, destroySession };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function createUpstashSessionStorage({ cookie }: any): import("@remix-run/node").SessionStorage<import("@remix-run/node").SessionData, import("@remix-run/node").SessionData>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createSessionStorage } from "@remix-run/node";
|
|
2
|
+
import crypto from "crypto";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
const redisBaseURL = config.redisBaseURL;
|
|
5
|
+
const headers = {
|
|
6
|
+
Authorization: `Bearer ${config.redisToken}`,
|
|
7
|
+
Accept: "application/json",
|
|
8
|
+
"Content-Type": "application/json",
|
|
9
|
+
};
|
|
10
|
+
const expiresToSeconds = (expires) => {
|
|
11
|
+
return 3600 * 8;
|
|
12
|
+
};
|
|
13
|
+
// For more info check https://remix.run/docs/en/v1/api/remix#createsessionstorage
|
|
14
|
+
export function createUpstashSessionStorage({ cookie }) {
|
|
15
|
+
return createSessionStorage({
|
|
16
|
+
cookie,
|
|
17
|
+
async createData(data, expires) {
|
|
18
|
+
const id = crypto.randomUUID();
|
|
19
|
+
await fetch(`${redisBaseURL}/set/${id}?EX=${expiresToSeconds(expires)}`, {
|
|
20
|
+
method: "post",
|
|
21
|
+
body: JSON.stringify({ data }),
|
|
22
|
+
headers,
|
|
23
|
+
});
|
|
24
|
+
return id;
|
|
25
|
+
},
|
|
26
|
+
async readData(id) {
|
|
27
|
+
const response = await fetch(`${redisBaseURL}/get/${id}`, {
|
|
28
|
+
headers,
|
|
29
|
+
});
|
|
30
|
+
try {
|
|
31
|
+
const { result } = (await response.json());
|
|
32
|
+
return JSON.parse(result).data;
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
async updateData(id, data, expires) {
|
|
39
|
+
await fetch(`${redisBaseURL}/set/${id}?EX=${expiresToSeconds(expires)}`, {
|
|
40
|
+
method: "post",
|
|
41
|
+
body: JSON.stringify({ data }),
|
|
42
|
+
headers,
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
async deleteData(id) {
|
|
46
|
+
await fetch(`${redisBaseURL}/del/${id}`, {
|
|
47
|
+
method: "post",
|
|
48
|
+
headers,
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
const axiosInstance = axios.create({
|
|
5
|
+
baseURL: `${config.graphqlAPIBaseURL}`,
|
|
6
|
+
});
|
|
7
|
+
axiosInstance.interceptors.request.use(function (request) {
|
|
8
|
+
// Do something before request is sent
|
|
9
|
+
console.log("---------------- EJECUTANDO REQUEST GRAPHQL ----------------");
|
|
10
|
+
//console.time(`${request.baseURL}${request.url}`);
|
|
11
|
+
console.log(chalk.green(`${request.baseURL}${request.url}`));
|
|
12
|
+
request.timeout = 120000;
|
|
13
|
+
return request;
|
|
14
|
+
}, function (error) {
|
|
15
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST GRAPHQL ----------------"));
|
|
16
|
+
console.log(`${error}`);
|
|
17
|
+
// Do something with request error
|
|
18
|
+
return Promise.reject(error);
|
|
19
|
+
});
|
|
20
|
+
// Add a response interceptor
|
|
21
|
+
axiosInstance.interceptors.response.use(function (response) {
|
|
22
|
+
// Do something with response data
|
|
23
|
+
//console.timeEnd(`${response.config.baseURL}${response.config.url}`);
|
|
24
|
+
return response;
|
|
25
|
+
}, function (error) {
|
|
26
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST GRAPHQL ----------------"));
|
|
27
|
+
console.log(`${error}`);
|
|
28
|
+
// Do something with response error
|
|
29
|
+
const { response } = error;
|
|
30
|
+
const msgError = response
|
|
31
|
+
? `HTTP ${response.status} ${response.statusText} - URL: ${response?.config?.baseURL}${response?.config?.url} - ${JSON.stringify(response?.data)}`
|
|
32
|
+
: error;
|
|
33
|
+
console.log(chalk.red(`${msgError}`));
|
|
34
|
+
throw new Error(msgError);
|
|
35
|
+
});
|
|
36
|
+
const httpGraphQLAPI = axiosInstance;
|
|
37
|
+
export default httpGraphQLAPI;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
const axiosInstance = axios.create({
|
|
5
|
+
baseURL: `${config.oauthBaseURL}`,
|
|
6
|
+
});
|
|
7
|
+
axiosInstance.interceptors.request.use(function (request) {
|
|
8
|
+
// Do something before request is sent
|
|
9
|
+
console.log("---------------- EJECUTANDO REQUEST ----------------");
|
|
10
|
+
//console.time(`${request.baseURL}${request.url}`);
|
|
11
|
+
console.log(chalk.green(`${request.baseURL}${request.url}`));
|
|
12
|
+
request.timeout = 120000;
|
|
13
|
+
return request;
|
|
14
|
+
}, function (error) {
|
|
15
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST ----------------"));
|
|
16
|
+
console.log(`${error}`);
|
|
17
|
+
// Do something with request error
|
|
18
|
+
return Promise.reject(error);
|
|
19
|
+
});
|
|
20
|
+
// Add a response interceptor
|
|
21
|
+
axiosInstance.interceptors.response.use(function (response) {
|
|
22
|
+
// Do something with response data
|
|
23
|
+
//console.timeEnd(`${response.config.baseURL}${response.config.url}`);
|
|
24
|
+
return response;
|
|
25
|
+
}, function (error) {
|
|
26
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST ----------------"));
|
|
27
|
+
console.log(`${error}`);
|
|
28
|
+
// Do something with response error
|
|
29
|
+
const { response } = error;
|
|
30
|
+
const msgError = response
|
|
31
|
+
? `HTTP ${response.status} ${response.statusText} - URL: ${response?.config?.baseURL}${response?.config?.url} - ${JSON.stringify(response?.data)}`
|
|
32
|
+
: error;
|
|
33
|
+
console.log(chalk.red(`${msgError}`));
|
|
34
|
+
throw new Error(msgError);
|
|
35
|
+
});
|
|
36
|
+
const httpOauth = axiosInstance;
|
|
37
|
+
export default httpOauth;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type AxiosUtilsResponse<T> = {
|
|
2
|
+
error?: boolean;
|
|
3
|
+
msg?: string;
|
|
4
|
+
userMsg?: string;
|
|
5
|
+
data?: T;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Handle web app table actions and return a response with a consistent format.
|
|
9
|
+
* @param action A function that returns a Promise of type T.
|
|
10
|
+
* @returns A Promise of AxiosUtilsResponse<T>.
|
|
11
|
+
*/
|
|
12
|
+
export declare function handlePossibleAxiosErrors<T>(action: () => Promise<T>): Promise<AxiosUtilsResponse<T>>;
|
|
13
|
+
declare const httpZauru: import("axios").AxiosInstance;
|
|
14
|
+
export default httpZauru;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
/**
|
|
5
|
+
* Handle web app table actions and return a response with a consistent format.
|
|
6
|
+
* @param action A function that returns a Promise of type T.
|
|
7
|
+
* @returns A Promise of AxiosUtilsResponse<T>.
|
|
8
|
+
*/
|
|
9
|
+
export async function handlePossibleAxiosErrors(action) {
|
|
10
|
+
try {
|
|
11
|
+
const result = await action();
|
|
12
|
+
return { error: false, data: result };
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return { error: true, userMsg: error?.toString() };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const axiosInstance = axios.create({
|
|
19
|
+
baseURL: `${config.zauruBaseURL}`,
|
|
20
|
+
});
|
|
21
|
+
axiosInstance.interceptors.request.use(function (request) {
|
|
22
|
+
// Do something before request is sent
|
|
23
|
+
console.log(`---------------- EJECUTANDO REQUEST ----------------`);
|
|
24
|
+
//console.time(`${request.baseURL}${request.url}`);
|
|
25
|
+
console.log(chalk.green(`${request.baseURL}${request.url}`));
|
|
26
|
+
request.timeout = 120000;
|
|
27
|
+
return request;
|
|
28
|
+
}, function (error) {
|
|
29
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST ----------------"));
|
|
30
|
+
console.log(`${error}`);
|
|
31
|
+
// Do something with request error
|
|
32
|
+
return Promise.reject(error);
|
|
33
|
+
});
|
|
34
|
+
// Add a response interceptor
|
|
35
|
+
axiosInstance.interceptors.response.use(function (response) {
|
|
36
|
+
// Do something with response data
|
|
37
|
+
//console.timeEnd(`${response.config.baseURL}${response.config.url}`);
|
|
38
|
+
return response;
|
|
39
|
+
}, function (error) {
|
|
40
|
+
console.log(chalk.red("---------------- ERROR CON REQUEST ----------------"));
|
|
41
|
+
console.log(`${error}`);
|
|
42
|
+
// Do something with response error
|
|
43
|
+
const { response } = error;
|
|
44
|
+
const msgError = response
|
|
45
|
+
? `HTTP ${response.status} ${response.statusText} - URL: ${response?.config?.baseURL}${response?.config?.url} - ${JSON.stringify(response?.data)}`
|
|
46
|
+
: error;
|
|
47
|
+
console.log(chalk.red(`${msgError}`));
|
|
48
|
+
throw new Error(msgError);
|
|
49
|
+
});
|
|
50
|
+
const httpZauru = axiosInstance;
|
|
51
|
+
export default httpZauru;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Session } from "@remix-run/node";
|
|
2
|
+
import type { AgencyGraphQL } from "@zauru-sdk/graphql";
|
|
3
|
+
import type { AxiosUtilsResponse } from "./httpZauru.server.js";
|
|
4
|
+
/**
|
|
5
|
+
* getAgencies
|
|
6
|
+
* @param headers
|
|
7
|
+
* @returns
|
|
8
|
+
*/
|
|
9
|
+
export declare function getAgencies(session: Session): Promise<AxiosUtilsResponse<AgencyGraphQL[]>>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { handlePossibleAxiosErrors } from "./httpZauru.server.js";
|
|
2
|
+
import httpGraphQLAPI from "./httpGraphQL.server.js";
|
|
3
|
+
import { getGraphQLAPIHeaders } from "~/common.server.js";
|
|
4
|
+
import graphql from "@zauru-sdk/graphql";
|
|
5
|
+
const { default: queries } = graphql;
|
|
6
|
+
/**
|
|
7
|
+
* getAgencies
|
|
8
|
+
* @param headers
|
|
9
|
+
* @returns
|
|
10
|
+
*/
|
|
11
|
+
export async function getAgencies(session) {
|
|
12
|
+
return handlePossibleAxiosErrors(async () => {
|
|
13
|
+
const headers = await getGraphQLAPIHeaders(session);
|
|
14
|
+
const response = await httpGraphQLAPI.post(``, {
|
|
15
|
+
query: queries.getAgencies,
|
|
16
|
+
}, {
|
|
17
|
+
headers,
|
|
18
|
+
});
|
|
19
|
+
return response.data?.data.agencies;
|
|
20
|
+
});
|
|
21
|
+
}
|