From 7940999c4bcd1eb672877fc83370665a2be11941 Mon Sep 17 00:00:00 2001 From: Chris Price Date: Wed, 21 Aug 2024 15:04:10 -0700 Subject: [PATCH] chore: more work on porting examples to new switch pattern (#1416) * chore: more work on porting examples to new switch pattern --- examples/nodejs/cache/batchutils.ts | 29 ++--- examples/nodejs/cache/dictionary.ts | 102 +++++++++++------- examples/nodejs/cache/leaderboard.ts | 114 ++++++++++++-------- examples/nodejs/cache/sharded-dictionary.ts | 70 +++++++----- 4 files changed, 192 insertions(+), 123 deletions(-) diff --git a/examples/nodejs/cache/batchutils.ts b/examples/nodejs/cache/batchutils.ts index e311cd0d5..6dc1bf50e 100644 --- a/examples/nodejs/cache/batchutils.ts +++ b/examples/nodejs/cache/batchutils.ts @@ -1,12 +1,12 @@ import { - CacheDelete, - CacheGet, - CacheSet, + BatchUtils, CacheClient, + CacheDeleteResponse, + CacheGetResponse, + CacheSetResponse, Configurations, + CreateCacheResponse, CredentialProvider, - CreateCache, - BatchUtils, } from '@gomomento/sdk'; const cacheName = 'cache'; @@ -19,10 +19,15 @@ async function main() { }); const createCacheResponse = await cacheClient.createCache(cacheName); - 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(); } const items: Array = [ @@ -36,19 +41,19 @@ async function main() { const setResponse = await BatchUtils.batchSet(cacheClient, cacheName, items); console.log('\nValues set for the following keys?'); for (const [key, resp] of Object.entries(setResponse)) { - console.log(`\t|${key}: ${String(resp instanceof CacheSet.Success)}`); + console.log(`\t|${key}: ${String(resp.type === CacheSetResponse.Success)}`); } const getResponse = await BatchUtils.batchGet(cacheClient, cacheName, ['a', 'b', 'c', '1', '2', '3']); console.log('\nValues fetched for the following keys?'); for (const [key, resp] of Object.entries(getResponse)) { - console.log(`\t|${key}: ${String(resp instanceof CacheGet.Hit)} | value: ${(resp as CacheGet.Hit).value()}`); + console.log(`\t|${key}: ${String(resp.type === CacheGetResponse.Hit)} | value: ${String(resp.value())}`); } const deleteResponse = await BatchUtils.batchDelete(cacheClient, cacheName, ['a', 'b', 'c', '1', '2', '3']); console.log('\nValues deleted for the following keys?'); for (const [key, resp] of Object.entries(deleteResponse)) { - console.log(`\t|${key}: ${String(resp instanceof CacheDelete.Success)}`); + console.log(`\t|${key}: ${String(resp.type === CacheDeleteResponse.Success)}`); } } diff --git a/examples/nodejs/cache/dictionary.ts b/examples/nodejs/cache/dictionary.ts index c23f2ed95..864524201 100644 --- a/examples/nodejs/cache/dictionary.ts +++ b/examples/nodejs/cache/dictionary.ts @@ -1,16 +1,16 @@ import { - CreateCache, CacheClient, - EnvMomentoTokenProvider, + CacheDictionaryFetchResponse, + CacheDictionaryGetFieldResponse, + CacheDictionaryGetFieldsResponse, + CacheDictionarySetFieldResponse, + CacheDictionarySetFieldsResponse, + CollectionTtl, Configurations, - CacheDictionarySetField, - CacheDictionarySetFields, - CacheDictionaryGetField, - CacheDictionaryGetFields, - CacheDictionaryFetch, - MomentoLoggerFactory, + CreateCacheResponse, DefaultMomentoLoggerFactory, - CollectionTtl, + EnvMomentoTokenProvider, + MomentoLoggerFactory, } from '@gomomento/sdk'; const cacheName = 'cache'; @@ -33,15 +33,20 @@ const main = async () => { }); const createCacheResponse = await momento.createCache(cacheName); - 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(); } // Set a value const dictionarySetFieldResponse = await momento.dictionarySetField(cacheName, dictionaryName, 'field1', 'value1'); - if (dictionarySetFieldResponse instanceof CacheDictionarySetField.Error) { + if (dictionarySetFieldResponse.type === CacheDictionarySetFieldResponse.Error) { console.log(`Error setting a value in a dictionary: ${dictionarySetFieldResponse.message()}`); process.exitCode = 1; } @@ -60,7 +65,7 @@ const main = async () => { ttl: CollectionTtl.of(30).withNoRefreshTtlOnUpdates(), } ); - if (dictionarySetFieldsResponse instanceof CacheDictionarySetFields.Error) { + if (dictionarySetFieldsResponse.type === CacheDictionarySetFieldsResponse.Error) { console.log(`Error setting multiple values in a dictionary: ${dictionarySetFieldsResponse.message()}`); process.exitCode = 1; } @@ -69,43 +74,58 @@ const main = async () => { console.log('\nGetting a single dictionary value'); const field = 'field1'; const dictionaryGetFieldResponse = await momento.dictionaryGetField(cacheName, dictionaryName, field); - if (dictionaryGetFieldResponse instanceof CacheDictionaryGetField.Hit) { - console.log(`Dictionary get of ${field}: status=HIT; value=${dictionaryGetFieldResponse.valueString()}`); - } else if (dictionaryGetFieldResponse instanceof CacheDictionaryGetField.Miss) { - // In this example you can get here if you: - // - change the field name to one that does not exist, or if you - // - set a short TTL, then add a sleep so that it expires. - console.log(`Dictionary get of ${field}: status=MISS`); - } else if (dictionaryGetFieldResponse instanceof CacheDictionaryGetField.Error) { - console.log(`Error getting value from dictionary: ${dictionaryGetFieldResponse.message()}`); - process.exitCode = 1; + switch (dictionaryGetFieldResponse.type) { + case CacheDictionaryGetFieldResponse.Miss: + // In this example you can get here if you: + // - change the field name to one that does not exist, or if you + // - set a short TTL, then add a sleep so that it expires. + console.log(`Dictionary get of ${field}: status=MISS`); + break; + case CacheDictionaryGetFieldResponse.Hit: + console.log(`Dictionary get of ${field}: status=HIT; value=${dictionaryGetFieldResponse.value()}`); + break; + case CacheDictionaryGetFieldResponse.Error: + console.log(`Error getting value from dictionary: ${dictionaryGetFieldResponse.message()}`); + process.exitCode = 1; + break; } // Get multiple values console.log('\nGetting multiple dictionary values'); const fieldsList = ['field1', 'field2', 'field3', 'field4']; const dictionaryGetFieldsResponse = await momento.dictionaryGetFields(cacheName, dictionaryName, fieldsList); - if (dictionaryGetFieldsResponse instanceof CacheDictionaryGetFields.Hit) { - console.log(`Got dictionary fields: ${JSON.stringify(dictionaryGetFieldsResponse.valueRecord(), null, 2)}`); - } else if (dictionaryGetFieldsResponse instanceof CacheDictionaryGetFields.Error) { - console.log(`Error getting values from a dictionary: ${dictionaryGetFieldsResponse.message()}`); - process.exitCode = 1; + switch (dictionaryGetFieldsResponse.type) { + case CacheDictionaryGetFieldsResponse.Miss: + console.log('Got a MISS on dictionaryGetFields!'); + break; + case CacheDictionaryGetFieldsResponse.Hit: + console.log(`Got dictionary fields: ${JSON.stringify(dictionaryGetFieldsResponse.value(), null, 2)}`); + break; + case CacheDictionaryGetFieldsResponse.Error: + console.log(`Error getting values from a dictionary: ${dictionaryGetFieldsResponse.message()}`); + process.exitCode = 1; + break; } // Get the whole dictionary console.log('\nGetting an entire dictionary'); const dictionaryFetchResponse = await momento.dictionaryFetch(cacheName, dictionaryName); - if (dictionaryFetchResponse instanceof CacheDictionaryFetch.Hit) { - const dictionary = dictionaryFetchResponse.valueRecord(); - console.log(`Fetched dictionary: ${JSON.stringify(dictionary, null, 2)}`); - } else if (dictionaryFetchResponse instanceof CacheDictionaryFetch.Miss) { - // You can reach here by: - // - fetching a dictionary that does not exist, e.g. changing the name above, or - // - setting a short TTL and adding a Task.Delay so the dictionary expires - console.log(`Expected ${dictionaryName} to be a hit; got a miss.`); - } else if (dictionaryFetchResponse instanceof CacheDictionaryFetch.Error) { - console.log(`Error while fetching ${dictionaryName}: ${dictionaryFetchResponse.message()}`); - process.exitCode = 1; + switch (dictionaryFetchResponse.type) { + case CacheDictionaryFetchResponse.Miss: + // You can reach here by: + // - fetching a dictionary that does not exist, e.g. changing the name above, or + // - setting a short TTL and adding a Task.Delay so the dictionary expires + console.log(`Expected ${dictionaryName} to be a hit; got a miss.`); + break; + case CacheDictionaryFetchResponse.Hit: { + const dictionary = dictionaryFetchResponse.value(); + console.log(`Fetched dictionary: ${JSON.stringify(dictionary, null, 2)}`); + break; + } + case CacheDictionaryFetchResponse.Error: + console.log(`Error while fetching ${dictionaryName}: ${dictionaryFetchResponse.message()}`); + process.exitCode = 1; + break; } }; diff --git a/examples/nodejs/cache/leaderboard.ts b/examples/nodejs/cache/leaderboard.ts index fc8dd10c1..cea6a039b 100644 --- a/examples/nodejs/cache/leaderboard.ts +++ b/examples/nodejs/cache/leaderboard.ts @@ -4,15 +4,15 @@ import { CredentialProvider, CacheClient, Configurations, - CreateCache, - LeaderboardDelete, - LeaderboardFetch, - LeaderboardLength, LeaderboardOrder, - LeaderboardRemoveElements, - LeaderboardUpsert, DefaultMomentoLoggerLevel, DefaultMomentoLoggerFactory, + CreateCacheResponse, + LeaderboardUpsertResponse, + LeaderboardFetchResponse, + LeaderboardLengthResponse, + LeaderboardRemoveElementsResponse, + LeaderboardDeleteResponse, } from '@gomomento/sdk'; async function main() { @@ -26,10 +26,15 @@ async function main() { }); const createCacheResponse = await cacheClient.createCache('my-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(); } const client = new PreviewLeaderboardClient({ @@ -47,10 +52,13 @@ async function main() { [789, 300.0], ]); const upsertResp1 = await leaderboard.upsert(elements1); - if (upsertResp1 instanceof LeaderboardUpsert.Success) { - console.log('Upsert attempt 1: success'); - } else if (upsertResp1 instanceof LeaderboardUpsert.Error) { - console.log('Upsert error:', upsertResp1.message()); + switch (upsertResp1.type) { + case LeaderboardUpsertResponse.Success: + console.log('Upsert attempt 1: success'); + break; + case LeaderboardUpsertResponse.Error: + console.log('Upsert error:', upsertResp1.message()); + break; } // Or upsert elements using a Record @@ -58,11 +66,15 @@ async function main() { 1234: 111, 5678: 222, }; + const upsertResp2 = await leaderboard.upsert(elements2); - if (upsertResp2 instanceof LeaderboardUpsert.Success) { - console.log('Upsert attempt 2: success'); - } else if (upsertResp2 instanceof LeaderboardUpsert.Error) { - console.log('Upsert error:', upsertResp2.message()); + switch (upsertResp2.type) { + case LeaderboardUpsertResponse.Success: + console.log('Upsert attempt 2: success'); + break; + case LeaderboardUpsertResponse.Error: + console.log('Upsert error:', upsertResp2.message()); + break; } // Fetch by score example specifying all options. @@ -73,10 +85,13 @@ async function main() { offset: 10, count: 100, }); - if (fetchByScore instanceof LeaderboardFetch.Success) { - console.log('Fetch by score success:', fetchByScore.values()); - } else if (fetchByScore instanceof LeaderboardFetch.Error) { - console.log('Fetch by score error:', fetchByScore.message()); + switch (fetchByScore.type) { + case LeaderboardFetchResponse.Success: + console.log('Fetch by score success:', fetchByScore.values()); + break; + case LeaderboardFetchResponse.Error: + console.log('Fetch by score error:', fetchByScore.message()); + break; } // Fetch by rank can be used to page through the leaderboard @@ -86,10 +101,13 @@ async function main() { const startRank = rank; const endRank = rank + 2; const fetchByRank = await leaderboard.fetchByRank(startRank, endRank, {order: LeaderboardOrder.Ascending}); - if (fetchByRank instanceof LeaderboardFetch.Success) { - console.log('Fetch by rank success:', fetchByRank.values()); - } else if (fetchByRank instanceof LeaderboardFetch.Error) { - console.log('Fetch by rank error:', fetchByRank.message()); + switch (fetchByRank.type) { + case LeaderboardFetchResponse.Success: + console.log('Fetch by rank success:', fetchByRank.values()); + break; + case LeaderboardFetchResponse.Error: + console.log('Fetch by rank error:', fetchByRank.message()); + break; } } @@ -97,37 +115,49 @@ async function main() { const getRank = await leaderboard.getRank([123, 1234], { order: LeaderboardOrder.Ascending, }); - if (getRank instanceof LeaderboardFetch.Success) { - console.log('Get rank success:', getRank.values()); - } else if (getRank instanceof LeaderboardFetch.Error) { - console.log('Get rank error:', getRank.message()); + switch (getRank.type) { + case LeaderboardFetchResponse.Success: + console.log('Get rank success:', getRank.values()); + break; + case LeaderboardFetchResponse.Error: + console.log('Get rank error:', getRank.message()); + break; } // Length returns length of a leaderboard. Returns 0 if // leaderboard is empty or doesn't exist. const lengthResp = await leaderboard.length(); - if (lengthResp instanceof LeaderboardLength.Success) { - console.log('Get leaderboard length success:', lengthResp.length()); - } else if (lengthResp instanceof LeaderboardLength.Error) { - console.log('Get leaderboard length error:', lengthResp.message()); + switch (lengthResp.type) { + case LeaderboardLengthResponse.Success: + console.log('Get leaderboard length success:', lengthResp.length()); + break; + case LeaderboardLengthResponse.Error: + console.log('Get leaderboard length error:', lengthResp.message()); + break; } // Remove elements by providing a list of element IDs. const removeResp = await leaderboard.removeElements([123, 456, 789]); - if (removeResp instanceof LeaderboardRemoveElements.Success) { - console.log('Remove elements success'); - } else if (removeResp instanceof LeaderboardRemoveElements.Error) { - console.log('Remove elements error:', removeResp.message()); + switch (removeResp.type) { + case LeaderboardRemoveElementsResponse.Success: + console.log('Remove elements success'); + break; + case LeaderboardRemoveElementsResponse.Error: + console.log('Remove elements error:', removeResp.message()); + break; } // Delete will remove theh entire leaderboard. // Leaderboard items have no TTL so make sure to clean up // all unnecessary elements when no longer needed. const deleteResp = await leaderboard.delete(); - if (deleteResp instanceof LeaderboardDelete.Success) { - console.log('Delete leaderboard success'); - } else if (deleteResp instanceof LeaderboardDelete.Error) { - console.log('Delete leaderboard error:', deleteResp.message()); + switch (deleteResp.type) { + case LeaderboardDeleteResponse.Success: + console.log('Delete leaderboard success'); + break; + case LeaderboardDeleteResponse.Error: + console.log('Delete leaderboard error:', deleteResp.message()); + break; } } diff --git a/examples/nodejs/cache/sharded-dictionary.ts b/examples/nodejs/cache/sharded-dictionary.ts index 789907b9b..ac5b99aef 100644 --- a/examples/nodejs/cache/sharded-dictionary.ts +++ b/examples/nodejs/cache/sharded-dictionary.ts @@ -1,10 +1,10 @@ import { CacheClient, - CacheDelete, - CacheDictionaryFetch, - CacheDictionarySetField, + CacheDeleteResponse, + CacheDictionaryFetchResponse, + CacheDictionarySetFieldResponse, Configurations, - CreateCache, + CreateCacheResponse, CredentialProvider, DefaultMomentoLoggerFactory, DefaultMomentoLoggerLevel, @@ -87,10 +87,11 @@ class ShardedDictionary { field, value ); - if (dictionarySetFieldResponse instanceof CacheDictionarySetField.Success) { - return; - } else { - throw new Error(`Error setting field ${field} in individual dictionary ${individualDictionaryToUse}`); + switch (dictionarySetFieldResponse.type) { + case CacheDictionarySetFieldResponse.Success: + return; + case CacheDictionarySetFieldResponse.Error: + throw new Error(`Error setting field ${field} in individual dictionary ${individualDictionaryToUse}`); } } @@ -101,10 +102,12 @@ class ShardedDictionary { const responses = await Promise.all(individualDictionaryFetchPromises); const individualDictionaryContents = responses.map(response => { - if (response instanceof CacheDictionaryFetch.Hit) { - return response.value(); - } else { - throw new Error(`Error fetching individual dictionary: ${response.toString()}`); + switch (response.type) { + case CacheDictionaryFetchResponse.Hit: + return response.value(); + case CacheDictionaryFetchResponse.Error: + case CacheDictionaryFetchResponse.Miss: + throw new Error(`Error fetching individual dictionary: ${response.toString()}`); } }); return Object.assign({}, ...individualDictionaryContents) as Record; @@ -139,10 +142,15 @@ async function main() { }); const createCacheResponse = await cacheClient.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(); } const maxTotalDictionarySizeMb = 10; @@ -192,20 +200,26 @@ async function main() { `Using regular Momento client to fetch individual dictionary '${dictionaryName}' from sharded dictionary` ); const dictionaryContentsResponse = await cacheClient.dictionaryFetch(cacheName, dictionaryName); - if (dictionaryContentsResponse instanceof CacheDictionaryFetch.Hit) { - const dictionaryContents = dictionaryContentsResponse.value(); - const {numKeysRead, totalBytesRead} = analyzeDictionaryContents(logger, dictionaryContents); - logger.info(`Individual dictionary contained ${numKeysRead} keys and ${totalBytesRead} bytes`); - } else { - throw new Error(`Error fetching dictionary contents: ${dictionaryContentsResponse.toString()}`); + switch (dictionaryContentsResponse.type) { + case CacheDictionaryFetchResponse.Hit: { + const dictionaryContents = dictionaryContentsResponse.value(); + const {numKeysRead, totalBytesRead} = analyzeDictionaryContents(logger, dictionaryContents); + logger.info(`Individual dictionary contained ${numKeysRead} keys and ${totalBytesRead} bytes`); + break; + } + case CacheDictionaryFetchResponse.Error: + case CacheDictionaryFetchResponse.Miss: + throw new Error(`Error fetching dictionary contents: ${dictionaryContentsResponse.toString()}`); } const deleteDictionaryResponse = await cacheClient.delete(cacheName, dictionaryName); - if (deleteDictionaryResponse instanceof CacheDelete.Success) { - logger.info(`Deleted individual dictionary '${dictionaryName}'`); - } else { - throw new Error( - `Error deleting individual dictionary '${dictionaryName}': ${deleteDictionaryResponse.toString()}` - ); + switch (deleteDictionaryResponse.type) { + case CacheDeleteResponse.Success: + logger.info(`Deleted individual dictionary '${dictionaryName}'`); + break; + case CacheDeleteResponse.Error: + throw new Error( + `Error deleting individual dictionary '${dictionaryName}': ${deleteDictionaryResponse.toString()}` + ); } } }