LoginSignup
3
7

More than 5 years have passed since last update.

GoogleAppsScriptのCacheService.getUserCache()の"User"

Last updated at Posted at 2018-07-14

GoogleAppsScriptで予約を行うLINE BOTを作っている。

予約時刻などのユーザの入力情報を一時的に保持するためにGASのCacheServiceを使っているのだが、複数のユーザーがこの予約BOTを使っていると、タイミングによっては、それぞれユーザーの入力情報がごっちゃになって訳わからんことになるという問題が発生した。

CacheServiceのドキュメントの下記の部分を読んで、getUserCache()を使えばOKだと思っていたのだけど、よく考えると、the current userって、BOTを使っているLINEの個別ユーザーじゃなくて、LINE APIサーバー自体のことだな、と気づく。

getDocumentCache() Cache Gets the cache instance scoped to the current document and script.
getScriptCache() Cache Gets the cache instance scoped to the script.
getUserCache() Cache Gets the cache instance scoped to the current user and script.

(https://developers.google.com/apps-script/reference/cache/)

そこで、
下記のような関数を作って、GAS内部で処理をするようにしたら、
複数人同時に処理をしても問題なくなった。

// 指定したユーザーIDとキーに対する値を返す
// 
// 指定したkeyに対するvalueがないと null が返ってくる
function cacheGet(keyStr, cache, userId){
  var value;
  var key = keyStr + "-" + userId;
  value = cache.get(key);
  return value;
}

// 指定したユーザーID&キーに対して指定した値を入れる
// 
function cachePut(keyStr, valueStr, cache, userId){
  var key = keyStr + "-" + userId;
  cache.put(key, valueStr);
}

// 指定したユーザーID&キーに対する値を削除する
// 
function cacheRemove(keyStr, cache, userId){
  var key = keyStr + "-" + userId;
  cache.remove(key);
}

めでたしめでたし。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7