@levrbet/shared 0.2.82 → 0.3.1

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 (57) hide show
  1. package/dist/core/config/urls.js +4 -4
  2. package/dist/core/config/urls.js.map +1 -1
  3. package/dist/core/utils/game.utils.d.ts +2 -0
  4. package/dist/core/utils/game.utils.js +69 -1
  5. package/dist/core/utils/game.utils.js.map +1 -1
  6. package/dist/server/oracle/config/game-periods/providers/lsports.periods.js +3 -3
  7. package/dist/server/oracle/config/game-periods/providers/lsports.periods.js.map +1 -1
  8. package/dist/server/oracle/config/game-periods/providers/optic-odds.periods.d.ts +4 -27
  9. package/dist/server/oracle/config/game-periods/providers/optic-odds.periods.js +4 -27
  10. package/dist/server/oracle/config/game-periods/providers/optic-odds.periods.js.map +1 -1
  11. package/dist/server/oracle/config/game-periods/sports.config.js +8 -73
  12. package/dist/server/oracle/config/game-periods/sports.config.js.map +1 -1
  13. package/dist/server/oracle/config/game-periods/types.d.ts +2 -6
  14. package/dist/server/oracle/config/game-periods/types.js +0 -1
  15. package/dist/server/oracle/config/game-periods/types.js.map +1 -1
  16. package/dist/server/oracle/redis-cache-manager/cache.keys.utils.d.ts +45 -74
  17. package/dist/server/oracle/redis-cache-manager/cache.keys.utils.js +65 -120
  18. package/dist/server/oracle/redis-cache-manager/cache.keys.utils.js.map +1 -1
  19. package/dist/server/oracle/redis-cache-manager/game.query.engine.d.ts +90 -0
  20. package/dist/server/oracle/redis-cache-manager/game.query.engine.js +436 -0
  21. package/dist/server/oracle/redis-cache-manager/game.query.engine.js.map +1 -0
  22. package/dist/server/oracle/redis-cache-manager/index.d.ts +2 -3
  23. package/dist/server/oracle/redis-cache-manager/index.js +2 -3
  24. package/dist/server/oracle/redis-cache-manager/index.js.map +1 -1
  25. package/dist/server/oracle/redis-cache-manager/market.query.engine.d.ts +50 -97
  26. package/dist/server/oracle/redis-cache-manager/market.query.engine.js +310 -467
  27. package/dist/server/oracle/redis-cache-manager/market.query.engine.js.map +1 -1
  28. package/dist/server/oracle/types/providers/game-clock/index.d.ts +1 -1
  29. package/dist/server/oracle/types/providers/game-clock/index.js +1 -1
  30. package/dist/server/oracle/types/providers/game-clock/index.js.map +1 -1
  31. package/dist/server/{utils/game_progress → oracle/types/providers/game-clock}/parser.d.ts +7 -1
  32. package/dist/server/{utils/game_progress → oracle/types/providers/game-clock}/parser.js +13 -2
  33. package/dist/server/oracle/types/providers/game-clock/parser.js.map +1 -0
  34. package/dist/server/utils/index.d.ts +0 -1
  35. package/dist/server/utils/index.js +0 -1
  36. package/dist/server/utils/index.js.map +1 -1
  37. package/package.json +5 -4
  38. package/scripts/setup-prisma.js +0 -0
  39. package/dist/server/oracle/redis-cache-manager/game.cache.service.d.ts +0 -185
  40. package/dist/server/oracle/redis-cache-manager/game.cache.service.js +0 -712
  41. package/dist/server/oracle/redis-cache-manager/game.cache.service.js.map +0 -1
  42. package/dist/server/oracle/redis-cache-manager/game.progress.d.ts +0 -4
  43. package/dist/server/oracle/redis-cache-manager/game.progress.js +0 -27
  44. package/dist/server/oracle/redis-cache-manager/game.progress.js.map +0 -1
  45. package/dist/server/oracle/redis-cache-manager/market.cache.service.d.ts +0 -87
  46. package/dist/server/oracle/redis-cache-manager/market.cache.service.js +0 -139
  47. package/dist/server/oracle/redis-cache-manager/market.cache.service.js.map +0 -1
  48. package/dist/server/utils/game_progress/caclulate.game.progress.d.ts +0 -6
  49. package/dist/server/utils/game_progress/caclulate.game.progress.js +0 -96
  50. package/dist/server/utils/game_progress/caclulate.game.progress.js.map +0 -1
  51. package/dist/server/utils/game_progress/game.utils.d.ts +0 -2
  52. package/dist/server/utils/game_progress/game.utils.js +0 -64
  53. package/dist/server/utils/game_progress/game.utils.js.map +0 -1
  54. package/dist/server/utils/game_progress/index.d.ts +0 -3
  55. package/dist/server/utils/game_progress/index.js +0 -20
  56. package/dist/server/utils/game_progress/index.js.map +0 -1
  57. package/dist/server/utils/game_progress/parser.js.map +0 -1
@@ -1,712 +0,0 @@
1
- "use strict";
2
- /**
3
- * @fileoverview Game Cache Service - Manages Redis caching operations for game-related data
4
- * This module provides functionality for caching and retrieving game data, including:
5
- * - Game schedules
6
- * - Active and post-game data
7
- * - Game scores and period information
8
- * - Fixture ID mappings between different providers
9
- *
10
- * @module game.cache.service
11
- */
12
- var __importDefault = (this && this.__importDefault) || function (mod) {
13
- return (mod && mod.__esModule) ? mod : { "default": mod };
14
- };
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.getAllFixtureIdsForGameIds = exports.getAllProvidersIdsForLevrFixtureIds = exports.invalidateScoreCache = exports.deleteAllSubKeys = exports.updateGameStatusInCache = exports.getGameScoreCache = exports.setGamesScoreCache = exports.updateGamesClockInCache = exports.getLevrFixtureIdUsingGameId = exports.mapProviderFixtureIdToLevrFixtureIdMany = exports.mapProviderFixtureIdToLevrFixtureId = exports.mapGameIdToLevrFixtureId = exports.removePostGamesCache = exports.removeActiveGamesCache = exports.getGameCacheByFixtureIdWithProviderFixtureId = exports.getGameCacheByFixtureId = exports.getPostGamesCache = exports.getActiveGamesCacheWithRelations = exports.getActiveGamesCache = exports.getSpecificGamesCacheByFixtureIds = exports.getSpecificGamesCacheByGameIds = exports.getPostGamesByFixtureId = exports.getActiveGamesByFixtureId = exports.getGamesByFixtureId = exports.getPostGameCacheByGameId = exports.getActiveGameCacheByGameId = exports.setPostGamesCache = exports.setActiveGamesCache = void 0;
17
- const client_1 = require("@prisma/client");
18
- const config_1 = require("../../config");
19
- const winston_1 = __importDefault(require("../../config/winston"));
20
- const cache_keys_utils_1 = require("./cache.keys.utils");
21
- const market_cache_service_1 = require("./market.cache.service");
22
- // *************************************Game setters*********************************************************
23
- /**
24
- * Caches an array of LevrGame objects in Redis using a pipeline.
25
- *
26
- * For each game, stores a mapping from the game ID to the fixture ID,
27
- * and serializes the game object under a fixture-specific key within a hash.
28
- * Executes all Redis commands in a single pipeline for efficiency.
29
- *
30
- * @param pipeline - The Redis pipeline (ChainableCommander) used to batch commands.
31
- * @param levrFixtureId - The unique identifier for the fixture to associate with the games.
32
- * @param games - An array of LevrGame objects to cache.
33
- * @param gameCollectionKey - The Redis hash key under which the games are stored.
34
- * @returns A Promise that resolves when the cache operation is complete.
35
- * @throws Will throw an error if the Redis operation fails.
36
- */
37
- const setGamesCache = async (pipeline, games, gameCollectionKey) => {
38
- games.forEach((game) => {
39
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, game.chainId);
40
- const fixtureKey = (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(game.levrFixtureId, game.chainId);
41
- // Store games array under fixture key
42
- pipeline.hset(hash, fixtureKey, JSON.stringify(game));
43
- // map provider fixture ids to levr fixture ids
44
- if (game.lsportsFixtureId && game.levrFixtureId)
45
- pipeline.hset(cache_keys_utils_1.providerFixtureIdToLevrId, game.lsportsFixtureId, game.levrFixtureId);
46
- if (game.opticOddsFixtureId && game.levrFixtureId)
47
- pipeline.hset(cache_keys_utils_1.providerFixtureIdToLevrId, game.opticOddsFixtureId, game.levrFixtureId);
48
- pipeline.hset(cache_keys_utils_1.gameIdsToLevrFixtureIdsMap, game.gameId, game.levrFixtureId);
49
- });
50
- const results = await pipeline.exec();
51
- if (!results) {
52
- throw new Error(`Pipeline execution failed while caching games for ${gameCollectionKey}`);
53
- }
54
- for (const [err] of results) {
55
- if (err) {
56
- throw new Error(`Error caching games for ${gameCollectionKey}: ${err.message}`);
57
- }
58
- }
59
- winston_1.default.info(`Cached ${games.length.toString()} games for ${gameCollectionKey}`);
60
- };
61
- /**
62
- * Caches active games in Redis.
63
- * @param {ChainableCommander} pipeline - Redis pipeline
64
- * @param {string} levrFixtureId - Fixture identifier
65
- * @param {LevrGame[]} games - Games to cache
66
- * @returns {Promise<void>}
67
- */
68
- const setActiveGamesCache = async (pipeline, games) => {
69
- await setGamesCache(pipeline, games, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
70
- };
71
- exports.setActiveGamesCache = setActiveGamesCache;
72
- /**
73
- * Caches post-game data in Redis.
74
- * @param {ChainableCommander} pipeline - Redis pipeline
75
- * @param {string} levrFixtureId - Fixture identifier
76
- * @param {LevrGame[]} games - Games to cache
77
- * @returns {Promise<void>}
78
- */
79
- const setPostGamesCache = async (pipeline, games) => {
80
- await setGamesCache(pipeline, games, cache_keys_utils_1.GameCollectionKeys.postGamesHash);
81
- };
82
- exports.setPostGamesCache = setPostGamesCache;
83
- //*******************************************Game fetchers*********************************************************
84
- const getAGameByGameId = async (redis, gameId, chainId, gameCollectionKey) => {
85
- // Get the fixtureId for this game
86
- const fixtureId = await redis.hget(cache_keys_utils_1.gameIdsToLevrFixtureIdsMap, gameId.toString());
87
- if (!fixtureId)
88
- return null;
89
- // Get all games for this fixture
90
- const fixtureKey = (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(fixtureId, chainId);
91
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, chainId);
92
- const gamesString = await redis.hget(hash, fixtureKey);
93
- if (!gamesString)
94
- return null;
95
- // Find the specific game
96
- const game = JSON.parse(gamesString);
97
- return game;
98
- };
99
- /**
100
- * Retrieves a game from the Redis cache using its game ID.
101
- * @param gameId - The ID of the game.
102
- * @returns {Promise<LevrGame | null>} - A promise that resolves with a LevrGame object or null if not found.
103
- */
104
- const getActiveGameCacheByGameId = async (redis, gameId, chainId) => {
105
- return await getAGameByGameId(redis, gameId, chainId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
106
- };
107
- exports.getActiveGameCacheByGameId = getActiveGameCacheByGameId;
108
- /**
109
- * Retrieves a game from the Redis cache using its game ID.
110
- * @param gameId - The ID of the game.
111
- * @returns {Promise<LevrGame | null>} - A promise that resolves with a LevrGame object or null if not found.
112
- */
113
- const getPostGameCacheByGameId = async (redis, gameId, chainId) => {
114
- return await getAGameByGameId(redis, gameId, chainId, cache_keys_utils_1.GameCollectionKeys.postGamesHash);
115
- };
116
- exports.getPostGameCacheByGameId = getPostGameCacheByGameId;
117
- /**
118
- * Retrieves all games for a given fixture ID from the Redis cache.
119
- * @param redis
120
- * @param levrFixtureId
121
- * @param gameCollectionKey
122
- * @returns {Promise<LevrGame[]>} - A promise that resolves with an array of LevrGame objects.
123
- * @notice all games are related to the fixtureId across all chains.
124
- */
125
- const getGamesByFixtureId = async (redis, levrFixtureId, gameCollectionKey) => {
126
- const pipeline = redis.pipeline();
127
- const levrGames = [];
128
- for (const chainId of config_1.supportedChainIds) {
129
- const fixtureKey = (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(levrFixtureId, chainId);
130
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, chainId);
131
- pipeline.hget(hash, fixtureKey);
132
- }
133
- const results = await pipeline.exec();
134
- if (!results)
135
- return [];
136
- for (const [err, gamesString] of results) {
137
- if (err)
138
- throw err;
139
- if (gamesString) {
140
- const game = JSON.parse(gamesString);
141
- levrGames.push(game);
142
- }
143
- }
144
- return levrGames;
145
- };
146
- exports.getGamesByFixtureId = getGamesByFixtureId;
147
- /**
148
- * Retrieves all active games for a given fixture ID from the Redis cache.
149
- * @param redis - Redis client instance
150
- * @param levrFixtureId - The unique identifier for the fixture
151
- * @param gameCollectionKey - The Redis hash key under which the games are stored
152
- * @returns {Promise<LevrGame[]>} - A promise that resolves with an array of LevrGame objects
153
- * @notice all games are related to the fixtureId across all chains.
154
- */
155
- const getActiveGamesByFixtureId = async (redis, levrFixtureId) => {
156
- return (0, exports.getGamesByFixtureId)(redis, levrFixtureId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
157
- };
158
- exports.getActiveGamesByFixtureId = getActiveGamesByFixtureId;
159
- const getPostGamesByFixtureId = async (redis, levrFixtureId) => {
160
- return (0, exports.getGamesByFixtureId)(redis, levrFixtureId, cache_keys_utils_1.GameCollectionKeys.postGamesHash);
161
- };
162
- exports.getPostGamesByFixtureId = getPostGamesByFixtureId;
163
- //*********************************Fetch by collection************************************************ */
164
- /**
165
- * Retrieves all games from a Redis hash collection and flattens them into a single array
166
- *
167
- * @param redis - Redis client instance
168
- * @param gameCollectionKey - The Redis hash key under which the games are stored
169
- * @returns {Promise<LevrGame[]>} - A promise that resolves with an array of LevrGame objects
170
- *
171
- * Process:
172
- * 1. Retrieves all hash fields and values using hgetall
173
- * 2. Each hash value is a JSON string containing an array of games for a fixture
174
- * 3. Parses all JSON strings into LevrGame objects
175
- */
176
- const getGamesCache = async (redis, gameCollectionKey, chainId) => {
177
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, chainId);
178
- const gamesString = await redis.hgetall(hash);
179
- // what the data looks like
180
- // activeGamesHash: {
181
- // fixtureId1: '{"id": "gameId1", ...}',
182
- // fixtureId2: '{"id": "gameId3", ...}',
183
- // ...
184
- // }
185
- const games = Object.values(gamesString).map((gameString) => JSON.parse(gameString));
186
- return games;
187
- };
188
- // // TODO: @ooglec check this function
189
- /**
190
- * Gets all active games from the cache with relations (markets and scores)
191
- * @param redis - Redis client instance
192
- * @param gameCollectionKey - Key for the game collection in Redis
193
- * @param chainId - Blockchain network chain ID
194
- * @notice this does not make a specific distinction for select game or fixtureIds
195
- */
196
- const getGamesCacheWithRelations = async (redis, gameCollectionKey, chainId) => {
197
- const pipeline = redis.pipeline();
198
- // Execute the pipeline to get all games in one go
199
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, chainId);
200
- pipeline.hgetall(hash);
201
- // Execute the pipeline to get Scores
202
- pipeline.hgetall(cache_keys_utils_1.getGameScoreByFixtureIdHash);
203
- const results = await pipeline.exec();
204
- // what the data looks like
205
- // activeGamesHash: {
206
- // fixtureId1: '{"id": "gameId1", ...}',
207
- // fixtureId2: '{"id": "gameId3", ...}',
208
- // ...
209
- // }
210
- if (!results || results.length < 2) {
211
- throw new Error("Pipeline execution failed");
212
- }
213
- // Extract results and check for errors
214
- const [gamesResult, scoresResult] = results;
215
- if (!gamesResult || !scoresResult) {
216
- throw new Error("Invalid pipeline results");
217
- }
218
- const [gamesError, gamesHashResult] = gamesResult;
219
- const [scoresError, gamesScoresResult] = scoresResult;
220
- if (gamesError)
221
- throw gamesError;
222
- if (scoresError)
223
- throw scoresError;
224
- // // TODO: results will be stringified JSON, so we need to parse it first before checking it's type
225
- //@dev results will be of the type Record<string, string>
226
- // hgetall(hash) Returns: Record<string, string>
227
- if (!gamesHashResult || typeof gamesHashResult !== "object") {
228
- return [];
229
- }
230
- const gamesHash = gamesHashResult; // conforms to type returned by hgetAll
231
- const games = Object.values(gamesHash).map((gameString) => JSON.parse(gameString));
232
- // get game markets for each game
233
- const gameUniqueIdentifiers = games.map((game) => game.objectId);
234
- const marketTypesArray = Object.values(client_1.MarketType);
235
- const gameMarketsQuery = gameUniqueIdentifiers.flatMap((gameUniqueId) => marketTypesArray.map((marketType) => ({
236
- gameUniqueIdentifier: gameUniqueId,
237
- marketType,
238
- })));
239
- const gameMarkets = await (0, market_cache_service_1.getMarketDataCacheWithOdds)(redis, gameMarketsQuery);
240
- // map markets to games
241
- // scores
242
- const scoresHash = gamesScoresResult;
243
- const scores = {};
244
- for (const [levrFixtureId, scoreString] of Object.entries(scoresHash)) {
245
- if (scoreString) {
246
- scores[levrFixtureId] = JSON.parse(scoreString);
247
- }
248
- }
249
- const gamesWithMarketsAndScores = games.map((game) => {
250
- const markets = gameMarkets[game.objectId] ?? [];
251
- const score = scores[game.levrFixtureId] ?? null;
252
- if (!markets) {
253
- return {
254
- ...game,
255
- markets: [],
256
- scores: score,
257
- };
258
- }
259
- return {
260
- ...game,
261
- markets,
262
- scores: score,
263
- };
264
- });
265
- return gamesWithMarketsAndScores;
266
- };
267
- /**
268
- * Retrieves specific games from the cache based on fixture IDs
269
- *
270
- * @param redis - Redis client instance
271
- * @param gameCollectionKey - Key for the game collection in Redis
272
- * @param levrFixtureIds - Array of fixture IDs to retrieve
273
- * @param chainId - Blockchain network chain ID
274
- *
275
- * @returns Promise containing array of LevrGame objects
276
- *
277
- * Process:
278
- * 1. Uses Redis pipeline for batch operations
279
- * 2. Creates cache keys for each fixture ID
280
- * 3. Retrieves game data from gameCollectionKey using fixture cache keys
281
- * 4. Parses JSON strings into LevrGame objects
282
- * 5. Returns array of games
283
- */
284
- const getSpecificGamesCacheNoRelations = async (redis, gameCollectionKey, levrFixtureIds, chainId) => {
285
- // create a list of fields with levrFixtureIds
286
- const fields = levrFixtureIds.map((fixtureId) => (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(fixtureId, chainId));
287
- const hash = (0, cache_keys_utils_1.getGamesKeyByChainId)(gameCollectionKey, chainId);
288
- const results = await redis.hmget(hash, ...fields);
289
- /**
290
- * // TODO: @ooglec check results is not null,
291
- * then check if error is present in the results
292
- * then check for issues on result is defined and of expected type
293
- */
294
- const specificGames = [];
295
- for (const gamesString of results) {
296
- if (!gamesString)
297
- continue; // skip null or undefined values
298
- if (gamesString && typeof gamesString === "string") {
299
- const games = JSON.parse(gamesString);
300
- specificGames.push(games);
301
- }
302
- }
303
- return specificGames;
304
- };
305
- // adds markets. odds and scores to the game
306
- const getSpecificGamesCacheWithRelations = async (redis, gameCollectionKey, levrFixtureIds, chainId) => {
307
- const pipeline = redis.pipeline();
308
- // create a list of fields with levrFixtureIds
309
- const fields = levrFixtureIds.map((fixtureId) => (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(fixtureId, chainId));
310
- pipeline.hmget(gameCollectionKey, ...fields);
311
- pipeline.hmget(cache_keys_utils_1.getGameScoreByFixtureIdHash, ...fields);
312
- const results = await pipeline.exec();
313
- if (!results || results.length !== 2)
314
- return [];
315
- const specificGames = [];
316
- const gamesResult = results[0];
317
- const scoresResult = results[1];
318
- const scores = {};
319
- for (let i = 0; i < fields.length; i++) {
320
- const [err, scoreString] = scoresResult[i];
321
- if (err)
322
- throw err;
323
- if (scoreString) {
324
- scores[fields[i]] = JSON.parse(scoreString);
325
- }
326
- }
327
- for (const [err, gamesString] of gamesResult) {
328
- if (err)
329
- throw err;
330
- if (gamesString) {
331
- const game = JSON.parse(gamesString);
332
- specificGames.push(...game);
333
- }
334
- }
335
- const gamesWithRelations = [];
336
- const gameUniqueIdentifiers = specificGames.map((game) => game.objectId);
337
- // Create query for all markets
338
- const allMarketTypes = Object.values(client_1.MarketType);
339
- const allMarketsQuery = gameUniqueIdentifiers.flatMap((gameUniqueId) => allMarketTypes.map((marketType) => ({
340
- gameUniqueIdentifier: gameUniqueId,
341
- marketType,
342
- })));
343
- const gameMarkets = await (0, market_cache_service_1.getMarketDataCacheWithOdds)(redis, allMarketsQuery);
344
- for (const game of specificGames) {
345
- const fixtureId = game.levrFixtureId;
346
- const score = scores[fixtureId] ?? null;
347
- const markets = gameMarkets[game.objectId] ?? [];
348
- gamesWithRelations.push({
349
- ...game,
350
- markets,
351
- scores: score,
352
- });
353
- }
354
- return gamesWithRelations;
355
- };
356
- /**
357
- * Retrieves specific games from the cache based on game IDs
358
- *
359
- * @param redis - Redis client instance
360
- * @param gameCollectionKey - Key for the game collection in Redis
361
- * @param gameIds - Array of game IDs to retrieve
362
- * @param chainId - Blockchain network chain ID
363
- *
364
- * @returns Promise containing array of LevrGame objects
365
- *
366
- * Process:
367
- * 1. Uses Redis pipeline for batch operations
368
- * 2. Looks up fixture IDs from gameIdsToLevrFixtureIdsMap using game IDs
369
- * 3. Filters out null fixture IDs and creates cache keys for each fixture
370
- * 4. Retrieves game data from gameCollectionKey using fixture cache keys
371
- * 5. Parses JSON strings into LevrGame objects
372
- * 6. Returns flattened array of games
373
- */
374
- const getSpecificGamesCacheByGameIds = async (redis, gameCollectionKey, gameIds, chainId, withRelations = false) => {
375
- // get the respective fixtureIds for the gameIds
376
- const fixtureIds = await redis.hmget(cache_keys_utils_1.gameIdsToLevrFixtureIdsMap, ...gameIds);
377
- const fields = fixtureIds
378
- .filter((fixtureId) => fixtureId !== null)
379
- .map((fixtureId) => (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(fixtureId, chainId));
380
- if (fields.length === 0)
381
- return [];
382
- if (withRelations) {
383
- return await getSpecificGamesCacheWithRelations(redis, gameCollectionKey, fields, chainId);
384
- }
385
- return await getSpecificGamesCacheNoRelations(redis, gameCollectionKey, fields, chainId);
386
- };
387
- exports.getSpecificGamesCacheByGameIds = getSpecificGamesCacheByGameIds;
388
- const getSpecificGamesCacheByFixtureIds = async (redis, fixtureIds, chainId, withRelations = false, active = true) => {
389
- if (fixtureIds.length === 0)
390
- return [];
391
- const hash = active ? cache_keys_utils_1.GameCollectionKeys.activeGamesHash : cache_keys_utils_1.GameCollectionKeys.postGamesHash;
392
- if (withRelations) {
393
- return getSpecificGamesCacheWithRelations(redis, hash, fixtureIds, chainId);
394
- }
395
- return getSpecificGamesCacheNoRelations(redis, hash, fixtureIds, chainId);
396
- };
397
- exports.getSpecificGamesCacheByFixtureIds = getSpecificGamesCacheByFixtureIds;
398
- const getActiveGamesCache = async (redis, chainId) => {
399
- return getGamesCache(redis, cache_keys_utils_1.GameCollectionKeys.activeGamesHash, chainId);
400
- };
401
- exports.getActiveGamesCache = getActiveGamesCache;
402
- const getActiveGamesCacheWithRelations = async (redis, chainId) => {
403
- return getGamesCacheWithRelations(redis, cache_keys_utils_1.GameCollectionKeys.activeGamesHash, chainId);
404
- };
405
- exports.getActiveGamesCacheWithRelations = getActiveGamesCacheWithRelations;
406
- const getPostGamesCache = async (redis, chainId) => {
407
- return getGamesCache(redis, cache_keys_utils_1.GameCollectionKeys.postGamesHash, chainId);
408
- };
409
- exports.getPostGamesCache = getPostGamesCache;
410
- /**
411
- * Retrieves active games from the Redis cache using its fixture ID.
412
- * @param fixtureId - The unique identifier for the fixture.
413
- * @returns {Promise<LevrGame | null>} - A promise that resolves with a LevrGame object or null if not found.
414
- */
415
- const getGameCacheByFixtureId = async (redis, fixtureId) => {
416
- return (0, exports.getGamesByFixtureId)(redis, fixtureId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
417
- };
418
- exports.getGameCacheByFixtureId = getGameCacheByFixtureId;
419
- /**
420
- * Retrieves a game from the Redis cache using the provider's fixture ID.
421
- * @param providerFixtureId - The fixture ID provided by the odds provider, e.g (lsports, rundown, optic odds)
422
- * @returns {Promise<LevrGame | null>} - A promise that resolves with a LevrGame object or null if not found.
423
- */
424
- const getGameCacheByFixtureIdWithProviderFixtureId = async (redis, providerFixtureId) => {
425
- try {
426
- const levrFixtureId = await getLevrFixtureIdUsingProviderFixtureId(redis, providerFixtureId);
427
- if (!levrFixtureId)
428
- return null;
429
- const levrGameEventRedis = await (0, exports.getGamesByFixtureId)(redis, levrFixtureId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
430
- return levrGameEventRedis;
431
- }
432
- catch (err) {
433
- winston_1.default.error("error getting game cache by fixtureId", err);
434
- return null;
435
- }
436
- };
437
- exports.getGameCacheByFixtureIdWithProviderFixtureId = getGameCacheByFixtureIdWithProviderFixtureId;
438
- //*********************************Remove from games cache***************************************************** */
439
- const removeGamesCache = async (redis, levrFixtureId, chainId, gameCollectionKey) => {
440
- try {
441
- const fixtureKey = (0, cache_keys_utils_1.getCachedLevrByFixtureIdKey)(levrFixtureId, chainId);
442
- await redis.hdel(gameCollectionKey, fixtureKey);
443
- await redis.hdel(cache_keys_utils_1.gameIdsToLevrFixtureIdsMap, levrFixtureId);
444
- }
445
- catch (err) {
446
- winston_1.default.error(`Error removing games for fixture ${levrFixtureId}`, err);
447
- }
448
- };
449
- const removeActiveGamesCache = async (redis, levrFixtureId, chainId) => {
450
- await removeGamesCache(redis, levrFixtureId, chainId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
451
- };
452
- exports.removeActiveGamesCache = removeActiveGamesCache;
453
- const removePostGamesCache = async (redis, levrFixtureId, chainId) => {
454
- await removeGamesCache(redis, levrFixtureId, chainId, cache_keys_utils_1.GameCollectionKeys.postGamesHash);
455
- };
456
- exports.removePostGamesCache = removePostGamesCache;
457
- //*********************************Mapping games to fixture ids***************************************************** */
458
- /**
459
- * Maps a game ID to a Levr fixture ID in Redis.
460
- * @param gameId - The game ID to be mapped.
461
- * @param levrFixtureId - The corresponding Levr fixture ID.
462
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
463
- */
464
- const mapGameIdToLevrFixtureId = async (redis, gameId, levrFixtureId) => {
465
- const setMapping = await redis.hset(cache_keys_utils_1.gameIdsToFixtureIds, gameId.toString(), levrFixtureId);
466
- if (setMapping !== 1) {
467
- throw new Error(`Failed to set mapping for gameId: ${gameId.toString()} to levrFixtureId: ${levrFixtureId}`);
468
- }
469
- };
470
- exports.mapGameIdToLevrFixtureId = mapGameIdToLevrFixtureId;
471
- const mapProviderFixtureIdToLevrFixtureId = async (redis, fixtureIds) => {
472
- const pipeline = redis.pipeline();
473
- await (0, exports.mapProviderFixtureIdToLevrFixtureIdMany)(pipeline, [fixtureIds]);
474
- };
475
- exports.mapProviderFixtureIdToLevrFixtureId = mapProviderFixtureIdToLevrFixtureId;
476
- const mapProviderFixtureIdToLevrFixtureIdMany = async (pipeline, fixtureIdsList) => {
477
- // Use the pipeline to execute multiple commands in a single round trip
478
- for (const { levrFixtureId, lsportsFixtureId, opticOddsFixtureId } of fixtureIdsList) {
479
- for (const providerFixtureId of [lsportsFixtureId, opticOddsFixtureId]) {
480
- pipeline.hset(cache_keys_utils_1.providerFixtureIdToLevrId, providerFixtureId, levrFixtureId);
481
- }
482
- pipeline.hset(cache_keys_utils_1.levrIdToProviderIds, levrFixtureId, JSON.stringify({ lsportsFixtureId, opticOddsFixtureId }));
483
- }
484
- // Execute the pipeline
485
- const result = await pipeline.exec();
486
- if (!result || result.length === 0) {
487
- throw new Error(`Failed to set mappings for provider fixture IDs to Levr fixture ID`);
488
- }
489
- };
490
- exports.mapProviderFixtureIdToLevrFixtureIdMany = mapProviderFixtureIdToLevrFixtureIdMany;
491
- /**
492
- * Retrieves the Levr fixture ID using a game ID from Redis.
493
- * @param gameId - The ID of the game.
494
- * @returns {Promise<string | null>} - A promise that resolves with the Levr fixture ID or null if not found.
495
- */
496
- const getLevrFixtureIdUsingGameId = async (redis, gameId) => {
497
- return await redis.hget(cache_keys_utils_1.gameIdsToLevrFixtureIdsMap, gameId.toString());
498
- };
499
- exports.getLevrFixtureIdUsingGameId = getLevrFixtureIdUsingGameId;
500
- /**
501
- * Retrieves the Levr fixture ID using a provider's fixture ID from Redis.
502
- * @param providerFixtureId - The fixture ID provided by the data provider.
503
- * @returns {Promise<string | null>} - A promise that resolves with the Levr fixture ID or null if not found.
504
- */
505
- const getLevrFixtureIdUsingProviderFixtureId = async (redis, providerFixtureId) => {
506
- return await redis.hget(cache_keys_utils_1.providerFixtureIdToLevrId, providerFixtureId);
507
- };
508
- //*********************************Get game period info***************************************************** */
509
- /**
510
- * Updates the game clock in the Redis cache or in the database if not found in cache.
511
- * @param gameId - The ID of the game.
512
- * @param gameClock - The current game clock value.
513
- * @param gamePeriod - The current game period.
514
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
515
- */
516
- const updateGamesClockInCache = async (redis, levrFixtureId, gameClock, gamePeriod) => {
517
- const games = await (0, exports.getGamesByFixtureId)(redis, levrFixtureId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
518
- for (const game of games) {
519
- game.gameClock = gameClock;
520
- game.currentPeriod = gamePeriod;
521
- }
522
- await setGamesCache(redis.pipeline(), [...games], cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
523
- };
524
- exports.updateGamesClockInCache = updateGamesClockInCache;
525
- /**
526
- * Sets the game score in the Redis cache.
527
- * @param gameId - The ID of the game.
528
- * @param score - The Scores object to be cached.
529
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
530
- */
531
- const setGamesScoreCache = async (redis, fixtureId, score) => {
532
- const field = fixtureId;
533
- try {
534
- const done = await redis.hset(cache_keys_utils_1.getGameScoreByFixtureIdHash, field, JSON.stringify(score));
535
- if (done === 1) {
536
- winston_1.default.warn(`Failed to set game score for fixtureId: ${fixtureId}`);
537
- }
538
- }
539
- catch (err) {
540
- winston_1.default.error("error setting game score in cache", err);
541
- }
542
- };
543
- exports.setGamesScoreCache = setGamesScoreCache;
544
- /**
545
- * Retrieves the game score from the Redis cache.
546
- * @param gameId - The ID of the game.
547
- * @returns {Promise<LevrScores | null>} - A promise that resolves with a Scores object or null if not found.
548
- */
549
- const getGameScoreCache = async (redis, fixtureId) => {
550
- const gameScore = await redis.hget(cache_keys_utils_1.getGameScoreByFixtureIdHash, fixtureId);
551
- return gameScore ? JSON.parse(gameScore) : null;
552
- };
553
- exports.getGameScoreCache = getGameScoreCache;
554
- /**
555
- * Updates the game status in the Redis cache or in the database if not found in cache.
556
- * @param gameId - The ID of the game.
557
- * @param gamePhase - The new GamePhase value.
558
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
559
- */
560
- const updateGameStatusInCache = async (redis, gameIds, levrFixtureId, gamePhase) => {
561
- const games = await (0, exports.getGamesByFixtureId)(redis, levrFixtureId, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
562
- for (const game of games) {
563
- if (!gameIds.includes(game.gameId))
564
- continue;
565
- game.gamePhase = gamePhase;
566
- }
567
- await setGamesCache(redis.pipeline(), games, cache_keys_utils_1.GameCollectionKeys.activeGamesHash);
568
- };
569
- exports.updateGameStatusInCache = updateGameStatusInCache;
570
- /**
571
- * Deletes all sub-keys associated with a given Levr fixture ID.
572
- * @param levrFixtureId - The Levr fixture ID.
573
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
574
- */
575
- const deleteAllSubKeys = async (redis, levrFixtureId) => {
576
- const allEntries = await redis.hgetall(cache_keys_utils_1.gameIdsToFixtureIds);
577
- const gameIdsToDelete = Object.entries(allEntries)
578
- .filter(([fixtureId]) => fixtureId === levrFixtureId)
579
- .map(([gameId]) => gameId);
580
- if (gameIdsToDelete.length > 0) {
581
- await redis.hdel(cache_keys_utils_1.gameIdsToFixtureIds, ...gameIdsToDelete);
582
- }
583
- const allProviderFixtureIdsEntries = await redis.hgetall(cache_keys_utils_1.providerFixtureIdToLevrId);
584
- const providerIdsToDelete = Object.entries(allProviderFixtureIdsEntries)
585
- .filter(([fixtureId]) => fixtureId === levrFixtureId)
586
- .map(([providerFixtureId]) => providerFixtureId);
587
- if (providerIdsToDelete.length > 0) {
588
- await redis.hdel(cache_keys_utils_1.providerFixtureIdToLevrId, ...providerIdsToDelete);
589
- }
590
- };
591
- exports.deleteAllSubKeys = deleteAllSubKeys;
592
- /**
593
- * Invalidates the game score cache.
594
- * @param gameId - The ID of the game.
595
- * @returns {Promise<void>} - A promise that resolves when the operation is complete.
596
- */
597
- const invalidateScoreCache = async (redis, fixtureId, callbackPromise) => {
598
- try {
599
- await callbackPromise();
600
- await redis.hdel(cache_keys_utils_1.getGameScoreByFixtureIdHash, fixtureId);
601
- }
602
- catch (err) {
603
- winston_1.default.error("error invalidating score cache", err);
604
- }
605
- };
606
- exports.invalidateScoreCache = invalidateScoreCache;
607
- /**
608
- * Retrieves all provider fixture IDs associated with multiple Levr fixture IDs.
609
- *
610
- * This function queries Redis to find all provider-specific fixture IDs that correspond
611
- * to the given Levr fixture IDs. It uses a Redis pipeline to efficiently batch
612
- * multiple queries into a single network request.
613
- *
614
- * @param redis - The Redis client instance used to perform the queries
615
- * @param levrFixtureIda - An array of Levr fixture IDs to look up
616
- *
617
- * @returns A Promise resolving to a Record/object where:
618
- * - Keys are Levr fixture IDs from the input array
619
- * - Values are arrays of provider-specific fixture IDs associated with each Levr ID
620
- * - If a Levr ID has no associated provider IDs or doesn't exist, it will map to an empty array
621
- *
622
- * @example
623
- * Get provider IDs for two Levr fixture IDs
624
- * const providerMap = await getAllProvidersIdsForLevrFixtureIds(redisClient, ['levr-123', 'levr-456']);
625
- * Result might be: { 'levr-123': ['provider1-789', 'provider2-012'], 'levr-456': ['provider1-345'] }
626
- *
627
- * @throws Will throw an error if the Redis operation fails
628
- */
629
- const getAllProvidersIdsForLevrFixtureIds = async (redis, levrFixtureIds) => {
630
- const providerIdsMap = {};
631
- if (levrFixtureIds.length === 0) {
632
- winston_1.default.warn("No Levr fixture IDs provided to getAllProvidersIdsForLevrFixtureIds");
633
- return providerIdsMap;
634
- }
635
- try {
636
- const results = await redis.hmget(cache_keys_utils_1.levrIdToProviderIds, ...levrFixtureIds);
637
- /**
638
- * then check if error is present in the results
639
- * then check for issues on result is defined and of expected type
640
- */
641
- if (results.length !== levrFixtureIds.length) {
642
- winston_1.default.error(`Mismatch in results length: expected ${levrFixtureIds.length.toString()}, got ${results.length.toString()} in getAllProvidersIdsForLevrFixtureIds`);
643
- return providerIdsMap;
644
- }
645
- results.forEach((value, index) => {
646
- if (value && typeof value === "string") {
647
- // Parse the JSON string to get the array of provider IDs
648
- const parsedValue = JSON.parse(value);
649
- if (!Array.isArray(parsedValue)) {
650
- winston_1.default.warn(`Parsed value for Levr fixture ID ${levrFixtureIds[index]} is not an array`);
651
- }
652
- else {
653
- providerIdsMap[levrFixtureIds[index]] = parsedValue;
654
- }
655
- }
656
- else {
657
- providerIdsMap[levrFixtureIds[index]] = [];
658
- }
659
- });
660
- winston_1.default.info("Successfully retrieved provider fixture IDs for Levr fixture IDs");
661
- return providerIdsMap;
662
- }
663
- catch (err) {
664
- winston_1.default.error("Error getting provider fixture IDs for Levr fixture IDs", err);
665
- return providerIdsMap;
666
- }
667
- };
668
- exports.getAllProvidersIdsForLevrFixtureIds = getAllProvidersIdsForLevrFixtureIds;
669
- /**
670
- * Gets all fixture IDs associated with a list of game IDs from Redis
671
- *
672
- * @param redis - Redis client instance
673
- * @param gameIds - Array of game IDs to lookup
674
- * @returns Record mapping game IDs to arrays of fixture IDs
675
- * @throws Will throw an error if the Redis operation fails
676
- */
677
- const getAllFixtureIdsForGameIds = async (redis, gameIds) => {
678
- const fixtureIdsMap = {};
679
- if (gameIds.length === 0) {
680
- winston_1.default.warn("No game IDs provided to getAllFixtureIdsForGameIds");
681
- return fixtureIdsMap;
682
- }
683
- try {
684
- const results = await redis.hmget(cache_keys_utils_1.gameIdsToFixtureIds, ...gameIds);
685
- if (results.length !== gameIds.length) {
686
- winston_1.default.error(`Mismatch in results length: expected ${gameIds.length.toString()}, got ${results.length.toString()} in getAllFixtureIdsForGameIds`);
687
- return fixtureIdsMap;
688
- }
689
- results.forEach((value, index) => {
690
- if (value && typeof value === "string") {
691
- const parsedValue = JSON.parse(value);
692
- if (!Array.isArray(parsedValue)) {
693
- winston_1.default.warn(`Parsed value for game ID ${gameIds[index]} is not an array`);
694
- }
695
- else {
696
- fixtureIdsMap[gameIds[index]] = parsedValue;
697
- }
698
- }
699
- else {
700
- fixtureIdsMap[gameIds[index]] = [];
701
- }
702
- });
703
- winston_1.default.info("Successfully retrieved fixture IDs for game IDs");
704
- return fixtureIdsMap;
705
- }
706
- catch (err) {
707
- winston_1.default.error("Error getting fixture IDs for game IDs", err);
708
- return fixtureIdsMap;
709
- }
710
- };
711
- exports.getAllFixtureIdsForGameIds = getAllFixtureIdsForGameIds;
712
- //# sourceMappingURL=game.cache.service.js.map