如何在 Node.js 上使用 gRPC 调用 Home Graph API

问题描述

鉴于可用的协议缓冲区定义:https://github.com/googleapis/googleapis/blob/master/google/home/graph/v1/homegraph.proto

如何在 Node.js 上使用 gRPC 调用 Home Graph API RPC endpoint 以通过单个连接多路复用并发 API 方法调用

解决方法

您可以将 @grpc-jsApplication Default Credentials 结合使用来初始化凭据。

$ npm install @grpc/grpc-js
$ npm install google-auth-library
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json
const grpc = require('@grpc/grpc-js');
const { GoogleAuth } = require('google-auth-library');

async function getCredentials() {
  const sslCredentials = grpc.credentials.createSsl();
  const googleAuth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/homegraph'
  });
  const authClient = await googleAuth.getClient();
  const callCredentials = grpc.credentials.createFromGoogleCredential(
      authClient
  );
  const credentials = grpc.credentials.combineChannelCredentials(
      sslCredentials,callCredentials
  );
  return credentials;
}

使用 google-proto-files@grpc/proto-loader 加载 Home Graph 服务 protobuf 定义及其依赖项。

const protoLoader = require('@grpc/proto-loader');
const protos = require('google-proto-files');

async function getHomegraph() {
  const homegraphProto = await protoLoader.load(
      protos.getProtoPath('home/graph','v1','homegraph.proto'),{
        includeDirs: [protos.getProtoPath('..')]
      }
  );
  const homegraph = grpc.loadPackageDefinition(
      homegraphProto
  ).google.home.graph.v1;
  return homegraph;
}

最后初始化客户端存根以调用 HomeGraphApiService 方法。

(async function() {
  const credentials = await getCredentials();
  const homegraph = await getHomegraph();

  const homegraphService = new homegraph.HomeGraphApiService(
      'homegraph.googleapis.com',credentials
  );

  homegraphService.sync({
    agentUserId: 'AGENT_USER_ID'
  },function(err,result) {
    if (err) {
      console.error(err);
    } else {
      console.log(result);
    }
  });

  // homegraphService.query();
  // homegraphService.requestSyncDevices();
  // homegraphService.reportStateAndNotification();
  // homegraphService.deleteAgentUser();
})();

请注意,默认情况下,如果参数(地址、凭据和选项)相同,Channel implementation 将重用全局池中的现有通道。您可以使用 grpc.use_local_subchannel_pool option 更改此行为。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...