"Could not load the default credentials" - 使用模拟器的 PubSub Node.js 模块

"Could not load the default credentials" - PubSub Node.js module using the Emulator

Node.js 的 PubSub 模块有问题。我使用 Docker 和 PubSub 模拟器创建了一个本地环境。我可以发布一条消息并使用异步拉取检索它(如此处记录:https://cloud.google.com/pubsub/docs/pull#asynchronous-pull). However when I'm trying to use the synchronous pull (https://cloud.google.com/pubsub/docs/pull#synchronous-pull)我一直遇到以下错误:

Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information. at GoogleAuth. (/var/code/node_modules/google-auth-library/build/src/auth/googleauth.js:167:23) at next (native) at fulfilled (/var/code/node_modules/google-auth-library/build/src/auth/googleauth.js:19:58) at process._tickCallback (internal/process/next_tick.js:109:7) (node:493) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 32)

每当我尝试实例化 v1 PublisherClient 或 SubscriberClient 时都会发生此错误:

const pubsub = require('@google-cloud/pubsub');

new pubsub.v1.PublisherClient();
new pubsub.v1.SubscriberClient();

我觉得 v1 组件不能与模拟器一起使用,而是直接连接到云服务。 有没有办法让这些客户端连接到模拟器而不是云?我找不到任何... 谢谢!

我找到了解决这个问题的方法:PublisherClient 和 SubscriberClient 构造函数都有设置模拟器路径的选项。选项为 servicePathport。您还需要有效凭据才能传递给使用 grpc 模块生成的 sslCreds 选项。以下是示例:

const grpc = require('grpc');

const subscriber = new pubsub.v1.SubscriberClient({
  servicePath: 'path.to.your.emulator',
  port: 8080, // port your emulator is running on (default is 443)
  sslCreds: grpc.credentials.createInsecure()
});

完整答案如下:https://github.com/googleapis/nodejs-pubsub/issues/346

以下 TS 示例似乎对我有用。

import { PubSub, v1 } from "@google-cloud/pubsub";
import * as gax from "google-gax";

if (process.env.PUBSUB_EMULATOR_HOST) {
    const pieces = process.env.PUBSUB_EMULATOR_HOST.split(":");

    options = {
        servicePath: pieces[0],
        port: pieces[1],
        isEmulator: true,
        sslCreds: gax.grpc.credentials.createInsecure(),
    };
}
const subClient = new v1.SubscriberClient(options);