Amazon Alexa

alexa-sdkでDynamoDBをつかう

この記事は一人Alexa Skills Kit for Node.js Advent Calendar 2017の17日目の記事です。 attributesを使うことでデータを一時的に保持することはできます。ですがセッシ […]

広告ここから
広告ここまで

この記事は一人Alexa Skills Kit for Node.js Advent Calendar 2017の17日目の記事です。

attributesを使うことでデータを一時的に保持することはできます。ですがセッションが終了すると消えてしまうものですので、永続化したいデータには向いていません。

DynamoDBをalexa-sdkでよしなに扱う

alexa-sdkを使う場合は心配になるくらい簡単にセットアップと利用ができます。

exports.handler = function (event, context, callback) {
    var alexa = Alexa.handler(event, context, callback);
    alexa.appId = 'appId';
    alexa.dynamoDBTableName = 'YourTableName'; // これだけ
    alexa.registerHandlers(handlers;
    alexa.execute();
};

alexa.dynamoDBTableNameに使用するテーブルの名前を書きましょう。
初回の実行時にテーブルが存在しなければalexa-sdkがDynamoDBのテーブルの作成をやってくれます。(エラーになった場合はLambdaのIAMロールがDynamoDBへのアクセスを許可されてるか確認しましょう)

あとはいかのような関数を用意してthis.attributesに保存したいデータをつっこみましょう。

function saveValue(options) {
    let key = `_${options.fieldName}`;

    // if append and the value exists push it into the array.
    // if append but it doesn't exist add it as an array.
    // else just save it as a singular value.
    // NOTE: This will fail if you set options.append to true
    // on a value that was previously saved with options.append
    // set to false. You'll need to convert the field first.
    // check if it's an array and if not convert it to an array
    // and push.
    if (options.append && this.attributes[key]) {
        this.attributes[key].push(options.data);
    } else if (options.append) {
        this.attributes[key] = [options.data];
    } else {
        this.attributes[key] = options.data;
    }
}

from: https://github.com/alexa/skill-sample-nodejs-petmatch/blob/master/lambda/custom/index.js#L277-L302
[key]がKeyで代入されてる値がValueとして保存されます。
また、プライマリキーはUserIdを自動挿入してくるので特に意識する必要はありません。

べんり・・・?

  • IAMロールにDynamoDB周りを追加
  • alexa.dynamoDBTableNameにテーブル名を追加
  • this.attributesにKVS方式でデータを保存

この3ステップで各種データをDynamoDBに保存することができます。
ただし、this.attributesの値を全部突っ込んでくることや、テーブルの新規作成までやってくるところが引っかかる人もいるかもしれません。

もし「ちょっとなぁ・・・」という方は、aws-sdkputItemなどをする方法も検討してみてください。

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts