

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon Quick Sight で実行時に埋め込みコールバックアクションを追加する
<a name="embedding-custom-actions-callback"></a>

埋め込みデータポイントコールバックアクションを使用して、Software as a Service (SaaS) アプリケーションと Amazon Quick Sight 埋め込みダッシュボードおよびビジュアルとのより緊密な統合を構築します。デベロッパーは、Amazon Quick Sight 埋め込み SDK で呼び出すデータポイントを登録できます。ビジュアルのコールバックアクションを登録すると、読者はビジュアル上のデータポイントを選択して、選択したデータポイントに固有のデータを提供するコールバックを受け取ることができます。この情報を使用して、キーレコードにフラグを付けたり、データポイント固有の未加工データをコンパイルしたり、レコードをキャプチャしたり、バックエンドプロセス用のデータをコンパイルしたりできます。

埋め込みコールバックは、カスタムビジュアルコンテンツ、テキストボックス、またはインサイトではサポートされていません。

コールバック用のデータポイントの登録を開始する前に、Embedding SDK をバージョン 2.3.0 に更新してください。Amazon Quick Sight Embedding SDK の使用の詳細については、GitHub の [amazon-quicksight-embedding-sdk](https://github.com/awslabs/amazon-quicksight-embedding-sdk) を参照してください。

データポイントコールバックは、Amazon Quick Sight SDK を通じて実行時に 1 つ以上のビジュアルに登録できます。また、[VisualCustomAction](https://docs.aws.amazon.com/quicksight/latest/APIReference/API_VisualCustomAction.html) API 構造体がサポートするあらゆるインタラクションに対して、データポイントコールバックを登録することもできます。これにより、ユーザーがビジュアル上でデータポイントを選択したとき、またはデータポイントのコンテキストメニューからデータポイントを選択したときに、データポイントコールバックを開始できます。次の例では、読者がビジュアル上のデータポイントを選択したときに開始するデータポイントコールバックを登録します。

```
/const MY_GET_EMBED_URL_ENDPOINT =
  "https://my.api.endpoint.domain/MyGetEmbedUrlApi"; // Sample URL

// The dashboard id to embed
const MY_DASHBOARD_ID = "my-dashboard"; // Sample ID

// The container element in your page that will have the embedded dashboard
const MY_DASHBOARD_CONTAINER = "#experience-container"; // Sample ID

// SOME HELPERS

const ActionTrigger = {
  DATA_POINT_CLICK: "DATA_POINT_CLICK",
  DATA_POINT_MENU: "DATA_POINT_MENU",
};

const ActionStatus = {
  ENABLED: "ENABLED",
  DISABLED: "DISABLED",
};

// This function makes a request to your endpoint to obtain an embed url for a given dashboard id
// The example implementation below assumes the endpoint takes dashboardId as request data
// and returns an object with EmbedUrl property
const myGetEmbedUrl = async (dashboardId) => {
  const apiOptions = {
    dashboardId,
  };
  const apiUrl = new URL(MY_GET_EMBED_URL_ENDPOINT);
  apiUrl.search = new URLSearchParams(apiOptions).toString();
  const apiResponse = await fetch(apiUrl.toString());
  const apiResponseData = await apiResponse.json();
  return apiResponseData.EmbedUrl;
};

// This function constructs a custom action object
const myConstructCustomActionModel = (
  customActionId,
  actionName,
  actionTrigger,
  actionStatus
) => {
  return {
    Name: actionName,
    CustomActionId: customActionId,
    Status: actionStatus,
    Trigger: actionTrigger,
    ActionOperations: [
      {
        CallbackOperation: {
          EmbeddingMessage: {},
        },
      },
    ],
  };
};

// This function adds a custom action on the first visual of first sheet of the embedded dashboard
const myAddVisualActionOnFirstVisualOfFirstSheet = async (
  embeddedDashboard
) => {
  // 1. List the sheets on the dashboard
  const { SheetId } = (await embeddedDashboard.getSheets())[0];
  // If you'd like to add action on the current sheet instead, you can use getSelectedSheetId method
  // const SheetId = await embeddedDashboard.getSelectedSheetId();

  // 2. List the visuals on the specified sheet
  const { VisualId } = (await embeddedDashboard.getSheetVisuals(SheetId))[0];

  // 3. Add the custom action to the visual
  try {
    const customActionId = "custom_action_id"; // Sample ID
    const actionName = "Flag record"; // Sample name
    const actionTrigger = ActionTrigger.DATA_POINT_CLICK; // or ActionTrigger.DATA_POINT_MENU
    const actionStatus = ActionStatus.ENABLED;
    const myCustomAction = myConstructCustomActionModel(
      customActionId,
      actionName,
      actionTrigger,
      actionStatus
    );
    const response = await embeddedDashboard.addVisualActions(
      SheetId,
      VisualId,
      [myCustomAction]
    );
    if (!response.success) {
      console.log("Adding visual action failed", response.errorCode);
    }
  } catch (error) {
    console.log("Adding visual action failed", error);
  }
};

const parseDatapoint = (visualId, datapoint) => {
  datapoint.Columns.forEach((Column, index) => {
    // FIELD | METRIC
    const columnType = Object.keys(Column)[0];

    // STRING | DATE | INTEGER | DECIMAL
    const valueType = Object.keys(Column[columnType])[0];
    const { Column: columnMetadata } = Column[columnType][valueType];

    const value = datapoint.RawValues[index][valueType];
    const formattedValue = datapoint.FormattedValues[index];

    console.log(
      `Column: ${columnMetadata.ColumnName} has a raw value of ${value}
           and formatted value of ${formattedValue.Value} for visual: ${visualId}`
    );
  });
};

// This function is used to start a custom workflow after the end user selects a datapoint
const myCustomDatapointCallbackWorkflow = (callbackData) => {
  const { VisualId, Datapoints } = callbackData;

  parseDatapoint(VisualId, Datapoints);
};

// EMBEDDING THE DASHBOARD

const main = async () => {
  // 1. Get embed url
  let url;
  try {
    url = await myGetEmbedUrl(MY_DASHBOARD_ID);
  } catch (error) {
    console.log("Obtaining an embed url failed");
  }

  if (!url) {
    return;
  }

  // 2. Create embedding context
  const embeddingContext = await createEmbeddingContext();

  // 3. Embed the dashboard
  const embeddedDashboard = await embeddingContext.embedDashboard(
    {
      url,
      container: MY_DASHBOARD_CONTAINER,
      width: "1200px",
      height: "300px",
      resizeHeightOnSizeChangedEvent: true,
    },
    {
      onMessage: async (messageEvent) => {
        const { eventName, message } = messageEvent;
        switch (eventName) {
          case "CONTENT_LOADED": {
            await myAddVisualActionOnFirstVisualOfFirstSheet(embeddedDashboard);
            break;
          }
          case "CALLBACK_OPERATION_INVOKED": {
            myCustomDatapointCallbackWorkflow(message);
            break;
          }
        }
      },
    }
  );
};

main().catch(console.error);
```

前述の例は、ユーザーがコンテキストメニューを開いたときにデータポイントコールバックを開始するように構成することもできます。前述の例でこれを実行するには、`ActionTrigger.DATA_POINT_MENU` に `actionTrigger` の値を設定します。

データポイントコールバックが登録されると、指定されたビジュアルまたはビジュアル上のほとんどのデータポイントに適用されます。コールバックはビジュアルの合計や小計には適用されません。リーダーがデータポイントとやり取りすると、Amazon Quick Sight 埋め込み SDK に`CALLBACK_OPERATION_INVOKED`メッセージが出力されます。このメッセージは、`onMessage` ハンドラーによってキャプチャされます。メッセージには、選択したデータポイントに関連するデータ行全体の未処理値と表示値が含まれます。また、データポイントが含まれているビジュアル内のすべての列の列メタデータも含まれています。以下は、`CALLBACK_OPERATION_INVOKED` メッセージの例です。

```
{
   CustomActionId: "custom_action_id",
   DashboardId: "dashboard_id",
   SheetId: "sheet_id",
   VisualId: "visual_id",
   DataPoints: [
        {
            RawValues: [
                    {
                        String: "Texas" // 1st raw value in row
                    },
                    {
                        Integer: 1000 // 2nd raw value in row
                    }
            ],
            FormattedValues: [
                    {Value: "Texas"}, // 1st formatted value in row
                    {Value: "1,000"} // 2nd formatted value in row
            ],
            Columns: [
                    { // 1st column metadata
                        Dimension: {
                            String: {
                                Column: {
                                    ColumnName: "State",
                                    DatsetIdentifier: "..."
                                }
                            }
                        }
                    },
                    { // 2nd column metadata
                        Measure: {
                            Integer: {
                                Column: {
                                    ColumnName: "Cancelled",
                                    DatsetIdentifier: "..."
                                },
                                AggregationFunction: {
                                    SimpleNumericalAggregation: "SUM"
                                }
                            }
                        }
                    }
            ]
        }
   ]
}
```