@runnerpro/backend 1.16.10 → 1.16.12

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.
@@ -54,8 +54,10 @@ const query = (queryText, values = []) => __awaiter(void 0, void 0, void 0, func
54
54
  });
55
55
  }
56
56
  catch (error) {
57
+ // Logging mejorado con información detallada del error
58
+ const enhancedError = enhancePostgreSQLError(error, queryText, values);
57
59
  // eslint-disable-next-line no-console
58
- console.error('PG query error', error);
60
+ console.error('PG query error', enhancedError);
59
61
  return [];
60
62
  }
61
63
  });
@@ -81,8 +83,10 @@ const queryWithClient = (queryText, values = [], _retry = false) => __awaiter(vo
81
83
  });
82
84
  }
83
85
  catch (error) {
86
+ // Logging mejorado con información detallada del error
87
+ const enhancedError = enhancePostgreSQLError(error, queryText, values);
84
88
  // eslint-disable-next-line no-console
85
- console.error('PG query error', error);
89
+ console.error('PG query error', enhancedError);
86
90
  // Liberar conexión como rota si es necesario
87
91
  if (['EPIPE', 'ECONNRESET', '57P01', 'ECONNREFUSED'].includes(error.code)) {
88
92
  if (client) {
@@ -197,6 +201,81 @@ function camelize(str) {
197
201
  function sleep(ms) {
198
202
  return new Promise((resolve) => setTimeout(resolve, ms));
199
203
  }
204
+ // ✅ Función para mejorar el logging de errores PostgreSQL
205
+ function enhancePostgreSQLError(error, queryText, values = []) {
206
+ const enhancedError = Object.assign(Object.assign({}, error), {
207
+ // Información básica del error
208
+ message: error.message, code: error.code, severity: error.severity, detail: error.detail, hint: error.hint, position: error.position,
209
+ // Información de la query que falló
210
+ query: {
211
+ original: queryText,
212
+ parsed: getParseQuery(queryText, values),
213
+ values: values,
214
+ length: queryText.length
215
+ },
216
+ // Información contextual del error
217
+ context: {
218
+ // Si hay posición del error, extraer el contexto
219
+ errorPosition: error.position ? parseInt(error.position) : null,
220
+ errorContext: error.position ? getErrorContext(queryText, parseInt(error.position)) : null,
221
+ // Información de tabla y columna si está disponible
222
+ table: error.table || extractTableFromQuery(queryText),
223
+ column: error.column || extractColumnFromQuery(queryText, error.position),
224
+ schema: error.schema,
225
+ // Información adicional
226
+ constraint: error.constraint,
227
+ dataType: error.dataType,
228
+ file: error.file,
229
+ line: error.line,
230
+ routine: error.routine
231
+ },
232
+ // Timestamp del error
233
+ timestamp: new Date().toISOString(),
234
+ // Stack trace completo
235
+ stack: error.stack });
236
+ return enhancedError;
237
+ }
238
+ // ✅ Función para extraer contexto del error en la query
239
+ function getErrorContext(queryText, position, contextLength = 50) {
240
+ if (!position || position < 0)
241
+ return null;
242
+ const start = Math.max(0, position - contextLength);
243
+ const end = Math.min(queryText.length, position + contextLength);
244
+ const before = queryText.substring(start, position);
245
+ const after = queryText.substring(position, end);
246
+ return {
247
+ before: before,
248
+ after: after,
249
+ position: position - start, // Posición relativa en el contexto
250
+ fullContext: queryText.substring(start, end)
251
+ };
252
+ }
253
+ // ✅ Función para extraer nombre de tabla de la query
254
+ function extractTableFromQuery(queryText) {
255
+ const tableRegex = /(?:FROM|UPDATE|INSERT\s+INTO|DELETE\s+FROM)\s+([a-zA-Z_][a-zA-Z0-9_]*)/i;
256
+ const match = queryText.match(tableRegex);
257
+ return match ? match[1] : null;
258
+ }
259
+ // ✅ Función para extraer nombre de columna de la query
260
+ function extractColumnFromQuery(queryText, position) {
261
+ if (!position)
262
+ return null;
263
+ // Buscar la palabra más cercana a la posición del error
264
+ const words = queryText.split(/\s+/);
265
+ let currentPos = 0;
266
+ for (const word of words) {
267
+ const wordStart = queryText.indexOf(word, currentPos);
268
+ const wordEnd = wordStart + word.length;
269
+ if (position >= wordStart && position <= wordEnd) {
270
+ // Verificar si parece un nombre de columna
271
+ if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(word)) {
272
+ return word;
273
+ }
274
+ }
275
+ currentPos = wordEnd;
276
+ }
277
+ return null;
278
+ }
200
279
  // ✅ Manejo de cierre mejorado
201
280
  const gracefulShutdown = () => __awaiter(void 0, void 0, void 0, function* () {
202
281
  try {
package/lib/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.updateSenderView = exports.sendPrompt = exports.saveResponseTime = exports.saveWorkoutAplication = exports.getPlanificacionPrueba7dias = exports.sendWorkoutToWatch = exports.getDefaultWorkoutImage = exports.generateShareMap = exports.reduceSizeImage = exports.getLetter = exports.getNumberByLetter = exports.appendSheet = exports.writeSheet = exports.findCellByValue = exports.readSheet = exports.NOTION_DATABASES_ID = exports.notionEditPage = exports.notionAddPage = exports.notionGetDatabase = exports.notionGetUsers = exports.getCountNotificaciones = exports.chatExposed = exports.chatApi = exports.chat = exports.getExerciseTranslatedDescription = exports.useTranslation = exports.LANGUAGES = exports.translate = exports.CHANNEL_SLACK = exports.notifySlack = exports.fetchIA = exports.err = exports.sendMail = exports.pool = exports.toPgArray = exports.batchQuery = exports.longRunningQuery = exports.queryWithClient = exports.query = exports.sleep = exports.sendNotification = void 0;
3
+ exports.updateSenderView = exports.sendPrompt = exports.saveResponseTime = exports.getPlanificacionPrueba7dias = exports.sendWorkoutToWatch = exports.getDefaultWorkoutImage = exports.generateShareMap = exports.reduceSizeImage = exports.getLetter = exports.getNumberByLetter = exports.appendSheet = exports.writeSheet = exports.findCellByValue = exports.readSheet = exports.NOTION_DATABASES_ID = exports.notionEditPage = exports.notionAddPage = exports.notionGetDatabase = exports.notionGetUsers = exports.getCountNotificaciones = exports.chatExposed = exports.chatApi = exports.chat = exports.getExerciseTranslatedDescription = exports.useTranslation = exports.LANGUAGES = exports.translate = exports.CHANNEL_SLACK = exports.notifySlack = exports.fetchIA = exports.err = exports.sendMail = exports.pool = exports.toPgArray = exports.batchQuery = exports.longRunningQuery = exports.queryWithClient = exports.query = exports.sleep = exports.sendNotification = void 0;
4
4
  const sendNotification_1 = require("./sendNotification");
5
5
  Object.defineProperty(exports, "sendNotification", { enumerable: true, get: function () { return sendNotification_1.sendNotification; } });
6
6
  const sleep_1 = require("./sleep");
@@ -54,8 +54,6 @@ const sendToWatch_1 = require("./workout/sendToWatch");
54
54
  Object.defineProperty(exports, "sendWorkoutToWatch", { enumerable: true, get: function () { return sendToWatch_1.sendWorkoutToWatch; } });
55
55
  const planificacionPrueba7dias_1 = require("./workout/planificacionPrueba7dias");
56
56
  Object.defineProperty(exports, "getPlanificacionPrueba7dias", { enumerable: true, get: function () { return planificacionPrueba7dias_1.getPlanificacionPrueba7dias; } });
57
- const saveWorkoutAplication_1 = require("./workout/saveWorkoutAplication");
58
- Object.defineProperty(exports, "saveWorkoutAplication", { enumerable: true, get: function () { return saveWorkoutAplication_1.saveWorkoutAplication; } });
59
57
  const saveResponseTime_1 = require("./chat/saveResponseTime");
60
58
  Object.defineProperty(exports, "saveResponseTime", { enumerable: true, get: function () { return saveResponseTime_1.saveResponseTime; } });
61
59
  const prompt_1 = require("./prompt");
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db/index.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,IAAI,CAAC;AAI5B,QAAA,MAAM,IAAI,iBAaR,CAAC;AASH,QAAA,MAAM,KAAK,cAAqB,MAAM,WAAU,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,iBAuB5E,CAAC;AAGF,QAAA,MAAM,eAAe,cAAqB,MAAM,WAAU,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,0BAiDtF,CAAC;AAGF,QAAA,MAAM,UAAU,YAAmB,GAAG,EAAE,uCAmBvC,CAAC;AAGF,QAAA,MAAM,gBAAgB,cACT,MAAM,WACT,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,qCAyBtC,CAAC;AAGF,QAAA,MAAM,SAAS,QAAS,MAAM,EAAE,WAM/B,CAAC;AAkDF,OAAO,EACL,KAAK,EAAE,oCAAoC;AAC3C,eAAe,EAAE,wBAAwB;AACzC,gBAAgB,EAAE,uBAAuB;AACzC,UAAU,EAAE,aAAa;AACzB,SAAS,EAAE,WAAW;AACtB,IAAI,GACL,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/db/index.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,IAAI,CAAC;AAI5B,QAAA,MAAM,IAAI,iBAaR,CAAC;AASH,QAAA,MAAM,KAAK,cAAqB,MAAM,WAAU,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,iBAyB5E,CAAC;AAGF,QAAA,MAAM,eAAe,cAAqB,MAAM,WAAU,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,0BAmDtF,CAAC;AAGF,QAAA,MAAM,UAAU,YAAmB,GAAG,EAAE,uCAmBvC,CAAC;AAGF,QAAA,MAAM,gBAAgB,cACT,MAAM,WACT,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EAAE,qCAyBtC,CAAC;AAGF,QAAA,MAAM,SAAS,QAAS,MAAM,EAAE,WAM/B,CAAC;AAoJF,OAAO,EACL,KAAK,EAAE,oCAAoC;AAC3C,eAAe,EAAE,wBAAwB;AACzC,gBAAgB,EAAE,uBAAuB;AACzC,UAAU,EAAE,aAAa;AACzB,SAAS,EAAE,WAAW;AACtB,IAAI,GACL,CAAC"}
@@ -14,9 +14,8 @@ import { generateShareMap } from './image/generateShareMap';
14
14
  import { getDefaultWorkoutImage } from './image/getDefaultWorkoutImage';
15
15
  import { sendWorkoutToWatch } from './workout/sendToWatch';
16
16
  import { getPlanificacionPrueba7dias } from './workout/planificacionPrueba7dias';
17
- import { saveWorkoutAplication } from './workout/saveWorkoutAplication';
18
17
  import { saveResponseTime } from './chat/saveResponseTime';
19
18
  import { sendPrompt } from './prompt';
20
19
  import { updateSenderView } from './chat/api/conversation';
21
- export { sendNotification, sleep, query, queryWithClient, longRunningQuery, batchQuery, toPgArray, pool, sendMail, err, fetchIA, notifySlack, CHANNEL_SLACK, translate, LANGUAGES, useTranslation, getExerciseTranslatedDescription, chat, chatApi, chatExposed, getCountNotificaciones, notionGetUsers, notionGetDatabase, notionAddPage, notionEditPage, NOTION_DATABASES_ID, readSheet, findCellByValue, writeSheet, appendSheet, getNumberByLetter, getLetter, reduceSizeImage, generateShareMap, getDefaultWorkoutImage, sendWorkoutToWatch, getPlanificacionPrueba7dias, saveWorkoutAplication, saveResponseTime, sendPrompt, updateSenderView, };
20
+ export { sendNotification, sleep, query, queryWithClient, longRunningQuery, batchQuery, toPgArray, pool, sendMail, err, fetchIA, notifySlack, CHANNEL_SLACK, translate, LANGUAGES, useTranslation, getExerciseTranslatedDescription, chat, chatApi, chatExposed, getCountNotificaciones, notionGetUsers, notionGetDatabase, notionAddPage, notionEditPage, NOTION_DATABASES_ID, readSheet, findCellByValue, writeSheet, appendSheet, getNumberByLetter, getLetter, reduceSizeImage, generateShareMap, getDefaultWorkoutImage, sendWorkoutToWatch, getPlanificacionPrueba7dias, saveResponseTime, sendPrompt, updateSenderView, };
22
21
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC7F,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,cAAc,EAAE,gCAAgC,EAAE,MAAM,eAAe,CAAC;AACvG,OAAO,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,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,OAAO,EACL,gBAAgB,EAChB,KAAK,EACL,KAAK,EACL,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,SAAS,EACT,IAAI,EACJ,QAAQ,EACR,GAAG,EACH,OAAO,EACP,WAAW,EACX,aAAa,EACb,SAAS,EACT,SAAS,EACT,cAAc,EACd,gCAAgC,EAChC,IAAI,EACJ,OAAO,EACP,WAAW,EACX,sBAAsB,EACtB,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,mBAAmB,EACnB,SAAS,EACT,eAAe,EACf,UAAU,EACV,WAAW,EACX,iBAAiB,EACjB,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,sBAAsB,EACtB,kBAAkB,EAClB,2BAA2B,EAC3B,gBAAgB,EAChB,UAAU,EACV,gBAAgB,GACjB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runnerpro/backend",
3
- "version": "1.16.10",
3
+ "version": "1.16.12",
4
4
  "description": "A collection of common backend functions",
5
5
  "exports": {
6
6
  ".": "./lib/cjs/index.js"
@@ -1,38 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.getTitleDescriptionTranslated = void 0;
13
- const db_1 = require("../db");
14
- const index_1 = require("./index");
15
- const common_1 = require("@runnerpro/common");
16
- const getTitleDescriptionTranslated = (idCliente, titleOriginal, descriptionOriginal) => __awaiter(void 0, void 0, void 0, function* () {
17
- let title;
18
- let description;
19
- let titlePreferredLanguage;
20
- let descriptionPreferredLanguage;
21
- const [cliente] = yield (0, db_1.query)('SELECT [PREFERRED LANGUAGE] FROM [CLIENTE] WHERE [ID] = ?', [idCliente]);
22
- if ((cliente === null || cliente === void 0 ? void 0 : cliente.preferredLanguage) && cliente.preferredLanguage !== common_1.LANGUAGES.ES) {
23
- // @ts-ignore
24
- title = titleOriginal ? yield (0, index_1.translate)(titleOriginal, { fromLanguage: cliente.preferredLanguage, toLanguage: common_1.LANGUAGES.ES }) : null;
25
- description = descriptionOriginal
26
- ? // @ts-ignore
27
- yield (0, index_1.translate)(descriptionOriginal, { fromLanguage: cliente.preferredLanguage, toLanguage: common_1.LANGUAGES.ES })
28
- : null;
29
- titlePreferredLanguage = titleOriginal;
30
- descriptionPreferredLanguage = descriptionOriginal;
31
- }
32
- else {
33
- title = titleOriginal;
34
- description = descriptionOriginal;
35
- }
36
- return { title, description, titlePreferredLanguage, descriptionPreferredLanguage };
37
- });
38
- exports.getTitleDescriptionTranslated = getTitleDescriptionTranslated;
@@ -1,8 +0,0 @@
1
- declare const getTitleDescriptionTranslated: (idCliente: any, titleOriginal: any, descriptionOriginal: any) => Promise<{
2
- title: any;
3
- description: any;
4
- titlePreferredLanguage: any;
5
- descriptionPreferredLanguage: any;
6
- }>;
7
- export { getTitleDescriptionTranslated };
8
- //# sourceMappingURL=titleDescriptionTranslated.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"titleDescriptionTranslated.d.ts","sourceRoot":"","sources":["../../../../src/translation/titleDescriptionTranslated.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,6BAA6B;;;;;EAsBlC,CAAC;AAEF,OAAO,EAAE,6BAA6B,EAAE,CAAC"}
@@ -1,17 +0,0 @@
1
- declare const saveWorkoutAplication: ({ date, type, title, description, distance, duration, power, desnivel, polyline, idCliente, aplicationType, aplicationId, queryConditionExist }: {
2
- date: any;
3
- type: any;
4
- title: any;
5
- description: any;
6
- distance: any;
7
- duration: any;
8
- power: any;
9
- desnivel: any;
10
- polyline: any;
11
- idCliente: any;
12
- aplicationType: any;
13
- aplicationId: any;
14
- queryConditionExist: any;
15
- }, data: any) => Promise<any>;
16
- export { saveWorkoutAplication };
17
- //# sourceMappingURL=saveWorkoutAplication.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"saveWorkoutAplication.d.ts","sourceRoot":"","sources":["../../../../src/workout/saveWorkoutAplication.ts"],"names":[],"mappings":"AAUA,QAAA,MAAM,qBAAqB;;;;;;;;;;;;;;6BAwD1B,CAAC;AA8CF,OAAO,EAAE,qBAAqB,EAAE,CAAC"}
@@ -1,101 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.saveWorkoutAplication = void 0;
16
- const db_1 = require("../db");
17
- const titleDescriptionTranslated_1 = require("../translation/titleDescriptionTranslated");
18
- const storage_1 = require("@google-cloud/storage");
19
- const path_1 = __importDefault(require("path"));
20
- const axios_1 = __importDefault(require("axios"));
21
- const generateShareMap_1 = require("../image/generateShareMap");
22
- const getDefaultWorkoutImage_1 = require("../image/getDefaultWorkoutImage");
23
- const moment_1 = __importDefault(require("moment"));
24
- const estructuraWorkout_1 = require("./estructuraWorkout");
25
- const saveWorkoutAplication = ({ date, type, title, description, distance, duration, power, desnivel, polyline, idCliente, aplicationType, aplicationId, queryConditionExist }, data) => __awaiter(void 0, void 0, void 0, function* () {
26
- const [exist] = yield (0, db_1.query)(`
27
- SELECT [ID], [TYPE]
28
- FROM [WORKOUT]
29
- WHERE
30
- ([ID CLIENTE] = ? AND [DATE] = ? AND ${queryConditionExist} AND [DONE] = FALSE AND [SHOW CLIENT] = TRUE)
31
- OR
32
- ([ID APLICATION] = ? AND [TIPO APLICATION] = ?)
33
- `, [idCliente, (0, moment_1.default)(date).format('YYYY-MM-DD'), aplicationId, aplicationType]);
34
- let idWorkout;
35
- if (!exist) {
36
- const { title: titleNoTranslate, description: descriptionNoTranslate, titlePreferredLanguage, descriptionPreferredLanguage, } = yield (0, titleDescriptionTranslated_1.getTitleDescriptionTranslated)(idCliente, title, description);
37
- [{ id: idWorkout }] = yield (0, db_1.query)(`
38
- INSERT INTO [WORKOUT] ([ID CLIENTE], [DATE], [TITLE], [DESCRIPTION], [TITLE PREFERRED LANGUAGE], [DESCRIPTION PREFERRED LANGUAGE], [TYPE], [DONE], [SHOW CLIENT])
39
- VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE) RETURNING [ID]
40
- `, [
41
- idCliente,
42
- (0, moment_1.default)(date).format('YYYY-MM-DD'),
43
- titleNoTranslate,
44
- descriptionNoTranslate,
45
- titlePreferredLanguage,
46
- descriptionPreferredLanguage,
47
- type,
48
- ]);
49
- }
50
- else {
51
- idWorkout = exist.id;
52
- yield (0, estructuraWorkout_1.saveDoneStructuraWorkout)(exist.id, null, exist.type);
53
- }
54
- yield (0, db_1.query)(`
55
- UPDATE [WORKOUT] SET [DISTANCE] = ?, [DURATION] = ?, [POTENCIA] = ?, [DESNIVEL] = ?, [POLYLINE] = ?, [TIPO APLICATION] = ?, [ID APLICATION] = ?, [DONE] = TRUE, [RAW] = ?
56
- WHERE [ID] = ?
57
- `, [distance, duration, power, desnivel, getPolyline(polyline), aplicationType, aplicationId, JSON.stringify(data), idWorkout]);
58
- yield saveMap(idWorkout, polyline);
59
- saveShareWorkoutImage(idWorkout, type);
60
- return idWorkout;
61
- });
62
- exports.saveWorkoutAplication = saveWorkoutAplication;
63
- const getPolyline = (activity) => {
64
- var _a, _b;
65
- if (!((_a = activity === null || activity === void 0 ? void 0 : activity.map) === null || _a === void 0 ? void 0 : _a.polyline))
66
- return null;
67
- const polyline = ((_b = activity.map) === null || _b === void 0 ? void 0 : _b.polyline.length) > 5000 ? activity.map.summary_polyline : activity.map.polyline;
68
- return encodeURIComponent(polyline);
69
- };
70
- const saveMap = (idWorkout, polyline) => __awaiter(void 0, void 0, void 0, function* () {
71
- if (!polyline)
72
- return;
73
- // @ts-ignore
74
- const serviceKey = path_1.default.join(process.cwd(), process.env.FIREBASE_STORAGE_CREDENTIALS);
75
- const storage = new storage_1.Storage({ keyFilename: serviceKey });
76
- const encodedPolyline = encodeURIComponent(polyline);
77
- const result = yield axios_1.default.get(`https://api.mapbox.com/styles/v1/david-runnerpro/clqwrghcj013401qr5cch6z45/static/path-3+ea5b1b-100(${encodedPolyline})/auto/1080x1080?access_token=pk.eyJ1IjoiZGF2aWQtcnVubmVycHJvIiwiYSI6ImNscXdrZW56YTA0MTQybWxmNWx2b3Z6NjYifQ.g3vCR3HDRobLyr_4WFAeJA&logo=false`, { responseType: 'arraybuffer' });
78
- const imageBuffer = Buffer.from(result.data, 'binary');
79
- // @ts-ignore
80
- yield storage.bucket(process.env.CLOUD_STORAGE_BUCKET_PUBLIC).file(`Workout/${idWorkout}`).save(imageBuffer);
81
- const urlMap = `https://storage.googleapis.com/${process.env.CLOUD_STORAGE_BUCKET_PUBLIC}/Workout/${idWorkout}`;
82
- yield (0, db_1.query)('UPDATE [WORKOUT] SET [HAVE MAP IMAGE] = TRUE, [PHOTO URL] = ? WHERE [ID] = ?', [urlMap, idWorkout]);
83
- });
84
- const saveShareWorkoutImage = (id, type) => __awaiter(void 0, void 0, void 0, function* () {
85
- // @ts-ignore
86
- const serviceKey = path_1.default.join(process.cwd(), process.env.FIREBASE_STORAGE_CREDENTIALS);
87
- const storage = new storage_1.Storage({ keyFilename: serviceKey });
88
- // @ts-ignore
89
- const [exists] = yield storage.bucket(process.env.CLOUD_STORAGE_BUCKET_PUBLIC).file(`Workout/${id}`).exists();
90
- let image;
91
- if (!exists)
92
- image = (0, getDefaultWorkoutImage_1.getDefaultWorkoutImage)(type);
93
- // @ts-ignore
94
- else
95
- [image] = yield storage.bucket(process.env.CLOUD_STORAGE_BUCKET_PUBLIC).file(`Workout/${id}`).download();
96
- const shareMap = yield (0, generateShareMap_1.generateShareMap)(image, id);
97
- // @ts-ignore
98
- yield storage.bucket(process.env.CLOUD_STORAGE_BUCKET_PUBLIC).file(`Workout/${id}-share`).save(shareMap);
99
- const urlShare = `https://storage.googleapis.com/${process.env.CLOUD_STORAGE_BUCKET_PUBLIC}/Workout/${id}-share`;
100
- yield (0, db_1.query)('UPDATE [WORKOUT] SET [PHOTO URL SHARE] = ? WHERE [ID] = ?', [urlShare, id]);
101
- });