|
| 1 | +import { getCache } from '@vercel/functions'; |
| 2 | + |
| 3 | +import { KvAdapter, SetCommandOptions } from '../types'; |
| 4 | + |
| 5 | +export class RuntimeCacheAdapter implements KvAdapter { |
| 6 | + private cache = getCache(); |
| 7 | + |
| 8 | + async mget<Data>(...keys: string[]): Promise<Array<Data | null>> { |
| 9 | + this.logger( |
| 10 | + `MGET - Keys: ${keys.toString()} - Source: RUNTIME_CACHE - Fetching ${keys.length} keys`, |
| 11 | + ); |
| 12 | + |
| 13 | + try { |
| 14 | + const values = await Promise.all( |
| 15 | + keys.map(async (key) => { |
| 16 | + try { |
| 17 | + // Use the Runtime Cache API |
| 18 | + const cachedValue = await this.cache.get(key); |
| 19 | + |
| 20 | + if (cachedValue !== null) { |
| 21 | + this.logger(`RUNTIME_CACHE GET - Key: ${key} - Found: true`); |
| 22 | + |
| 23 | + return cachedValue; |
| 24 | + } |
| 25 | + |
| 26 | + this.logger(`RUNTIME_CACHE GET - Key: ${key} - Found: false`); |
| 27 | + |
| 28 | + return null; |
| 29 | + } catch (error) { |
| 30 | + this.logger( |
| 31 | + `RUNTIME_CACHE GET ERROR - Key: ${key} - Error: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 32 | + ); |
| 33 | + |
| 34 | + return null; |
| 35 | + } |
| 36 | + }), |
| 37 | + ); |
| 38 | + |
| 39 | + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions |
| 40 | + return values as Array<Data | null>; |
| 41 | + } catch (error) { |
| 42 | + this.logger( |
| 43 | + `RUNTIME_CACHE ACCESS ERROR - Returning null values: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 44 | + ); |
| 45 | + |
| 46 | + // Return null for all keys if Runtime Cache is unavailable |
| 47 | + return keys.map(() => null); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 52 | + async set<Data>(key: string, value: Data, _opts?: SetCommandOptions): Promise<Data | null> { |
| 53 | + this.logger(`SET - Key: ${key} - Setting in runtime cache`); |
| 54 | + |
| 55 | + try { |
| 56 | + await this.cache.set(key, value); |
| 57 | + this.logger(`RUNTIME_CACHE SET - Key: ${key} - Success`); |
| 58 | + } catch (error) { |
| 59 | + this.logger( |
| 60 | + `RUNTIME_CACHE SET ERROR - Key: ${key} - Error: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + return value; |
| 65 | + } |
| 66 | + |
| 67 | + private logger(message: string) { |
| 68 | + // Check if logging is enabled using the same logic as the main KV class |
| 69 | + const loggingEnabled = |
| 70 | + (process.env.NODE_ENV !== 'production' && process.env.KV_LOGGER !== 'false') || |
| 71 | + process.env.KV_LOGGER === 'true'; |
| 72 | + |
| 73 | + if (loggingEnabled) { |
| 74 | + // eslint-disable-next-line no-console |
| 75 | + console.log(`[BigCommerce] Runtime Cache ${message}`); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments