How to use @grpc/grpc-js - 10 common examples

To help you get started, we’ve selected a few @grpc/grpc-js examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cjihrig / grpc-server-js / test / server.js View on Github external
const Assert = require('assert');
const Fs = require('fs');
const Http2 = require('http2');
const Path = require('path');
const Barrier = require('cb-barrier');
const Lab = require('@hapi/lab');
const Grpc = require('@grpc/grpc-js');
const { Server, ServerCredentials } = require('../lib');
const { loadProtoFile } = require('./common');

// Test shortcuts
const lab = exports.lab = Lab.script();
const { describe, it, before, after, beforeEach, afterEach } = lab;


const clientInsecureCreds = Grpc.credentials.createInsecure();
const serverInsecureCreds = ServerCredentials.createInsecure();


describe('Server', () => {
  describe('constructor', () => {
    it('should work with no arguments', () => {
      Assert.doesNotThrow(() => {
        new Server(); // eslint-disable-line no-new
      });
    });

    it('should work with an empty object argument', () => {
      const options = {};

      Assert.doesNotThrow(() => {
        new Server(options); // eslint-disable-line no-new
github GoogleCloudPlatform / esp-v2 / tests / endpoints / bookstore_grpc / grpc_server.js View on Github external
// This port is used by the backend settings in envoy.yaml
var PORT = 8082;
const path = require('path');
const PROTO_PATH = path.join(__dirname, '/proto/bookstore.proto');

var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});

var bookstore_proto =
    grpc.loadPackageDefinition(packageDefinition).endpoints.examples.bookstore;

// The bookstore example uses a simple, in-memory database
// for illustrative purposes only.
var bookstoreDatabase = {
  100: {id: 100, theme: 'Kids', books: {1001: {id: 1001, title: 'Alphabet'}}},
  200: {
    id: 200,
    theme: 'Classic',
    books: {2001: {id: 2001, title: 'Hamlet', author: 'Shakspeare'}}
  }
};

function listShelves(call, callback) {
  console.log(call.metadata);
  var found = [];
  for (var key in bookstoreDatabase) {
github googleapis / nodejs-pubsub / test / pubsub.ts View on Github external
import {CallOptions, ChannelCredentials, ServiceError} from '@grpc/grpc-js';
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';

import {google} from '../proto/pubsub';
import * as pubsubTypes from '../src/pubsub';
import {Snapshot} from '../src/snapshot';
import * as subby from '../src/subscription';
import {Topic} from '../src/topic';
import * as util from '../src/util';

const PKG = require('../../package.json');
const sandbox = sinon.createSandbox();

const fakeCreds = {} as ChannelCredentials;
sandbox.stub(grpc.credentials, 'createInsecure').returns(fakeCreds);

const subscriptionCached = subby.Subscription;

// tslint:disable-next-line no-any
let subscriptionOverride: any;

function Subscription(
  pubsub: pubsubTypes.PubSub,
  name: string,
  options: subby.SubscriptionOptions
) {
  const overrideFn = subscriptionOverride || subscriptionCached;
  return new overrideFn(pubsub, name, options);
}

let promisified = false;
github GoogleCloudPlatform / esp-v2 / tests / endpoints / bookstore_grpc / grpc_server.js View on Github external
return function(call, callback) {
    var testValues = call.metadata.get('x-grpc-test');
    var firstTestValue = undefined;
    if (testValues != undefined && testValues.length > 0) {
      firstTestValue = testValues[0];
    }
    // Add more gRPC statuses as needed.
    switch (firstTestValue) {
      case 'ABORTED':
        callback({
          code: grpc.status.ABORTED,  // 10
          message: 'ABORTED',
        });
        break;
      case 'INTERNAL':
        callback({
          code: grpc.status.INTERNAL,  // 13
          message: 'INTERNAL',
        });
        break;
      case 'DATA_LOSS':
        callback({
          code: grpc.status.DATA_LOSS,  // 15
          message: 'DATA_LOSS',
        });
        break;
      default:
github GoogleCloudPlatform / esp-v2 / tests / endpoints / bookstore_grpc / grpc_server.js View on Github external
function main() {
  let server = new grpc.Server();

  // Bookstore service
  server.addService(bookstore_proto.Bookstore.service, {
    ListShelves: testDecorator(listShelves),
    CreateShelf: testDecorator(createShelf),
    GetShelf: testDecorator(getShelf),
    DeleteShelf: testDecorator(deleteShelf),
    ListBooks: testDecorator(listBooks),
    CreateBook: testDecorator(createBook),
    GetBook: testDecorator(getBook),
    DeleteBook: testDecorator(deleteBook),
  });

  // Health service following standard protocol
  const statusMap = {
    "": proto.grpc.health.v1.HealthCheckResponse.ServingStatus.SERVING,
github ablehq / firestore-explorer / firebase-proxy / src / controllers / LocalHelper.ts View on Github external
import { LocalQuery } from "../models/Commands";
import { Firestore } from "@google-cloud/firestore";
const grpc = require("@grpc/grpc-js");
// Create a new client
const firestore = new Firestore({
  servicePath: "localhost",
  port: 8080,
  projectId: "firebase-explorer-test",
  sslCreds: grpc.credentials.createInsecure(),
  customHeaders: {
    Authorization: "Bearer owner"
  }
});

export const handleLocalQuery = async (query: LocalQuery) => {
  let data: { [key: string]: any } = {};
  const db = firestore;
  const result = await db.doc("movies/60756").get();
  const collections = await result.ref.listCollections();
  console.log(collections);
  data["success"] = true;
  data["data"] = {
    id: result.id,
    path: result.ref.path,
    data: result.data()
github mozilla / fxa / packages / fxa-event-broker / bin / workerDev.ts View on Github external
.createQueue({
          QueueName: queueName
        })
        .promise();
    }

    // Utilize the local firestore emulator if we were told to use it
    if (firestoreEnabled && NODE_ENV === 'development') {
      const fstore = new Firestore({
        customHeaders: {
          Authorization: 'Bearer owner'
        },
        port: 8006,
        projectId: 'fx-event-broker',
        servicePath: 'localhost',
        sslCreds: grpc.credentials.createInsecure()
      });
      db = new FirestoreDatastore(firestoreConfig, fstore);
    }
  } catch (err) {
    logger.error('Error loading application:', { err });
    process.exit(1);
  }

  const capabilityService = new ClientCapabilityService(
    logger,
    Config.get('clientCapabilityFetch')
  );
  const webhookService = new ClientWebhookService(
    logger,
    Config.get('clientCapabilityFetch.refreshInterval'),
    db
github LN-Zap / zap-desktop / lnd / util.js View on Github external
export const createMacaroonCreds = async macaroonPath => {
  const metadata = new Metadata()

  if (macaroonPath) {
    // If the macaroon is already in hex format, add as is.
    const isHex = /^[0-9a-fA-F]+$/.test(macaroonPath)
    if (isHex) {
      metadata.add('macaroon', macaroonPath)
    }
    // Otherwise, treat it as a file path - load the file and convert to hex.
    else {
      const macaroon = await readFile(macaroonPath).catch(e => {
        const error = new Error(`Macaroon path could not be accessed: ${e.message}`)
        error.code = 'LND_GRPC_MACAROON_ERROR'
        throw error
      })
      metadata.add('macaroon', macaroon.toString('hex'))
    }
github LN-Zap / node-lnd-grpc / src / utils / createMacaroonCreds.js View on Github external
const createMacaroonCreds = async macaroonPath => {
  const metadata = new Metadata()
  let lndMacaroon

  if (macaroonPath) {
    // If the macaroon is already in hex format, add as is.
    const isHex = /^[0-9a-fA-F]+$/.test(macaroonPath)
    if (isHex) {
      lndMacaroon = macaroonPath
    }
    // If it's not a filepath, then assume it is a base64url encoded string.
    else if (macaroonPath === basename(macaroonPath)) {
      lndMacaroon = decodeMacaroon(macaroonPath)
    }
    // Otherwise, treat it as a file path - load the file and convert to hex.
    else {
      const macaroon = await readFile(untildify(macaroonPath)).catch(e => {
        const error = new Error(`Macaroon path could not be accessed: ${e.message}`)
github LN-Zap / node-lnd-grpc / src / service.js View on Github external
connectionOptions,
      version,
    } = opts

    try {
      // Find the most recent proto file for this service if a specific version was not requested.
      this.version = version || getLatestProtoVersion()

      const serviceDefinition = registry[this.version].services.find(s => s.name === this.serviceName)
      const [protoPackage, protoFile] = serviceDefinition.proto.split('/')
      const filepath = join(protoDir || getProtoDir(), this.version, protoPackage, protoFile)
      this.debug(`Establishing gRPC connection to ${this.serviceName} with proto file %s`, filepath)

      // Load gRPC package definition as a gRPC object hierarchy.
      const packageDefinition = await load(filepath, grpcOptions)
      const rpc = loadPackageDefinition(packageDefinition)

      // Wait for the cert to exist (this can take some time immediately after starting lnd).
      if (waitForCert) {
        const waitTime = Number.isFinite(waitForCert) ? waitForCert : FILE_WAIT_TIMEOUT
        await waitForFile(cert, waitTime)
      }

      // Create ssl credentials to use with the gRPC client.
      let creds = await createSslCreds(cert)

      // Add macaroon to credentials if service requires macaroons.
      if (this.useMacaroon && macaroon) {
        // Wait for the macaroon to exist (this can take some time immediately after Initializing a wallet).
        if (waitForMacaroon) {
          const waitTime = Number.isFinite(waitForMacaroon) ? waitForMacaroon : FILE_WAIT_TIMEOUT
          await waitForFile(macaroon, waitTime)