Skip to content

Commit

Permalink
chore: more work on porting examples to new switch pattern (#1416)
Browse files Browse the repository at this point in the history
* chore: more work on porting examples to new switch pattern
  • Loading branch information
cprice404 authored Aug 21, 2024
1 parent ef7018d commit 7940999
Show file tree
Hide file tree
Showing 4 changed files with 192 additions and 123 deletions.
29 changes: 17 additions & 12 deletions examples/nodejs/cache/batchutils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {
CacheDelete,
CacheGet,
CacheSet,
BatchUtils,
CacheClient,
CacheDeleteResponse,
CacheGetResponse,
CacheSetResponse,
Configurations,
CreateCacheResponse,
CredentialProvider,
CreateCache,
BatchUtils,
} from '@gomomento/sdk';

const cacheName = 'cache';
Expand All @@ -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<BatchUtils.BatchSetItem> = [
Expand All @@ -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)}`);
}
}

Expand Down
102 changes: 61 additions & 41 deletions examples/nodejs/cache/dictionary.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
};

Expand Down
114 changes: 72 additions & 42 deletions examples/nodejs/cache/leaderboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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({
Expand All @@ -47,22 +52,29 @@ 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
const elements2: Record<number, number> = {
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.
Expand All @@ -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
Expand All @@ -86,48 +101,63 @@ 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;
}
}

// Get rank fetches elements given a list of element IDs.
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;
}
}

Expand Down
Loading

0 comments on commit 7940999

Please sign in to comment.