Closed17

Discovery Engine API client for Node.jsを試す

筧剛彰 / Takaaki Kakei筧剛彰 / Takaaki Kakei

下準備

Quickstartに従って、プロジェクトでAPIを有効化して、サービスアカウントをセットアップしておく
https://cloud.google.com/nodejs/docs/reference/discoveryengine/latest#quickstart

筧剛彰 / Takaaki Kakei筧剛彰 / Takaaki Kakei

今回はアプリケーションが Google Cloud 環境外で動かす想定なので、以下の手順で基本的に動かす

https://cloud.google.com/docs/authentication/production?hl=ja#manually

サンプル

// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');

// Instantiates a client. Explicitly use service account credentials by
// specifying the private key file. All clients in google-cloud-node have this
// helper, see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// const projectId = 'project-id'
// const keyFilename = '/path/to/keyfile.json'
const storage = new Storage({projectId, keyFilename});

// Makes an authenticated API request.
async function listBuckets() {
  try {
    const [buckets] = await storage.getBuckets();

    console.log('Buckets:');
    buckets.forEach(bucket => {
      console.log(bucket.name);
    });
  } catch (err) {
    console.error('ERROR:', err);
  }
}
listBuckets();
筧剛彰 / Takaaki Kakei筧剛彰 / Takaaki Kakei
筧剛彰 / Takaaki Kakei筧剛彰 / Takaaki Kakei

権限周りが鬼門だったけど、強めな権限でとりあえず実行できた

  • IAMの権限をオーナーとストレージ管理者
  • サービスアカウントのロールを管理者
筧剛彰 / Takaaki Kakei筧剛彰 / Takaaki Kakei
const projectId = 'xxxxxx';

const credentials = process.env.KEY|| '{}';
const credentialsJson = JSON.parse(credentials);

const pageSize = 10;
// const pageToken = 'abc123' //responseから取得するらしい

const { DocumentServiceClient } =
  require('@google-cloud/discoveryengine').v1beta;

const discoveryengineClient = new DocumentServiceClient({
  projectId,
  credentialsJson,
});

async function callListDocuments() {
  const location = 'global';
  const data_store = 'yyyyyyyyyy'; // データストアの ID
  const branch = 'default_branch'; // Branch must be one of "default_branch" or "0"

  const parent = `projects/${projectId}/locations/${location}/dataStores/${data_store}/branches/${branch}`;
  const request = {
    parent,
  };
  const iterable = await discoveryengineClient.listDocumentsAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}
callListDocuments();

このスクラップは2023/11/30にクローズされました