diff --git a/examples/nodejs/cache/advanced.ts b/examples/nodejs/cache/advanced.ts index 9396287c6..9525229ac 100644 --- a/examples/nodejs/cache/advanced.ts +++ b/examples/nodejs/cache/advanced.ts @@ -1,9 +1,4 @@ import { - CacheGet, - ListCaches, - CreateCache, - CacheSet, - CacheDelete, CacheClient, Configurations, MomentoLoggerFactory, @@ -11,6 +6,11 @@ import { DefaultMomentoLoggerLevel, CredentialProvider, MiddlewareFactory, + CreateCacheResponse, + ListCachesResponse, + CacheSetResponse, + CacheGetResponse, + CacheDeleteResponse, } from '@gomomento/sdk'; import {range} from './utils/collections'; import * as fs from 'fs'; @@ -42,23 +42,31 @@ async function main() { async function createCacheExample() { const createCacheResponse = await momento.createCache(cacheName); - if (createCacheResponse instanceof CreateCache.AlreadyExists) { - logger.info('cache already exists'); - } else if (createCacheResponse instanceof CreateCache.Error) { - throw createCacheResponse.innerException(); + switch (createCacheResponse.type) { + case CreateCacheResponse.AlreadyExists: + logger.info('cache already exists'); + break; + case CreateCacheResponse.Success: + logger.info('cache created'); + break; + case CreateCacheResponse.Error: + throw createCacheResponse.innerException(); } } async function listCachesExample() { logger.info('Listing caches:'); const listResponse = await momento.listCaches(); - if (listResponse instanceof ListCaches.Error) { - logger.info(`Error listing caches: ${listResponse.message()}`); - } else if (listResponse instanceof ListCaches.Success) { - logger.info('Found caches:'); - listResponse.getCaches().forEach(cacheInfo => { - logger.info(`${cacheInfo.getName()}`); - }); + switch (listResponse.type) { + case ListCachesResponse.Success: + logger.info('Found caches:'); + listResponse.getCaches().forEach(cacheInfo => { + logger.info(`${cacheInfo.getName()}`); + }); + break; + case ListCachesResponse.Error: + logger.info(`Error listing caches: ${listResponse.message()}`); + break; } } @@ -70,26 +78,36 @@ async function setGetDeleteExample() { const setResponse = await momento.set(cacheName, cacheKey, cacheValue, { ttl: exampleTtlSeconds, }); - if (setResponse instanceof CacheSet.Success) { - logger.info('Key stored successfully!'); - } else if (setResponse instanceof CacheSet.Error) { - logger.info(`Error setting key: ${setResponse.message()}`); + switch (setResponse.type) { + case CacheSetResponse.Success: + logger.info('Key stored successfully!'); + break; + case CacheSetResponse.Error: + logger.info(`Error setting key: ${setResponse.message()}`); + break; } const getResponse = await momento.get(cacheName, cacheKey); - if (getResponse instanceof CacheGet.Hit) { - logger.info(`cache hit: ${getResponse.valueString()}`); - } else if (getResponse instanceof CacheGet.Miss) { - logger.info('cache miss'); - } else if (getResponse instanceof CacheGet.Error) { - logger.info(`Error: ${getResponse.message()}`); + switch (getResponse.type) { + case CacheGetResponse.Miss: + logger.info('cache miss'); + break; + case CacheGetResponse.Hit: + logger.info(`cache hit: ${getResponse.valueString()}`); + break; + case CacheGetResponse.Error: + logger.info(`Error: ${getResponse.message()}`); + break; } const deleteResponse = await momento.delete(cacheName, cacheKey); - if (deleteResponse instanceof CacheDelete.Error) { - logger.info(`Error deleting cache key: ${deleteResponse.message()}`); - } else if (deleteResponse instanceof CacheDelete.Success) { - logger.info('Deleted key from cache'); + switch (deleteResponse.type) { + case CacheDeleteResponse.Success: + logger.info('Deleted key from cache'); + break; + case CacheDeleteResponse.Error: + logger.info(`Error deleting cache key: ${deleteResponse.message()}`); + break; } } @@ -103,7 +121,7 @@ async function concurrentGetsExample() { const getResponses = await Promise.all(getPromises); getResponses.forEach((response, index) => { const key = `key${index + 1}`; - if (response instanceof CacheGet.Hit) { + if (response.type === CacheGetResponse.Hit) { logger.info(`Concurrent get for ${key} returned ${response.valueString()}`); } else { logger.info(`Something went wrong with concurrent get for key ${key}: ${response.toString()}`); diff --git a/examples/nodejs/cache/readme.ts b/examples/nodejs/cache/readme.ts index b7ace94d6..7f2d62f3b 100644 --- a/examples/nodejs/cache/readme.ts +++ b/examples/nodejs/cache/readme.ts @@ -1,4 +1,4 @@ -import {CacheGet, CacheClient, Configurations, CredentialProvider} from '@gomomento/sdk'; +import {CacheClient, CacheGetResponse, Configurations, CredentialProvider} from '@gomomento/sdk'; async function main() { const cacheClient = await CacheClient.create({ @@ -10,7 +10,7 @@ async function main() { await cacheClient.createCache('cache'); await cacheClient.set('cache', 'foo', 'FOO'); const getResponse = await cacheClient.get('cache', 'foo'); - if (getResponse instanceof CacheGet.Hit) { + if (getResponse.type === CacheGetResponse.Hit) { console.log(`Got value: ${getResponse.valueString()}`); } } diff --git a/examples/nodejs/compression-zstd/compression.ts b/examples/nodejs/compression-zstd/compression.ts index 62b3ecded..32798e9c7 100644 --- a/examples/nodejs/compression-zstd/compression.ts +++ b/examples/nodejs/compression-zstd/compression.ts @@ -1,10 +1,10 @@ import { CacheClient, - CacheGet, - CacheSet, + CacheGetResponse, + CacheSetResponse, CompressionLevel, Configurations, - CreateCache, + CreateCacheResponse, CredentialProvider, } from '@gomomento/sdk'; import {CompressorFactory} from '@gomomento/sdk-nodejs-compression-zstd'; @@ -29,10 +29,16 @@ async function main() { // create cache const cacheName = 'cache'; const createResponse = await cacheClient.createCache(cacheName); - if (createResponse instanceof CreateCache.Success) { - console.log('Cache created successfully!'); - } else { - console.log(`Error creating cache: ${createResponse.toString()}`); + switch (createResponse.type) { + case CreateCacheResponse.AlreadyExists: + console.log(`Cache already exists: ${cacheName}`); + break; + case CreateCacheResponse.Success: + console.log('Cache created successfully!'); + break; + case CreateCacheResponse.Error: + console.log(`Error creating cache: ${createResponse.toString()}`); + break; } // This string is long and repetitive enough to be compressible. @@ -42,32 +48,43 @@ async function main() { const setResponse = await cacheClient.set(cacheName, 'my-key', compressibleValue, { compress: true, }); - if (setResponse instanceof CacheSet.Success) { - console.log('Key stored successfully with compression!'); - } else { - console.log(`Error setting key: ${setResponse.toString()}`); + switch (setResponse.type) { + case CacheSetResponse.Success: + console.log('Key stored successfully with compression!'); + break; + case CacheSetResponse.Error: + console.log(`Error setting key: ${setResponse.toString()}`); + break; } // get the value without decompressing const noDecompressResponse = await cacheClient.get(cacheName, 'my-key', { decompress: false, }); - if (noDecompressResponse instanceof CacheGet.Hit) { - console.log(`cache hit, compressed value: ${noDecompressResponse.valueString()}`); - } else if (noDecompressResponse instanceof CacheGet.Miss) { - console.log('cache miss'); - } else if (noDecompressResponse instanceof CacheGet.Error) { - console.log(`Error: ${noDecompressResponse.message()}`); + switch (noDecompressResponse.type) { + case CacheGetResponse.Miss: + console.log('cache miss'); + break; + case CacheGetResponse.Hit: + console.log(`cache hit, compressed value: ${noDecompressResponse.valueString()}`); + break; + case CacheGetResponse.Error: + console.log(`Error: ${noDecompressResponse.message()}`); + break; } // get decompressed value const getResponse = await cacheClient.get(cacheName, 'my-key'); - if (getResponse instanceof CacheGet.Hit) { - console.log(`cache hit, decompressed value: ${getResponse.valueString()}`); - } else if (getResponse instanceof CacheGet.Miss) { - console.log('cache miss'); - } else if (getResponse instanceof CacheGet.Error) { - console.log(`Error: ${getResponse.message()}`); + switch (getResponse.type) { + case CacheGetResponse.Miss: + console.log('cache miss'); + break; + case CacheGetResponse.Hit: + console.log(`cache hit, decompressed value: ${getResponse.valueString()}`); + break; + case CacheGetResponse.Error: + console.log(`Error: ${getResponse.message()}`); + break; } } diff --git a/examples/nodejs/get-set-batch-perf-test/perf-test.ts b/examples/nodejs/get-set-batch-perf-test/perf-test.ts index 8418c7988..3e62d8b23 100644 --- a/examples/nodejs/get-set-batch-perf-test/perf-test.ts +++ b/examples/nodejs/get-set-batch-perf-test/perf-test.ts @@ -1,8 +1,11 @@ import { CacheClient, - CacheGetBatch, + CacheGet, + CacheGetBatchResponse, + CacheGetResponse, CacheSet, - CacheSetBatch, + CacheSetBatchResponse, + CacheSetResponse, DefaultMomentoLoggerFactory, DefaultMomentoLoggerLevel, MomentoLogger, @@ -237,7 +240,7 @@ class PerfTest { } const setResponses = await Promise.all(setPromises); const setDuration = getElapsedMillis(setStartTime); - const error = setResponses.find(response => response instanceof CacheSet.Error); + const error = setResponses.find(response => response.type === CacheSetResponse.Error); if (error !== undefined) { throw new Error(`Error in async sets: ${error.toString()}`); } @@ -249,7 +252,7 @@ class PerfTest { context: PerfTestContext, getConfig: GetSetConfig ): Promise { - const getPromises: Promise[] = []; + const getPromises: Promise[] = []; const getStartTime = process.hrtime(); for (let i = 0; i < getConfig.batchSize; i++) { const key = `key-${i}`; @@ -259,7 +262,7 @@ class PerfTest { } const getResponses = await Promise.all(getPromises); const getDuration = getElapsedMillis(getStartTime); - const error = getResponses.find(response => response instanceof CacheSet.Error); + const error = getResponses.find(response => response.type === CacheGetResponse.Error); if (error !== undefined) { throw new Error(`Error in async gets: ${error.toString()}`); } @@ -282,8 +285,7 @@ class PerfTest { context.totalItemSizeBytes += setConfig.batchSize * setConfig.itemSizeBytes; const setBatchResponse = await setBatchPromise; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (setBatchResponse instanceof CacheSetBatch.Error) { + if (setBatchResponse.type === CacheSetBatchResponse.Error) { throw new Error(`Error setting batch: ${setBatchResponse.toString()}`); } const setBatchDuration = getElapsedMillis(setBatchStartTime); @@ -300,8 +302,7 @@ class PerfTest { const getBatchPromise = momento.getBatch(this.cacheName, keys); context.totalItemSizeBytes += getConfig.batchSize * getConfig.itemSizeBytes; const getBatchResponse = await getBatchPromise; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (getBatchResponse instanceof CacheGetBatch.Error) { + if (getBatchResponse.type === CacheGetBatchResponse.Error) { throw new Error(`Error getting batch: ${getBatchResponse.toString()}`); } const getBatchDuration = getElapsedMillis(getBatchStartTime); diff --git a/examples/nodejs/get-set-batch-perf-test/utils/cache.ts b/examples/nodejs/get-set-batch-perf-test/utils/cache.ts index 1d5180431..55bbc2ebc 100644 --- a/examples/nodejs/get-set-batch-perf-test/utils/cache.ts +++ b/examples/nodejs/get-set-batch-perf-test/utils/cache.ts @@ -1,11 +1,11 @@ import { CacheClient, Configurations, - CreateCache, EnvMomentoTokenProvider, MomentoLogger, MomentoLoggerFactory, - CacheFlush, + CreateCacheResponse, + FlushCacheResponse, } from '@gomomento/sdk'; export function getCacheClient( @@ -33,18 +33,25 @@ export function getCacheClient( export async function createCache(momentCacheClient: CacheClient, cacheName: string, logger: MomentoLogger) { const createResponse = await momentCacheClient.createCache(cacheName); - if (createResponse instanceof CreateCache.AlreadyExists) { - logger.info(`cache '${cacheName}' already exists`); - } else if (createResponse instanceof CreateCache.Error) { - throw createResponse.innerException(); + switch (createResponse.type) { + case CreateCacheResponse.AlreadyExists: + logger.info(`cache '${cacheName}' already exists`); + break; + case CreateCacheResponse.Success: + logger.info('created cache'); + break; + case CreateCacheResponse.Error: + throw createResponse.innerException(); } } export async function flushCache(momentCacheClient: CacheClient, cacheName: string, logger: MomentoLogger) { const flushCacheResponse = await momentCacheClient.flushCache(cacheName); - if (flushCacheResponse instanceof CacheFlush.Success) { - logger.info('Cache flushed successfully'); - } else if (flushCacheResponse instanceof CacheFlush.Error) { - throw flushCacheResponse.innerException(); + switch (flushCacheResponse.type) { + case FlushCacheResponse.Success: + logger.info('Cache flushed successfully'); + break; + case FlushCacheResponse.Error: + throw flushCacheResponse.innerException(); } } diff --git a/examples/nodejs/mongodb-examples/simple-read-aside/src/read-aside-momento-mongo.ts b/examples/nodejs/mongodb-examples/simple-read-aside/src/read-aside-momento-mongo.ts index 7ba301804..be8a086a7 100644 --- a/examples/nodejs/mongodb-examples/simple-read-aside/src/read-aside-momento-mongo.ts +++ b/examples/nodejs/mongodb-examples/simple-read-aside/src/read-aside-momento-mongo.ts @@ -1,4 +1,4 @@ -import {CacheClient, CacheGet, CacheSet} from '@gomomento/sdk'; +import {CacheClient, CacheGet, CacheGetResponse, CacheSet, CacheSetResponse} from '@gomomento/sdk'; import { MongoClient } from "mongodb"; interface WrapperArgs { @@ -17,13 +17,16 @@ export class ReadAsideWrapper { public async getItem(keyToGet: string): Promise { const getResponse = await this.client.get(this.cacheName, keyToGet); - if (getResponse instanceof CacheGet.Hit) { - return getResponse.valueString(); - } else if (getResponse instanceof CacheGet.Miss) { + switch (getResponse.type) { + case CacheGetResponse.Miss: console.log(`Cache MISS. Fetching data from DB instead. key=${keyToGet}`) - } else if (getResponse instanceof CacheGet.Error) { + break; + case CacheGetResponse.Hit: + return getResponse.valueString(); + case CacheGetResponse.Error: console.error(`Error fetching from Cache. Falling back to DB. key=${keyToGet} err=${getResponse.message()}`); // We are not throwing an error here as we are going to attempt next to get the item from MongoDB. + break; } const resp = await this.MongoDBHandler(keyToGet, this.cacheName); @@ -31,12 +34,14 @@ export class ReadAsideWrapper { if (resp !== 'null') { const setRsp = await this.client.set(this.cacheName, keyToGet, resp); // If the value is inserted into the Momento Cache, return success. - if (setRsp instanceof CacheSet.Success) { - console.log(`Retrieved data from MongoDB and inserted into Momento. key=${keyToGet}`); - } else if (setRsp instanceof CacheSet.Error) { - console.error(`Retrieved data from MongoDB but failed to insert into Momento. key=${keyToGet} err=${setRsp.message()}`); - return resp; - } + switch (setRsp.type) { + case CacheSetResponse.Success: + console.log(`Retrieved data from MongoDB and inserted into Momento. key=${keyToGet}`); + break; + case CacheSetResponse.Error: + console.error(`Retrieved data from MongoDB but failed to insert into Momento. key=${keyToGet} err=${setRsp.message()}`); + return resp; + } } else { const err: string = "Item not in Momento cache or MongoDB"; console.error(err); diff --git a/examples/nodejs/observability/observability.ts b/examples/nodejs/observability/observability.ts index 1372f9916..900a2c172 100644 --- a/examples/nodejs/observability/observability.ts +++ b/examples/nodejs/observability/observability.ts @@ -5,7 +5,14 @@ example_observability_setupMetrics(); // Note that these must run before anything else to properly instrument the gRPC calls and // configure OpenTelemetry to send metrics to Prometheus and traces to Zipkin. -import {CacheGet, CreateCache, CacheSet, CacheClient, Configurations, CredentialProvider} from '@gomomento/sdk'; +import { + CacheClient, + Configurations, + CredentialProvider, + CreateCacheResponse, + CacheSetResponse, + CacheGetResponse, +} from '@gomomento/sdk'; import {ExampleMetricMiddleware} from './example-metric-middleware'; import {uuid} from 'uuidv4'; @@ -21,10 +28,15 @@ async function main() { console.log("Creating cache 'cache'"); const createCacheResponse = await momento.createCache(cache); - if (createCacheResponse instanceof CreateCache.AlreadyExists) { - console.log('cache already exists'); - } else if (createCacheResponse instanceof CreateCache.Error) { - throw createCacheResponse.innerException(); + switch (createCacheResponse.type) { + case CreateCacheResponse.AlreadyExists: + console.log('cache already exists'); + break; + case CreateCacheResponse.Success: + console.log('cache created'); + break; + case CreateCacheResponse.Error: + throw createCacheResponse.innerException(); } for (let i = 0; i < 100; i++) { @@ -32,19 +44,26 @@ async function main() { const value = uuid(); console.log(`${i}: Storing key=${key}, value=${value}`); const setResponse = await momento.set(cache, key, value); - if (setResponse instanceof CacheSet.Success) { - console.log('Key stored successfully!'); - } else { - console.log(`Error setting key: ${setResponse.toString()}`); + switch (setResponse.type) { + case CacheSetResponse.Success: + console.log('Key stored successfully!'); + break; + case CacheSetResponse.Error: + console.log(`Error setting key: ${setResponse.toString()}`); + break; } const getResponse = await momento.get(cache, key); - if (getResponse instanceof CacheGet.Hit) { - console.log(`cache hit: ${getResponse.valueString()}`); - } else if (getResponse instanceof CacheGet.Miss) { - console.log('cache miss'); - } else if (getResponse instanceof CacheGet.Error) { - console.log(`Error: ${getResponse.message()}`); + switch (getResponse.type) { + case CacheGetResponse.Miss: + console.log('cache miss'); + break; + case CacheGetResponse.Hit: + console.log(`cache hit: ${getResponse.valueString()}`); + break; + case CacheGetResponse.Error: + console.log(`Error: ${getResponse.message()}`); + break; } } }