Momento Cache Data APIs
API reference for Momento Cache (Data APIs)
API reference for Momento Cacheに掲載されている
Data APIsに関するメモです。
Momento CacheのAPIには種類がある
Momento CacheのAPIには主に3種類のAPIが存在します。
- Control
- Data
- Time to Live
他にも認証用のAPIや特定のデータ型を操作するAPIがあります。
今回は基本となるData APIsについて解説します。
Data APIsでは何ができるのか
主にMomento上にあるキャッシュデータを操作できます。すでに作成されているキャッシュに対して有効です。
メソッド | 操作内容 |
---|---|
Set | Momento Cache上にあるキャッシュにデータをセットする |
Get | Momento Cache上にあるキャッシュから指定されたデータを取得する |
Delete | Momento Cache上にあるキャッシュからKeyで指定されたデータを削除する |
Increment | Momento Cache上にキャッシュされた数値データに任意の数値を加算する(デフォルトは1) |
Ping | Momento Cacheとの疎通確認 |
ItemGetType | Momento Cache上のキャッシュからデータ型を取り出す |
KeyExists | Momento Cache上に指定されたキーがキャッシュに存在するかどうかをチェックする |
KeysExist | Momento Cache上に指定されたキーがキャッシュに存在するかどうかをチェックする |
SetIfNotExists | 指定された値を、指定されたキーを持つキャッシュ項目に関連付けます |
Set
Momento Cache上にあるキャッシュにデータをセットします。キャッシュ先がない場合はエラーが発生します。
import { CacheClient, CreateCache, CacheSet, Configurations, CredentialProvider } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log("Cache 'test-cache' created");
} else if (result instanceof CreateCache.AlreadyExists) {
console.log("Cache 'test-cache' already exists");
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_set_data(cache_client, cache_name, key_name, key_value) {
const result = await cache_client.set(cache_name, key_name, key_value);
if (result instanceof CacheSet.Success) {
console.log(`Key ${key_name} stored successfully`);
} else if (result instanceof CacheSet.Error) {
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const key_value = 'test-data';
momento_create_cache(cache_name, cache_client);
momento_set_data(cache_client, cache_name, key_name, key_value);
}
main();
Get
Momento Cache上にあるキャッシュから指定されたデータを取得します。
取得元のキャッシュが存在しない場合はエラーが発生します。
import { CacheClient, CreateCache, CacheSet, CacheGet, Configurations, CredentialProvider } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_set_data(cache_client, cache_name, key_name, key_value) {
const result = await cache_client.set(cache_name, key_name, key_value);
if (result instanceof CacheSet.Success) {
console.log(`Key ${key_name} stored successfully`);
} else if (result instanceof CacheSet.Error) {
throw new Error(
`An error occurred while attempting to store key ${key_name} in cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_get_data(cache_client, cache_name, key_name) {
const result = await cache_client.get(cache_name, key_name);
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key ${key_name}: ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log(`Key ${key_name} was not found in cache ${cache_name}`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const key_value = 'test-data';
momento_create_cache(cache_name, cache_client);
momento_set_data(cache_client, cache_name, key_name, key_value);
momento_get_data(cache_client, cache_name, key_name);
}
main();
Delete
Momento Cache上にあるキャッシュからKeyで指定されたデータを削除します。
import { CacheClient, CreateCache, CacheSet, CacheGet, CacheDelete, Configurations, CredentialProvider } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_set_data(cache_client, cache_name, key_name, key_value) {
const result = await cache_client.set(cache_name, key_name, key_value);
if (result instanceof CacheSet.Success) {
console.log(`Key ${key_name} stored successfully`);
} else if (result instanceof CacheSet.Error) {
throw new Error(
`An error occurred while attempting to store key ${key_name} in cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_get_data(cache_client, cache_name, key_name) {
const result = await cache_client.get(cache_name, key_name);
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key ${key_name}: ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log(`Key ${key_name} was not found in cache ${cache_name}`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_delete_data(cache_client, cache_name, key_name) {
const result = await cache_client.delete(cache_name, key_name);
if (result instanceof CacheDelete.Success) {
console.log(`Key ${key_name} deleted successfully`);
} else if (result instanceof CacheDelete.Error) {
throw new Error(
`An error occurred while attempting to delete key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const key_value = 'test-data';
momento_create_cache(cache_name, cache_client);
momento_set_data(cache_client, cache_name, key_name, key_value);
momento_get_data(cache_client, cache_name, key_name);
momento_delete_data(cache_client, cache_name, key_name)
momento_get_data(cache_client, cache_name, key_name);
}
main();
Increment
Momento Cache上にキャッシュされた数値データに任意の数値を加算します。(デフォルトは1)
既存の値がベース10(10進法)の整数を表すUTF-8文字列である場合に限り、フィールドの値を追加します。
注意点:既存の値は文字としてキャッシュにセットします。たとえば、「10」ではなく「'10'」としてキャッシュします。
また、インクリメントの数値は64ビット符号付き整数(-9223372036854775808から9223372036854775807の間)でなければいけません。
対象のキーが存在しない状態でIncrement
を実行すると加算値がそのままキャッシュされます。
import { CacheClient, CreateCache, CacheGet, CacheIncrement, Configurations, CredentialProvider } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_get_data(cache_client, cache_name, key_name) {
const result = await cache_client.get(cache_name, key_name);
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key ${key_name}: ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log(`Key ${key_name} was not found in cache ${cache_name}`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_increment_value(cache_client, cache_name, key_name, num, amount) {
await cache_client.set(cache_name, key_name, num);
const result = await cache_client.increment(cache_name, key_name, amount);
if (result instanceof CacheIncrement.Success) {
console.log(`Key ${key_name} incremented successfully. New value in key ${key_name}: ${result.valueNumber()}`);
} else if (result instanceof CacheIncrement.Error) {
throw new Error(
`An error occurred while attempting to increment the value of key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_increment_value_noset(cache_client, cache_name, key_name, amount) {
const result = await cache_client.increment(cache_name, key_name, amount);
if (result instanceof CacheIncrement.Success) {
console.log(`Key ${key_name} incremented successfully. New value in key ${key_name}: ${result.valueNumber()}`);
} else if (result instanceof CacheIncrement.Error) {
throw new Error(
`An error occurred while attempting to increment the value of key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const num = '1';
const amount = 2
momento_create_cache(cache_name, cache_client);
momento_increment_value(cache_client, cache_name, key_name, num, amount);
const key_name2 = 'none-key'
momento_increment_value_noset(cache_client, cache_name, key_name2, amount);
momento_get_data(cache_client, cache_name, key_name2);
}
main();
Ping
Node.jsのMomento SDKでは対応していないため、Web SDKを利用してください。
import { Configurations, CredentialProvider, CacheClient } from '@gomomento/sdk-web';
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
cache_client.ping();
}
main();
ItemGetType
与えられたキーに対して、対応する項目が存在すればその型(SCALAR、DICTIONARY、LISTなど)を返します。
import { CacheClient, CredentialProvider, CreateCache, CacheIncrement, Configurations, CacheItemGetType, ItemType } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_increment_value(cache_client, cache_name, key_name, num, amount) {
await cache_client.set(cache_name, key_name, num);
const result = await cache_client.increment(cache_name, key_name, amount);
if (result instanceof CacheIncrement.Success) {
console.log(`Key ${key_name} incremented successfully. New value in key ${key_name}: ${result.valueNumber()}`);
} else if (result instanceof CacheIncrement.Error) {
throw new Error(
`An error occurred while attempting to increment the value of key ${key_name} from cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_item_get_type(cache_client, cache_name, key_name) {
const result = await cache_client.itemGetType(cache_name, key_name);
if (result instanceof CacheItemGetType.Hit) {
console.log(`Item type retrieved successfully: ${ItemType[result.itemType()]}`);
} else if (result instanceof CacheItemGetType.Miss) {
console.log(`Key ${key_name} was not found in cache cache_name`);
} else if (result instanceof CacheItemGetType.Error) {
throw new Error(
`An error occurred while attempting to get the type of key ${key_name} from cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const num = '1';
const amount = 2
momento_create_cache(cache_name, cache_client);
momento_increment_value(cache_client, cache_name, key_name, num, amount);
momento_item_get_type(cache_client, cache_name, key_name);
}
main();
KeyExists
指定されたキーがMomento上の指定されたキャッシュに存在するかをチェックします。
指定するキーは単一である必要があります。
import { CacheClient, CredentialProvider, CreateCache, Configurations, CacheKeyExists } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_key_exists(cache_client, cache_name, key_name) {
const result = await cache_client.keyExists(cache_name, key_name);
if (result instanceof CacheKeyExists.Success) {
console.log('momento_key_exists CacheKeyExists');
} else if (result instanceof CacheKeyExists.Error) {
throw new Error(
`An error occurred while attempting to get the type of key ${key_name} from cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
momento_create_cache(cache_name, cache_client);
momento_key_exists(cache_client, cache_name, key_name);
}
main();
KeysExist
指定されたキーがMomento上の指定されたキャッシュに存在するかをチェックします。
指定するキーは複数(配列)である必要があります。
import { CacheClient, CredentialProvider, CreateCache, Configurations, CacheKeysExist } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_keys_exist(cache_client, cache_name, key_names) {
const result = await cache_client.keysExist(cache_name, key_names);
if (result instanceof CacheKeysExist.Success) {
console.log('momento_keys_exist CacheKeysExists!');
} else if (result instanceof CacheKeysExist.Error) {
throw new Error(
`An error occurred while attempting to get the type of key ${key_names} from cache cache_name: ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const key_names = ['test-key', 'sample-key'];
momento_create_cache(cache_name, cache_client);
momento_keys_exist(cache_client, cache_name, key_names);
}
main();
補足:KeyExistsとKeysExistの違い
指定するキーが文字列か配列か以外にも違いがあります。詳しくは実装をみてみましょう。
SetIfNotExists
指定された値を、指定されたキーを持つMomento上のキャッシュに関連付けます。
キャッシュが持つ特定のKeyに値を関連付けます。
import { CacheClient, CredentialProvider, CreateCache, Configurations, CacheSetIfNotExists } from '@gomomento/sdk';
async function momento_create_cache(cache_name, cache_client) {
const result = await cache_client.createCache(cache_name);
if (result instanceof CreateCache.Success) {
console.log(`Cache ${cache_name} created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache ${cache_name} already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache ${cache_name}: ${result.errorCode()}: ${result.toString()}`
);
}
}
async function momento_setif_not_exists(cache_client, cache_name, key_name, field_name) {
const result = await cache_client.setIfNotExists(cache_name, key_name, field_name);
if (result instanceof CacheSetIfNotExists.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfNotExists.NotStored) {
console.log("Key 'test-key' already exists in cache 'test-cache', so we did not overwrite it");
} else if (result instanceof CacheSetIfNotExists.Error) {
throw new Error(
`An error occurred while attempting to call setIfNotExists for the key 'test-key' in cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
}
export default function main() {
const cache_client = new CacheClient({
configuration: Configurations.Laptop.v1(),
defaultTtlSeconds: 60,
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
const cache_name = 'test-cache';
const key_name = 'test-key';
const field_name = 'field-name';
momento_create_cache(cache_name, cache_client);
momento_setif_not_exists(cache_client, cache_name, key_name, field_name);
}
main();
Discussion