2009年6月20日土曜日

情報の永続化 Persistence API サンプル

通常、アプリケーションで何か情報を保持するためには、MySQL等のデータベースを用意して保存させる必要があるが、OpenSocialにはデータの永続化のためのPersistence APIというものがある。Persistence APIにできることは、

  • ある情報に名前を付けて永続化する
  • 永続化されている情報を取り出す
  • 永続化されている情報を削除する

要は、Key-Valueペアの文字列情報を保存することができる。そこで、データを保存して取得するだけの、Persistence APIを使ったシンプルなサンプルアプリを作ってみた。

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="PersistenceTest"> 
    <Require feature="opensocial-0.8"/>
  </ModulePrefs>
  <Content type="html">
  <![CDATA[
  <script type="text/javascript">
  
  function saveData() {
    var value = document.getElementById("input_data").value;
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, "key", value));
    req.send(function(response) {
      if (response.hadError()) {
        alert(response.getErrorMessage());
      } else {
        alert("データが保存されました。")
      }
    });
  }
  
  function loadData() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "viewer");
    req.add(req.newFetchPersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, ["key"]), "viewer_data");
    req.send(function(response) {
      if (response.hadError()) {
        alert(response.getErrorMessage());
      } else {
        var myId = response.get("viewer").getData().getId();
        var data = response.get("viewer_data").getData();
        alert(data[myId]["key"]);
      }
    });
  }
  </script>
  
  <input type="text" id="input_data"/>
  <button onclick="saveData()">データ保存</button>
  <button onclick="loadData()">データ取得</button>
  ]]> 
  </Content>
</Module>

「データ保存」ボタンを押すと、savaData()関数がnewUpdatePersonAppDataRequest()メソッドを使って、入力されたデータの永続化を行い、「データ取得」ボタンを押すと、loadData()関数がnewFetchPersonAppDataRequest()メソッドを使って永続化されたデータの取得を行う。

newUpdatePersonAppDataRequest()メソッドやnewFetchPersonAppDataRequest()メソッドは、newFetchPersonRequest()メソッドと同様、opensocial.DataRequestオブジェクトのメソッドだ。DataRequestオブジェクトに追加してリクエストを送信する。

newUpdatePersonAppDataRequest()メソッドは3つの引数は、

  1. ユーザのID
  2. 永続化する情報のキー文字列
  3. 永続化する情報の文字列
mixi Platformでは、第1引数のユーザIDは、セキュイティの観点からopensocial.IdSpec.PersonId.VIEWERしか許可されていないそうだ。

newUpdatePersonAppDataRequest()メソッドでは、「誰のデータを取得するか」を指定するidSpecと、「どのデータを取得するか」を指定するキー文字列を指定する。キー文字列は配列で指定するところに注意(つまり、複数のデータを一度に取得できる)。

このサンプルアプリでは、自分 (VIEWER) のデータを保存し、自分 (VIEWER) のデータを取得する。

参考URL:
OpenSocial API デベロッパーガイド, mixi Developer Center

0 コメント:

コメントを投稿