Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: working through more instanceof->switch examples #1417

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 49 additions & 31 deletions examples/nodejs/cache/advanced.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import {
CacheGet,
ListCaches,
CreateCache,
CacheSet,
CacheDelete,
CacheClient,
Configurations,
MomentoLoggerFactory,
DefaultMomentoLoggerFactory,
DefaultMomentoLoggerLevel,
CredentialProvider,
MiddlewareFactory,
CreateCacheResponse,
ListCachesResponse,
CacheSetResponse,
CacheGetResponse,
CacheDeleteResponse,
} from '@gomomento/sdk';
import {range} from './utils/collections';
import * as fs from 'fs';
Expand Down Expand Up @@ -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;
}
}

Expand All @@ -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;
}
}

Expand All @@ -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()}`);
Expand Down
4 changes: 2 additions & 2 deletions examples/nodejs/cache/readme.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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()}`);
}
}
Expand Down
63 changes: 40 additions & 23 deletions examples/nodejs/compression-zstd/compression.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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.
Expand All @@ -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;
}
}

Expand Down
19 changes: 10 additions & 9 deletions examples/nodejs/get-set-batch-perf-test/perf-test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import {
CacheClient,
CacheGetBatch,
CacheGet,
CacheGetBatchResponse,
CacheGetResponse,
CacheSet,
CacheSetBatch,
CacheSetBatchResponse,
CacheSetResponse,
DefaultMomentoLoggerFactory,
DefaultMomentoLoggerLevel,
MomentoLogger,
Expand Down Expand Up @@ -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()}`);
}
Expand All @@ -249,7 +252,7 @@ class PerfTest {
context: PerfTestContext,
getConfig: GetSetConfig
): Promise<void> {
const getPromises: Promise<CacheSet.Response>[] = [];
const getPromises: Promise<CacheGet.Response>[] = [];
const getStartTime = process.hrtime();
for (let i = 0; i < getConfig.batchSize; i++) {
const key = `key-${i}`;
Expand All @@ -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()}`);
}
Expand All @@ -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);
Expand All @@ -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);
Expand Down
27 changes: 17 additions & 10 deletions examples/nodejs/get-set-batch-perf-test/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
CacheClient,
Configurations,
CreateCache,
EnvMomentoTokenProvider,
MomentoLogger,
MomentoLoggerFactory,
CacheFlush,
CreateCacheResponse,
FlushCacheResponse,
} from '@gomomento/sdk';

export function getCacheClient(
Expand Down Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -17,26 +17,31 @@ export class ReadAsideWrapper {

public async getItem(keyToGet: string): Promise<string> {
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);
// if the handler comes back with other than null, try to insert into a Momento cache. If null, error.
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);
Expand Down
Loading
Loading