メインコンテンツまでスキップ

Momento Cache API リファレンス

コントロールAPI

これらのAPIメソッドは、cacheを管理・制御するために使用されます。

Create cache

指定された名前のcacheを作成します。

属性:

名前説明
cacheNameString作成するcacheの名前。
const result = await cacheClient.createCache(cacheName);
switch (result.type) {
case CreateCacheResponse.AlreadyExists:
console.log(`Cache '${cacheName}' already exists`);
break;
case CreateCacheResponse.Success:
console.log(`Cache '${cacheName}' created`);
break;
case CreateCacheResponse.Error:
throw new Error(
`An error occurred while attempting to create cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Delete cache

cacheを削除します。

属性:

名前説明
cacheNameString削除するcacheの名前。
const result = await cacheClient.deleteCache(cacheName);
switch (result.type) {
case DeleteCacheResponse.Success:
console.log(`Cache '${cacheName}' deleted`);
break;
case DeleteCacheResponse.Error:
throw new Error(
`An error occurred while attempting to delete cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

List caches

すべてのcacheのリストを返します。

const result = await cacheClient.listCaches();
switch (result.type) {
case ListCachesResponse.Success:
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
break;
case ListCachesResponse.Error:
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}

Flush cache

cacheの全データをフラッシュします。

属性:

名前説明
cacheNameStringフラッシュするcacheの名前。
const result = await cacheClient.flushCache(cacheName);
switch (result.type) {
case FlushCacheResponse.Success:
console.log(`Cache '${cacheName}' flushed`);
break;
case FlushCacheResponse.Error:
throw new Error(
`An error occurred while attempting to flush cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

:::ヒント

Delete CacheCreate Cacheの順に使用することでこのプロセスを模倣できますが、FlushCache APIはcacheの設定を保持したまま、データのみを削除します。

:::

データAPI

これらのAPIメソッドは、cache内のデータを直接操作するために使用されます。

Set

指定された生存時間(TTL)秒の値をcacheに設定します。このkeyの値がすでに存在する場合は、前の値のデータタイプが何であれ、新しい値で置き換えられます。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を追加するkey。
value[]Byte格納される値。
ttlSecondsintcache内のアイテムのTTL。
const result = await cacheClient.set(cacheName, 'test-key', 'test-value');
switch (result.type) {
case CacheSetResponse.Success:
console.log("Key 'test-key' stored successfully");
break;
case CacheSetResponse.Error:
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetBatch

複数のキーと値のペアを、指定されたTTL(Time To Live)秒数でキャッシュに設定します。キーの値がすでに存在する場合は、前の値のデータタイプが何であれ、新しい値に置き換えられます。

NameTypeDescription
cacheNameStringキャッシュの名前
items{ String/[]Byte : String/[]Byte }格納されるべきキーと値のマッピング
ttlSecondsintキャッシュにあるアイテムのために生きる時間
const values = new Map<string, string>([
['abc', '123'],
['xyz', '321'],
['123', 'xyz'],
['321', 'abc'],
]);
const result = await cacheClient.setBatch(cacheName, values);
switch (result.type) {
case CacheSetBatchResponse.Success:
console.log('Keys and values stored successfully');
break;
case CacheSetBatchResponse.Error:
throw new Error(
`An error occurred while attempting to batch set in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
メソッド・レスポンス・オブジェクト
  • Success
  • results(): CacheSet.Response[]
  • Error

Get

指定されたkeyに対して格納されているcache値を取得します。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を取得するために指定するkeyです。
const getResponse = await cacheClient.get(cacheName, 'test-key');
// simplified style; assume the value was found
console.log(`cache hit: ${getResponse.value()!}`);

// pattern-matching style; safer for production code
switch (getResponse.type) {
case CacheGetResponse.Hit:
console.log(`Retrieved value for key 'test-key': ${getResponse.valueString()}`);
break;
case CacheGetResponse.Miss:
console.log(`Key 'test-key' was not found in cache '${cacheName}'`);
break;
case CacheGetResponse.Error:
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${getResponse.errorCode()}: ${getResponse.toString()}`
);
}

GetBatch

指定したキーに対応するキャッシュ値を取得します。

NameTypeDescription
cacheNameStringキャッシュの名前
keysString[] / Bytes[]値を取得するキーのリスト
const keys = ['abc', 'xyz', '123', '321'];
const getBatchResponse = await cacheClient.getBatch(cacheName, keys);

// simplified style; assume the value was found
const values = getBatchResponse.values()!;
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}

// pattern-matching style; safer for production code
switch (getBatchResponse.type) {
case CacheGetBatchResponse.Success: {
const values = getBatchResponse.values();
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}
break;
}
case CacheGetBatchResponse.Error:
throw new Error(
`An error occurred while attempting to batch get in cache '${cacheName}': ${getBatchResponse.errorCode()}: ${getBatchResponse.toString()}`
);
}
メソッド・レスポンス・オブジェクト
  • Success
  • values(): Record<string, string>
  • results(): CacheGet.Response[]
  • Error

Delete

与えられたkeyに対して格納されているcache値を削除します。

名前説明
cacheNameStringcacheの名前。
key[]Byte値を削除するために指定するkey。
const result = await cacheClient.delete(cacheName, 'test-key');
switch (result.type) {
case CacheDeleteResponse.Success:
console.log("Key 'test-key' deleted successfully");
break;
case CacheDeleteResponse.Error:
throw new Error(
`An error occurred while attempting to delete key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Increment

既存の値がベース10(10進法)の整数を表すUTF-8文字列である場合に限り、フィールドの値を追加 します。もしフィールドが存在しない場合、このメソッドはフィールドの値をインクリメントして設定しま す。

名前説明
cacheNameStringcacheの名前。
fieldString値のインクリメントする場合の対象となるkey。
amountInteger値に加算する量です。正の値、負の値、またはゼロを指定します。デフォルトは1。

:::注記

インクリメントされた値は、-9223372036854775808から9223372036854775807の間、つまり64ビッ ト符号付き整数配列でなければなりません。そうでない場合は、エラーが返されます。

:::

await cacheClient.set(cacheName, 'test-key', '10');
const result = await cacheClient.increment(cacheName, 'test-key', 1);
switch (result.type) {
case CacheIncrementResponse.Success:
console.log(`Key 'test-key' incremented successfully. New value in key test-key: ${result.valueNumber()}`);
break;
case CacheIncrementResponse.Error:
throw new Error(
`An error occurred while attempting to increment the value of key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Ping

サーバにpingを送信します。このAPIは、クライアントがサーバに正常に接続できることを確認するた めの接続性のチェックに使用できます。

メソッドのレスポンスオブジェクト
  • Success
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

ItemGetType

与えられたkeyに対して、対応するアイテムが存在する場合、その型(SCALAR、DICTIONARY、LISTな ど)を返します。

名前説明
cacheNameStringcacheの名前。
keyString | Byteitemの型が返却されるべきkey。
メソッドのレスポンスオブジェクト
  • Cache hit
  • 型(): enum: SCALAR, DICTIONARY, SET, LIST, SORTED_SET
  • Cache miss
  • Cache error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.itemGetType(cacheName, 'test-key');
switch (result.type) {
case CacheItemGetTypeResponse.Hit:
console.log(`Item type retrieved successfully: ${ItemType[result.itemType()]}`);
break;
case CacheItemGetTypeResponse.Miss:
console.log("Key 'test-key' was not found in cache '${cacheName}'");
break;
case CacheItemGetTypeResponse.Error:
throw new Error(
`An error occurred while attempting to get the type of key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeyExists

指定されたkeyがcacheに存在するかどうかをチェックします。

名前説明
cacheNameStringcacheの名前。
keyString | Bytecacheに存在するかどうかをチェックするkey。
メソッドのレスポンスオブジェクト
  • Success
  • exists(): Bool
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.keyExists(cacheName, 'test-key');
switch (result.type) {
case CacheKeyExistsResponse.Success:
console.log("Does 'test-key' exist in the cache?", result.exists());
break;
case CacheKeyExistsResponse.Error:
throw new Error(
`An error occurred while attempting to call keyExists on key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeysExist

指定されたkey(複数)がcacheに存在するかどうかをチェックします。

名前説明
cacheNameStringcacheの名前。
keysString[] | Byte[]cacheに存在するかどうかをチェックするkey(複数)。
メソッドのレスポンスオブジェクト
  • Success
  • exists(): Bool[]
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const result = await cacheClient.keysExist(cacheName, ['test-key1', 'test-key2']);
switch (result.type) {
case CacheKeysExistResponse.Success:
console.log("Do 'test-key1' and 'test-key2' exist in the cache?", result.exists());
break;
case CacheKeysExistResponse.Error:
throw new Error(
`An error occurred while attempting to call keysExist on keys 'test-key1' and 'test-key2' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetIfAbsent

警告

SetIfPresentのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そうすると、一貫性の動作が定義されません。代わりにSetIfAbsentSetIfPresent` と一緒に使用してください。

キーがキャッシュにまだ存在しない場合は、指定されたキーを使用して、指定された値をキャッシュ項目に関連付けます。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfAbsent(cacheName, 'test-key', 'test-field');
switch (result.type) {
case CacheSetIfAbsentResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfAbsentResponse.NotStored:
console.log(`Key 'test-key' already exists in cache ${cacheName}, so we did not overwrite it`);
break;
case CacheSetIfAbsentResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfAbsent for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfPresent

警告

SetIfPresentのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そうすると、一貫性の動作が定義されません。代わりにSetIfAbsentSetIfPresent` と一緒に使用してください。

指定されたキーが既にキャッシュに存在する場合は、指定された値を指定されたキーのキャッシュ項目に関連付けます。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfPresent(cacheName, 'test-key', 'test-field');
switch (result.type) {
case CacheSetIfPresentResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfPresentResponse.NotStored:
console.log(`Key 'test-key' does not exist in cache ${cacheName}, so we did not set the field`);
break;
case CacheSetIfPresentResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfPresent for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfEqual

警告

SetIfEqualのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そうすると、一貫性のない動作になります。代わりにSetIfNotEqualSetIfEqual` と一緒に使用してください。

指定されたキーが既にキャッシュ内に存在し、キャッシュ内の値が equal で指定された値と等しい場合に、指定された値を指定されたキーのキャッシュアイテムに関連付ける。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
equalString | Bytes比較する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfEqualResponse.NotStored:
console.log("Value of key 'test-key' does not equal 'value-to-check', so we did not set the field");
break;
case CacheSetIfEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfNotEqual

警告

SetIfEqualのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そうすると、一貫性のない動作になります。代わりにSetIfNotEqualSetIfEqual` と一緒に使用してください。

指定したキーがキャッシュ内に存在しないか、キャッシュ内の値が notEqual で指定した値と等しくない場合に、指定した値を指定したキーのキャッシュアイテムに関連付ける。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
notEqualString | Bytes比較する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfNotEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfNotEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfNotEqualResponse.NotStored:
console.log("Value of key 'test-key' equals 'value-to-check', so we did not set the field");
break;
case CacheSetIfNotEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfNotEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfPresentAndNotEqual

SetIfPresentAndNotEqualのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そのようなことをすると、一貫性の動作が未定義になります。代わりにSetIfAbsentOrEqual SetIfPresentAndNotEqual` を使用してください。 :::

指定されたキーが既にキャッシュ内に存在し、キャッシュ内の値が notEqual で指定された値と等しくない場合に、指定された値を指定されたキーのキャッシュアイテムに関連付ける。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
notEqualString | Bytes比較する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfPresentAndNotEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfPresentAndNotEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfPresentAndNotEqualResponse.NotStored:
console.log(
`Key 'test-key' does not exist in cache ${cacheName} or equals 'value-to-check', so we did not set the field`
);
break;
case CacheSetIfPresentAndNotEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfPresentAndNotEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfAbsentOrEqual

::警告 SetIfAbsentOrEqualのようなチェックアンドセット (CAS) API をSetDeleteのようなスカラー API や非 CAS API と一緒に使用しないでください。そのようなことをすると、一貫性の動作が未定義になります。代わりにSetIfAbsentOrEqual と一緒SetIfPresentAndNotEqual` を使用してください。 :::

指定したキーがキャッシュ内に存在しないか、キャッシュ内の値が equal で指定した値と等しい場合に、指定した値を指定したキーのキャッシュアイテムに関連付ける。

NameTypeDescription
cacheNameStringキャッシュの名前
keyString | Bytes設定されるキー
valueString | Bytes保存する値
equalString | Bytes比較する値
ttlSecondsDurationキャッシュ内のアイテムの生存時間
Method response object
  • Stored
  • NotStored
  • Error

詳しくはレスポンスオブジェクトを参照。

const result = await cacheClient.setIfAbsentOrEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfAbsentOrEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfAbsentOrEqualResponse.NotStored:
console.log(
`Key 'test-key' exists in cache ${cacheName} and is not equal to 'value-to-check', so we did not set the field`
);
break;
case CacheSetIfAbsentOrEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfAbsentOrEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

生存時間(TTL)API

これらのAPIは、すべての型のcacheに適用されます。

UpdateTtl

cacheアイテムのTTLを、指定された値(秒)で上書きします。

名前説明
cacheNameStringcacheの名前。
keyString | Bytes値のTTLを上書きする対象のkey。
ttlDurationcacheで上書きしたいTTLを秒単位で指定します。
resp, err := client.UpdateTtl(ctx, &momento.UpdateTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.UpdateTtlSet:
log.Printf("Successfully updated TTL for key\n")
case *responses.UpdateTtlMiss:
log.Printf("Key does not exist in cache\n")
}

IncreaseTtl

TTLを増加させる場合のみ、keyのTTL秒数を指定された値に増やします。

  • TTLが5秒で、6秒を指定した場合、新しいTTLは6秒になります。
  • TTLが5秒で、3秒を指定した場合、TTLは増加しません。 | 名前 | 型 | 説明 | | --------- | ------ | ----------------------------------------------- | | cacheName | String | cacheの名前。 | | | key | String | Bytes | 値のTTLを増加させるkeyの指定。 | | ttl | Duration | 増加したいTTLを秒単位で指定します。 |
resp, err := client.IncreaseTtl(ctx, &momento.IncreaseTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.IncreaseTtlSet:
log.Printf("Successfully increased TTL for key\n")
case *responses.IncreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

DecreaseTtl

TTLを減少させる場合のみ、keyのTTL秒数を指定された値に減らします。

  • TTLが5秒で、3秒を指定した場合、新しいTTLは3秒になります。
  • TTLが5秒で、6秒を指定した場合、TTLは減少しません。
名前説明
cacheNameStringcacheの名前。
keyString | Bytes値のTTLを減少させるkeyの指定。
ttlDuration減少させたいTTLを秒単位で指定します。
resp, err := client.DecreaseTtl(ctx, &momento.DecreaseTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.DecreaseTtlSet:
log.Printf("Successfully decreased TTL for key\n")
case *responses.DecreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

ItemGetTtl

与えられたkeyに対して、そのアイテムがcacheから失効するまでの生存時間(TTL)を返します。

名前説明
cacheNameStringcacheの名前。
keyString | Byteアイテムの型を返すkeyの指定。
メソッドのレスポンスオブジェクト
  • Cache hit
  • remainingTtl(): Duration
  • Cache miss
  • Cache error

具体的な情報については、レスポンスオブジェクトを参照してください。

resp, err := client.ItemGetTtl(ctx, &momento.ItemGetTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *responses.ItemGetTtlHit:
log.Printf("TTL for key is %d\n", r.RemainingTtl().Milliseconds())
case *responses.ItemGetTtlMiss:
log.Printf("Key does not exist in cache\n")
}

認証API

これらのAPIは、Momentoの認証トークンやアクセスを管理するために使用されます。

GenerateApiKey

指定した権限と有効期限を持つ新しいMomento認証トークンを生成します。

名前説明
scopePermissionScope新しいトークンに付与する権限です。あらかじめ構築されたTokenScope オブジェクトは、SDKによって提供されます。
expiresInExpiresInトークンが期限切れになるまでの秒数、またはneverの指定。
メソッドのレスポンスオブジェクト
  • Success
  • authToken: string - the new auth token
  • refreshToken: string - a refresh token that can be used with the RefreshApiKey API to refresh the token before it expires
  • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

// Generate a token that allows all data plane APIs on all caches and topics.
const allDataRWTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));
switch (allDataRWTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with AllDataReadWrite scope!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allDataRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${allDataRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${allDataRWTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with AllDataReadWrite scope: ${allDataRWTokenResponse.errorCode()}: ${allDataRWTokenResponse.toString()}`
);
}

// Generate a token that can only call read-only data plane APIs on a specific cache foo. No topic apis (publish/subscribe) are allowed.
const singleCacheROTokenResponse = await authClient.generateApiKey(
TokenScopes.cacheReadOnly('foo'),
ExpiresIn.minutes(30)
);
switch (singleCacheROTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with read-only access to cache foo!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${singleCacheROTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${singleCacheROTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${singleCacheROTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with single cache read-only scope: ${singleCacheROTokenResponse.errorCode()}: ${singleCacheROTokenResponse.toString()}`
);
}

// Generate a token that can call all data plane APIs on all caches. No topic apis (publish/subscribe) are allowed.
const allCachesRWTokenResponse = await authClient.generateApiKey(
TokenScopes.cacheReadWrite(AllCaches),
ExpiresIn.minutes(30)
);
switch (allCachesRWTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with read-write access to all caches!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allCachesRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${allCachesRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${allCachesRWTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with all caches read-write scope: ${allCachesRWTokenResponse.errorCode()}: ${allCachesRWTokenResponse.toString()}`
);
}

// Generate a token that can call publish and subscribe on all topics within cache bar
const singleCacheAllTopicsRWTokenResponse = await authClient.generateApiKey(
TokenScopes.topicPublishSubscribe({name: 'bar'}, AllTopics),
ExpiresIn.minutes(30)
);
switch (singleCacheAllTopicsRWTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with publish-subscribe access to all topics within cache bar!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${singleCacheAllTopicsRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${singleCacheAllTopicsRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${singleCacheAllTopicsRWTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with read-write scope for all topics in a single cache: ${singleCacheAllTopicsRWTokenResponse.errorCode()}: ${singleCacheAllTopicsRWTokenResponse.toString()}`
);
}

// Generate a token that can only call subscribe on topic where_is_mo within cache mo_nuts
const oneCacheOneTopicRWTokenResponse = await authClient.generateApiKey(
TokenScopes.topicSubscribeOnly('mo_nuts', 'where_is_mo'),
ExpiresIn.minutes(30)
);
switch (oneCacheOneTopicRWTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with subscribe-only access to topic where_is_mo within cache mo_nuts!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneCacheOneTopicRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${oneCacheOneTopicRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${oneCacheOneTopicRWTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with read-write scope for single topic in a single cache: ${oneCacheOneTopicRWTokenResponse.errorCode()}: ${oneCacheOneTopicRWTokenResponse.toString()}`
);
}

// Generate a token with multiple permissions
const cachePermission1 = {
role: CacheRole.ReadWrite, // Managed role that grants access to read as well as write apis on caches
cache: 'acorns', // Scopes the access to a single cache named 'acorns'
};
const cachePermission2 = {
role: CacheRole.ReadOnly, // Managed role that grants access to only read data apis on caches
cache: AllCaches, // Built-in value for access to all caches in the account
};
const topicPermission1 = {
role: TopicRole.PublishSubscribe, // Managed role that grants access to subscribe as well as publish apis
cache: 'walnuts', // Scopes the access to a single cache named 'walnuts'
topic: 'mo_favorites', // Scopes the access to a single topic named 'mo_favorites' within cache 'walnuts'
};
const topicPermission2 = {
role: TopicRole.SubscribeOnly, // Managed role that grants access to only subscribe api
cache: AllCaches, // Built-in value for all cache(s) in the account.
topic: AllTopics, // Built-in value for access to all topics in the listed cache(s).
};

const permissions = {
permissions: [cachePermission1, cachePermission2, topicPermission1, topicPermission2],
};

const multiplePermsTokenResponse = await authClient.generateApiKey(permissions, ExpiresIn.minutes(30));
switch (multiplePermsTokenResponse.type) {
case GenerateApiKeyResponse.Success:
console.log('Generated an API key with multiple cache and topic permissions!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${multiplePermsTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${multiplePermsTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${multiplePermsTokenResponse.expiresAt.epoch()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with multiple permissions: ${multiplePermsTokenResponse.errorCode()}: ${multiplePermsTokenResponse.toString()}`
);
}

RefreshApiKey

既存の有効期限内のMomento認証トークンを更新します。元のトークンと同じ権限と有効期限を持つ 新しいトークンを生成します。

名前説明
refreshTokenString最初のGenerateApiKeyの呼び出しから取得した、現在の認証トー クンのrefreshTokenを指定。
メソッドのレスポンスオブジェクト
  • Success
  • authToken: string - the new auth token
  • refreshToken: string - a refresh token that can be used with the RefreshApiKey API to refresh the token before it expires
  • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

具体的な情報については、レスポンスオブジェクトを参照してください。

const generateTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));

let successResponse: GenerateApiKey.Success;
switch (generateTokenResponse.type) {
case GenerateApiKeyResponse.Success: {
successResponse = generateTokenResponse;
break;
}
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey: ${generateTokenResponse.errorCode()}: ${generateTokenResponse.toString()}`
);
}

console.log('Generated API key; refreshing!');
const refreshAuthClient = new AuthClient({
credentialProvider: CredentialProvider.fromString({apiKey: successResponse.apiKey}),
});
const refreshTokenResponse = await refreshAuthClient.refreshApiKey(successResponse.refreshToken);
switch (refreshTokenResponse.type) {
case RefreshApiKeyResponse.Success:
console.log('API key refreshed!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`Refreshed API key starts with: ${refreshTokenResponse.apiKey.substring(0, 10)}`);
console.log(`New refresh token starts with: ${refreshTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Refreshed API key expires At: ${refreshTokenResponse.expiresAt.epoch()}`);
break;
case RefreshApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call refreshApiKey: ${refreshTokenResponse.errorCode()}: ${refreshTokenResponse.toString()}`
);
}

コレクションデータ型

コレクション型は、ユースケースに応じて、さまざまなタイプの構造を含むことができます。サポートされ ているデータ型は以下の通りです:

  • Dictionaries(辞書型)は、順序のないフィールドと値のペアを格納するために使用されます。
  • Lists(リスト型)は、順序付けられた要素のコレクションで、各要素が挿入された順序でソートされています。
  • Sets(セット型)は、ユニークな要素の文字列による、順序のないコレクションです。
  • Sorted Sets(ソート済みセット型) は、ユニークな要素の順序付きコレクションです。各要素 は、値:スコアのペアを含んでいます。

利用方法についての詳しい情報は、コレクションデータ型をご覧ください。