Socket
Socket
Sign inDemoInstall

@nextpay/grpc-node-status-proto

Package Overview
Dependencies
37
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @nextpay/grpc-node-status-proto

[![Version](https://img.shields.io/npm/v/@nextpay/grpc-node-status-proto.svg)](https://www.npmjs.com/package/@nextpay/grpc-node-status-proto) [![License](https://img.shields.io/npm/l/@nextpay/grpc-node-status-proto.svg)](https://github.com/quangtm210395/g


Version published
Weekly downloads
685
decreased by-14.05%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

grpc-node-status-proto

Version License Build Status

Utility function for serializing and deserializing between the grpc-status-details-bin metadata value and StatusProto when using the node grpc package. Error details allow sending/receiving additional data along with an error. For instance, if a request sends invalid data, a gRPC server could send back a BadRequest message identifying the field and why it failed validation.

gRPC services that send rich error details place information in the grpc-status-details-bin metadata property of the ServiceError passed to the callback of a failed gRPC method call. The value of the grpc-status-details-bin field is a serialized Status message. The Status message's details field is an array of Any messages, which consist of a type field and the serialized data for that message type.

This library, given an error, returns back the both deserialized Status message and an array of deserialized detail messages as a StatusProto object.

Install

# yarn
yarn add @nextpay/grpc-node-status-proto

# npm
npm install @nextpay/grpc-node-status-proto

Usage

This library provide methods to serialize and deserialize grpc-status-details-bin metadata value and StatusProto when using the node grpc package.

Version 1.x using grpc

Version 2.x using new @grpc/grpc-js

export class StatusProto<T extends Message> {
  private status: Status | undefined;

  private code: number;

  private message: string;

  private details: Array<T>;
}

where:

  • status is a google defined Status
  • code is gRPC status Code
  • message is error message
  • and details is the Status's details array with each item deserialized and unpacked from an Any message to its actual message type. You can create your own message type or checkout google's defined message types

StatusProto.fromServiceError(error, deserializeMap)

StatusProto.fromServiceError allows passing in the deserializeMap argument, where each key is a message type and each value is its corresponding deserialize function. You can use provided googleDeserializeMap captured of Google's rpc error details type's deserialize function to deserialize google's Error Details

Example:

import {
  googleDeserializeMap, StatusProto, BadRequest, Status,
} from "@nextpay/grpc-node-status-proto";

// Make grpc call that fails and returns a Status object with
// details in the `grpc-status-details-bin` Metadata property
function hello(message: string, metadata?: any) {
  return new Promise((resolve, reject) => {
    const meta = new Metadata();
    if (metadata) {
      Object.keys(metadata).map((key: string) => {
        meta.add(key, metadata[key]);
        return null;
      });
    }
    let response = {};
    const call: ClientUnaryCall = stub.hello(
      { message }, meta, async (err: any, res: any): Promise<any> => {
        if (err) {
          const statusProto = StatusProto.fromServiceError(err, googleDeserializeMap);
          const details = statusProto.getDetails();
          for (let i = 0; i < details.length; i += 1) {
            const detail = details[i];
            if (detail instanceof BadRequest) {
              console.info('badrequest: ', detail.toObject());
              // TODO do something with bad request error
            }
          }
          console.error('calling greeter.hello failed: ', err);
          reject(err);
          return;
        }
        response = res;
      },
    );
    call.once('status', (status: StatusObject) => {
      resolve({ data: response, meta: status.metadata.getMap() });
    });
  });
}

statusProto.toServiceError()

statusProto.toServiceError() convert a StatusProto to grpc 's ServiceError

Example:

import {
  StatusProto, BadRequest, googleErrorDetailsTypeNameMap,
} from "@nextpay/grpc-node-status-proto";

// import others thing from grpc...

// adding hello rpc function
server.addService(Greeter.Greeter.service, {
  hello(call: ServerUnaryCall<any, any>, callback: any) {
    console.info('greeting: ', call.request.message);
    if (!call.request.message) {
      const metadata: Metadata = new Metadata();
      metadata.add('1', '123');
      const br = new BadRequest();
      const fv = new BadRequest.FieldViolation();
      fv.setField('message');
      fv.setDescription('message is missing');
      br.addFieldViolations(fv);

      const statusProto = new StatusProto(status.INVALID_ARGUMENT, 'Required fields must not be null');
      statusProto.addDetail(br, googleErrorDetailsTypeNameMap.BadRequest);
      const error = statusProto.toServiceError();
      return callback(error);
    }
    return callback(null, { message: `hi there from greeter, response for: ${call.request.message}` });
  },
});

For full example, checkout here

FAQs

Last updated on 19 Jul 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc