grpc
- Version 1.24.11
- Published
- 23.3 MB
- 6 dependencies
- Apache-2.0 license
Install
npm i grpc
yarn add grpc
pnpm add grpc
Overview
gRPC Library for Node
Index
Namespaces
grpc
- Call
- CallCredentials
- callError
- CallOptions
- CancelRequester
- Certificate
- Channel
- ChannelCredentials
- CheckServerIdentityCallback
- Client
- ClientDuplexStream
- ClientReadableStream
- ClientUnaryCall
- ClientWritableStream
- closeClient()
- CloseRequester
- connectivityState
- credentials
- Deadline
- deserialize
- Filename
- GenericClientOptions
- getClientChannel()
- GetPeerRequester
- GoogleOAuth2Client
- GrpcObject
- handleBidiStreamingCall
- handleCall
- handleClientStreamingCall
- handleServerStreamingCall
- handleUnaryCall
- InterceptingCall
- KeyCertPair
- Listener
- ListenerBuilder
- load()
- loadObject()
- LoadObjectOptions
- LoadOptions
- loadPackageDefinition()
- logVerbosity
- makeGenericClientConstructor()
- MessageListener
- MessageRequester
- Metadata
- metadataGenerator
- MetadataListener
- MetadataOptions
- MetadataRequester
- MetadataValue
- MethodDefinition
- methodTypes
- PackageDefinition
- propagate
- ProtobufMessage
- ProtobufTypeDefinition
- requestCallback
- Requester
- RequesterBuilder
- sendUnaryData
- serialize
- Server
- ServerCredentials
- ServerDuplexStream
- ServerReadableStream
- ServerUnaryCall
- ServerWritableStream
- ServerWriteableStream
- ServiceDefinition
- ServiceError
- setLogger()
- setLogVerbosity()
- status
- StatusBuilder
- StatusListener
- StatusObject
- UntypedServiceImplementation
- VerifyOptions
- waitForClientReady()
- writeFlags
Namespaces
namespace grpc
module 'grpc' {}
variable credentials
const credentials: { createSsl( rootCerts?: Buffer, privateKey?: Buffer, certChain?: Buffer, verifyOptions?: VerifyOptions ): ChannelCredentials; createFromMetadataGenerator( metadataGenerator: metadataGenerator ): CallCredentials; createFromGoogleCredential( googleCredential: GoogleOAuth2Client ): CallCredentials; combineChannelCredentials( channelCredential: ChannelCredentials, ...credentials: CallCredentials[] ): ChannelCredentials; combineCallCredentials(...credentials: CallCredentials[]): CallCredentials; createInsecure(): ChannelCredentials;};
Credentials module
This module contains factory methods for two different credential types: CallCredentials and ChannelCredentials. ChannelCredentials are things like SSL credentials that can be used to secure a connection, and are used to construct a Client object. CallCredentials generally modify metadata, so they can be attached to an individual method call.
CallCredentials can be composed with other CallCredentials to create CallCredentials. ChannelCredentials can be composed with CallCredentials to create ChannelCredentials. No combined credential can have more than one ChannelCredentials.
For example, to create a client secured with SSL that uses Google default application credentials to authenticate:
var channel_creds = credentials.createSsl(root_certs);(new GoogleAuth()).getApplicationDefault(function(err, credential) {var call_creds = credentials.createFromGoogleCredential(credential);var combined_creds = credentials.combineChannelCredentials(channel_creds, call_creds);var client = new Client(address, combined_creds);});
function closeClient
closeClient: (clientObj: Client) => void;
Close client.
Parameter clientObj
The client to close
function getClientChannel
getClientChannel: (client: Client) => Channel;
Return the underlying channel object for the specified client
Parameter client
The client The channel
See Also
grpc.Client#getChannel
function load
load: <T = GrpcObject>( filename: Filename, format?: 'proto' | 'json', options?: LoadOptions) => T;
Load a gRPC object from a .proto file.
Parameter filename
The file to load
Parameter format
The file format to expect. Defaults to 'proto'
Parameter options
Options to apply to the loaded file The resulting gRPC object
function loadObject
loadObject: <T = GrpcObject>(value: object, options?: LoadObjectOptions) => T;
Load a ProtoBuf.js object as a gRPC object.
Parameter value
The ProtoBuf.js reflection object to load
Parameter options
Options to apply to the loaded file The resulting gRPC object.
function loadPackageDefinition
loadPackageDefinition: (packageDefinition: PackageDefinition) => GrpcObject;
Load a gRPC package definition as a gRPC object hierarchy
Parameter packageDef
The package definition object The resulting gRPC object
function makeGenericClientConstructor
makeGenericClientConstructor: ( methods: ServiceDefinition<any>, serviceName: string, classOptions: GenericClientOptions) => typeof Client;
Creates a constructor for a client with the given methods, as specified in the methods argument. The resulting class will have an instance method for each method in the service, which is a partial application of one of the
grpc.Client
request methods, depending onrequestSerialize
andresponseSerialize
, with themethod
,serialize
, anddeserialize
arguments predefined.Parameter methods
An object mapping method names to method attributes
Parameter serviceName
The fully qualified name of the service
Parameter classOptions
An options object. New client constructor, which is a subclass of
grpc.Client
, and has the same arguments as that constructor.
function setLogger
setLogger: (logger: Console) => void;
Sets the logger function for the gRPC module. For debugging purposes, the C core will log synchronously directly to stdout unless this function is called. Note: the output format here is intended to be informational, and is not guaranteed to stay the same in the future. Logs will be directed to logger.error.
Parameter logger
A Console-like object.
function setLogVerbosity
setLogVerbosity: (verbosity: logVerbosity) => void;
Sets the logger verbosity for gRPC module logging. The options are members of the grpc.logVerbosity map.
Parameter verbosity
The minimum severity to log
function waitForClientReady
waitForClientReady: ( client: Client, deadline: Deadline, callback: (error: Error | null) => void) => void;
Wait for the client to be ready. The callback will be called when the client has successfully connected to the server, and it will be called with an error if the attempt to connect to the server has unrecoverably failed or if the deadline expires. This function will make the channel start connecting if it has not already done so.
Parameter client
The client to wait on
Parameter deadline
When to stop waiting for a connection. Pass Infinity to wait forever.
Parameter callback
The callback to call when done attempting to connect.
See Also
grpc.Client#waitForReady
class Channel
class Channel {}
constructor
constructor( target: string, credentials: ChannelCredentials, options: { [key: string]: string | number });
This constructor API is almost identical to the Client constructor, except that some of the options for the Client constructor are not valid here.
Parameter target
The address of the server to connect to
Parameter credentials
Channel credentials to use when connecting
Parameter options
A map of channel options that will be passed to the core
method close
close: () => void;
Close the channel. This has the same functionality as the existing grpc.Client.prototype.close
method createCall
createCall: ( method: string, deadline: Date | number, host: string | null, parentCall: Call | null, propagateFlags: number | null) => Call;
Create a call object. Call is an opaque type that is used by the Client and Server classes. This function is called by the gRPC library when starting a request. Implementers should return an instance of Call that is returned from calling createCall on an instance of the provided Channel class.
Parameter method
The full method string to request.
Parameter deadline
The call deadline
Parameter host
A host string override for making the request
Parameter parentCall
A server call to propagate some information from
Parameter propagateFlags
A bitwise combination of elements of grpc.propagate that indicates what information to propagate from parentCall.
method getConnectivityState
getConnectivityState: (tryToConnect: boolean) => connectivityState;
Get the channel's current connectivity state.
Parameter tryToConnect
If true, the channel will start connecting if it is idle. Otherwise, idle channels will only start connecting when a call starts.
method getTarget
getTarget: () => string;
Return the target that this channel connects to
method watchConnectivityState
watchConnectivityState: ( currentState: connectivityState, deadline: Date | number, callback: (error?: Error) => void) => void;
Watch for connectivity state changes.
Parameter currentState
The state to watch for transitions from. This should always be populated by calling getConnectivityState immediately before.
Parameter deadline
A deadline for waiting for a state change
Parameter callback
Called with no error when a state change, or with an error if the deadline passes without a state change.
class Client
class Client {}
Create a client with the given methods
constructor
constructor(address: string, credentials: ChannelCredentials, options?: {});
A generic gRPC client. Primarily useful as a base class for generated clients
Parameter address
Server address to connect to
Parameter credentials
Credentials to use to connect to the server
Parameter options
Options to apply to channel creation
method close
close: () => void;
Close this client.
method getChannel
getChannel: () => Channel;
Return the underlying channel object for the specified client The channel
method makeBidiStreamRequest
makeBidiStreamRequest: <RequestType, ResponseType>( method: string, serialize: serialize<RequestType>, deserialize: deserialize<ResponseType>, metadata?: Metadata | null, options?: CallOptions | null) => ClientDuplexStream<RequestType, ResponseType>;
Make a bidirectional stream request with this method on the given channel.
Parameter method
The name of the method to request
Parameter serialize
The serialization function for inputs
Parameter deserialize
The deserialization function for outputs
Parameter metadata
Array of metadata key/value pairs to add to the call
Parameter options
Options map An event emitter for stream related events
method makeClientStreamRequest
makeClientStreamRequest: <RequestType, ResponseType>( method: string, serialize: serialize<RequestType>, deserialize: deserialize<ResponseType>, metadata: Metadata | null, options: CallOptions | null, callback: requestCallback<ResponseType>) => ClientWritableStream<RequestType>;
Make a client stream request to the given method, using the given serialize and deserialize functions, with the given argument.
Parameter method
The name of the method to request
Parameter serialize
The serialization function for inputs
Parameter deserialize
The deserialization function for outputs
Parameter metadata
Array of metadata key/value pairs to add to the call
Parameter options
Options map
Parameter callback
The callback to for when the response is received An event emitter for stream related events
method makeServerStreamRequest
makeServerStreamRequest: <RequestType, ResponseType>( method: string, serialize: serialize<RequestType>, deserialize: deserialize<ResponseType>, argument: RequestType, metadata?: Metadata | null, options?: CallOptions | null) => ClientReadableStream<ResponseType>;
Make a server stream request to the given method, with the given serialize and deserialize function, using the given argument
Parameter method
The name of the method to request
Parameter serialize
The serialization function for inputs
Parameter deserialize
The deserialization function for outputs
Parameter argument
The argument to the call. Should be serializable with serialize
Parameter metadata
Array of metadata key/value pairs to add to the call
Parameter options
Options map An event emitter for stream related events
method makeUnaryRequest
makeUnaryRequest: <RequestType, ResponseType>( method: string, serialize: serialize<RequestType>, deserialize: deserialize<ResponseType>, argument: RequestType | null, metadata: Metadata | null, options: CallOptions | null, callback: requestCallback<ResponseType>) => ClientUnaryCall;
Make a unary request to the given method, using the given serialize and deserialize functions, with the given argument.
Parameter method
The name of the method to request
Parameter serialize
The serialization function for inputs
Parameter deserialize
The deserialization function for outputs
Parameter argument
The argument to the call. Should be serializable with serialize
Parameter metadata
Metadata to add to the call
Parameter options
Options map
Parameter callback
The callback to for when the response is received An event emitter for stream related events
method waitForReady
waitForReady: ( deadline: Deadline, callback: (error: Error | null) => void) => void;
Wait for the client to be ready. The callback will be called when the client has successfully connected to the server, and it will be called with an error if the attempt to connect to the server has unrecoverablly failed or if the deadline expires. This function will make the channel start connecting if it has not already done so.
Parameter deadline
When to stop waiting for a connection.
Parameter callback
The callback to call when done attempting to connect.
class ClientDuplexStream
class ClientDuplexStream<RequestType, ResponseType> extends Duplex {}
A stream that the client can read from or write to. Used for calls with duplex streaming.
method cancel
cancel: () => void;
Cancel the ongoing call. Results in the call ending with a CANCELLED status, unless it has already ended with some other status.
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method write
write: ( message: RequestType, flags?: any & writeFlags, callback?: Function) => boolean;
Write a message to the request stream. If serializing the argument fails, the call will be cancelled and the stream will end with an error.
Parameter message
The message to write. Must be a valid argument to the serialize function of the corresponding method
Parameter flags
Flags to modify how the message is written
Parameter callback
Callback for when this chunk of data is flushed As defined for [Writable]
class ClientReadableStream
class ClientReadableStream<ResponseType> extends Readable {}
A stream that the client can read from. Used for calls that are streaming from the server side.
class ClientUnaryCall
class ClientUnaryCall extends EventEmitter {}
An EventEmitter. Used for unary calls.
class ClientWritableStream
class ClientWritableStream<RequestType> extends Writable {}
A stream that the client can write to. Used for calls that are streaming from the client side.
method cancel
cancel: () => void;
Cancel the ongoing call. Results in the call ending with a CANCELLED status, unless it has already ended with some other status.
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method write
write: ( message: RequestType, flags?: any & writeFlags, callback?: Function) => boolean;
Write a message to the request stream. If serializing the argument fails, the call will be cancelled and the stream will end with an error.
Parameter message
The message to write. Must be a valid argument to the serialize function of the corresponding method
Parameter flags
Flags to modify how the message is written
Parameter callback
Callback for when this chunk of data is flushed As defined for [Writable]
class InterceptingCall
class InterceptingCall {}
A chainable gRPC call proxy which will delegate to an optional requester object. By default, interceptor methods will chain to nextCall. If a requester is provided which implements an interceptor method, that requester method will be executed as part of the chain. operations.
constructor
constructor(nextCall: InterceptingCall, requester?: Requester);
Parameter next_Call
The next call in the chain
Parameter requester
Interceptor methods to handle request
method cancel
cancel: () => void;
Run a cancel operation through the interceptor chain
method cancelWithStatus
cancelWithStatus: (status: StatusObject, message: string) => void;
Run a cancelWithStatus operation through the interceptor chain.
Parameter status
Parameter message
method getPeer
getPeer: () => object;
Pass a getPeer call down to the base gRPC call (should not be intercepted)
method halfClose
halfClose: () => void;
Run a close operation through the interceptor chain
method recvMessageWithContext
recvMessageWithContext: (context: object) => void;
For receiving streaming messages, we need to seed the base interceptor with the streaming context to create a RECV_MESSAGE batch.
Parameter context
Carries objects needed for streaming operations
method sendMessage
sendMessage: (message: any) => void;
Pass a message through the interceptor chain.
method sendMessageWithContext
sendMessageWithContext: (context: object, message: any) => void;
For streaming calls, we need to transparently pass the stream's context through the interceptor chain. Passes the context between InterceptingCalls but hides it from any requester implementations.
Parameter context
Carries objects needed for streaming operations.
Parameter message
The message to send.
method start
start: (metadata: Metadata, listener: Listener) => void;
Starts a call through the outbound interceptor chain and adds an element to the reciprocal inbound listener chain.
class ListenerBuilder
class ListenerBuilder {}
A builder for listener interceptors
constructor
constructor();
method build
build: () => Listener;
Builds the call listener
method withOnReceiveMessage
withOnReceiveMessage: (onReceiveMessage: MessageListener) => this;
Adds onReceiveMessage method to the builder
Parameter onReceiveMessage
A listener method for receiving message
method withOnReceiveMetadata
withOnReceiveMetadata: (onReceiveMetadata: MetadataListener) => this;
Adds onReceiveMetadata method to the builder
Parameter onReceiveMetadata
A listener method for receiving metadata
method withOnReceiveStatus
withOnReceiveStatus: (onReceiveStatus: StatusListener) => this;
Adds onReceiveStatus method to the builder
Parameter onReceiveStatus
A listener method for receiving status
class Metadata
class Metadata {}
A class for storing metadata. Keys are normalized to lowercase ASCII.
constructor
constructor(options?: MetadataOptions);
Parameter options
Boolean options for the beginning of the call. These options only have any effect when passed at the beginning of a client request.
method add
add: (key: string, value: MetadataValue) => void;
Adds the given value for the given key by appending to a list of previous values associated with that key. Normalizes the key.
Parameter key
The key for which a new value should be appended.
Parameter value
The value to add. Must be a buffer if and only if the normalized key ends with '-bin'.
method clone
clone: () => Metadata;
Clones the metadata object. The newly cloned object.
method get
get: (key: string) => MetadataValue[];
Gets a list of all values associated with the key. Normalizes the key.
Parameter key
The key whose value should be retrieved. A list of values associated with the given key.
method getMap
getMap: () => { [key: string]: any };
Gets a plain object mapping each key to the first value associated with it. This reflects the most common way that people will want to see metadata. A key/value mapping of the metadata.
method remove
remove: (key: string) => void;
Removes the given key and any associated values. Normalizes the key.
Parameter key
The key whose values should be removed.
method set
set: (key: string, value: MetadataValue) => void;
Sets the given value for the given key by replacing any other values associated with that key. Normalizes the key.
Parameter key
The key to whose value should be set.
Parameter value
The value to set. Must be a buffer if and only if the normalized key ends with '-bin'.
method setOptions
setOptions: (options: MetadataOptions) => void;
Set options on the metadata object
Parameter options
Boolean options for the beginning of the call. These options only have any effect when passed at the beginning of a client request.
class RequesterBuilder
class RequesterBuilder {}
A builder for the outbound methods of an interceptor
constructor
constructor();
method build
build: () => Requester;
Builds the requester's interceptor methods.
method withCancel
withCancel: (cancel: CancelRequester) => this;
Add a cancel requester to the builder.
Parameter cancel
A requester method for handling
cancel
method withHalfClose
withHalfClose: (halfClose: CloseRequester) => this;
Add a close requester to the builder.
Parameter halfClose
A requester method for handling client close.
method withSendMessage
withSendMessage: (sendMessage: MessageRequester) => this;
Add a message requester to the builder.
Parameter sendMessage
A requester method for handling messages.
method withStart
withStart: (start: MetadataRequester) => this;
Add a metadata requester to the builder
Parameter start
A requester method for handling metadata
class Server
class Server {}
Server object that stores request handlers and delegates incoming requests to those handlers
constructor
constructor(options?: {});
Constructs a server object that stores request handlers and delegates incoming requests to those handlers
Parameter options
Options that should be passed to the internal server implementation
var server = new grpc.Server();server.addProtoService(protobuf_service_descriptor, service_implementation);server.bind('address:port', server_credential);server.start();
method addProtoService
addProtoService: <ImplementationType = UntypedServiceImplementation>( service: ServiceDefinition<ImplementationType>, implementation: ImplementationType) => void;
Add a proto service to the server, with a corresponding implementation
Parameter service
The proto service descriptor
Parameter implementation
Map of method names to method implementation for the provided service.
Deprecated
Use
Server#addService
instead
method addService
addService: <ImplementationType = UntypedServiceImplementation>( service: ServiceDefinition<ImplementationType>, implementation: ImplementationType) => void;
Add a service to the server, with a corresponding implementation.
Parameter service
The service descriptor
Parameter implementation
Map of method names to method implementation for the provided service.
method bind
bind: (port: string, creds: ServerCredentials) => number;
Binds the server to the given port, with SSL disabled if creds is an insecure credentials object
Parameter port
The port that the server should bind on, in the format "address:port"
Parameter creds
Server credential object to be used for SSL. Pass an insecure credentials object for an insecure port. The bound port number or 0 if the operation failed.
method bindAsync
bindAsync: ( port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void) => void;
Binds the server to the given port, with SSL disabled if creds is an insecure credentials object. Provides the result asynchronously.
Parameter port
The port that the server should bind on, in the format "address:port"
Parameter creds
Server credential object to be used for SSL. Pass an insecure credentials object for an insecure port.
Parameter callback
Called with the result of attempting to bind a port - error: If non-null, indicates that binding the port failed. - port: The bound port number. If binding the port fails, this will be negative to match the output of bind.
method forceShutdown
forceShutdown: () => void;
Forcibly shuts down the server. The server will stop receiving new calls and cancel all pending calls. When it returns, the server has shut down. This method is idempotent with itself and tryShutdown, and it will trigger any outstanding tryShutdown callbacks.
method register
register: <RequestType, ResponseType>( name: string, handler: handleCall<RequestType, ResponseType>, serialize: serialize<ResponseType>, deserialize: deserialize<RequestType>, type: string) => boolean;
Registers a handler to handle the named method. Fails if there already is a handler for the given method. Returns true on success
Parameter name
The name of the method that the provided function should handle/respond to.
Parameter handler
Function that takes a stream of request values and returns a stream of response values
Parameter serialize
Serialization function for responses
Parameter deserialize
Deserialization function for requests
Parameter type
The streaming type of method that this handles True if the handler was set. False if a handler was already set for that name.
method start
start: () => void;
Start the server and begin handling requests
method tryShutdown
tryShutdown: (callback: () => void) => void;
Gracefully shuts down the server. The server will stop receiving new calls, and any pending calls will complete. The callback will be called when all pending calls have completed and the server is fully shut down. This method is idempotent with itself and forceShutdown.
Parameter callback
The shutdown complete callback
class ServerCredentials
class ServerCredentials {}
ServerCredentials factories
method createInsecure
static createInsecure: () => ServerCredentials;
Create insecure server credentials The ServerCredentials
method createSsl
static createSsl: ( rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean) => ServerCredentials;
Create SSL server credentials
Parameter rootCerts
Root CA certificates for validating client certificates
Parameter keyCertPairs
A list of private key and certificate chain pairs to be used for authenticating the server
Parameter checkClientCertificate
Indicates that the server should request and verify the client's certificates. Defaults to
false
. The ServerCredentials
class ServerDuplexStream
class ServerDuplexStream<RequestType, ResponseType> extends Duplex {}
A stream that the server can read from or write to. Used for calls with duplex streaming.
property cancelled
cancelled: boolean;
Indicates if the call has been cancelled
property metadata
metadata: Metadata;
The request metadata from the client
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method sendMetadata
sendMetadata: (responseMetadata: Metadata) => void;
Send the initial metadata for a writable stream.
Parameter responseMetadata
Metadata to send
class ServerReadableStream
class ServerReadableStream<RequestType> extends Readable {}
A stream that the server can read from. Used for calls that are streaming from the client side.
property cancelled
cancelled: boolean;
Indicates if the call has been cancelled
property metadata
metadata: Metadata;
The request metadata from the client
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method sendMetadata
sendMetadata: (responseMetadata: Metadata) => void;
Send the initial metadata for a writable stream.
Parameter responseMetadata
Metadata to send
class ServerUnaryCall
class ServerUnaryCall<RequestType> extends EventEmitter {}
An EventEmitter. Used for unary calls.
property cancelled
cancelled: boolean;
Indicates if the call has been cancelled
property metadata
metadata: Metadata;
The request metadata from the client
property request
request: {};
The request message from the client
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method sendMetadata
sendMetadata: (responseMetadata: Metadata) => void;
Send the initial metadata for a writable stream.
Parameter responseMetadata
Metadata to send
class ServerWritableStream
class ServerWritableStream<RequestType, ResponseType = unknown> extends Writable {}
A stream that the server can write to. Used for calls that are streaming from the server side.
property cancelled
cancelled: boolean;
Indicates if the call has been cancelled
property metadata
metadata: Metadata;
The request metadata from the client
property request
request: {};
The request message from the client
method getPeer
getPeer: () => string;
Get the endpoint this call/stream is connected to. The URI of the endpoint
method sendMetadata
sendMetadata: (responseMetadata: Metadata) => void;
Send the initial metadata for a writable stream.
Parameter responseMetadata
Metadata to send
class StatusBuilder
class StatusBuilder {}
A builder for gRPC status objects
constructor
constructor();
method build
build: () => StatusObject;
Builds the status object A gRPC status
method withCode
withCode: (code: number) => this;
Adds a status code to the builder
Parameter code
The status code
method withDetails
withDetails: (details: string) => this;
Adds details to the builder
Parameter details
A status message
method withMetadata
withMetadata: (metadata: Metadata) => this;
Adds metadata to the builder
Parameter metadata
The gRPC status metadata
interface CallCredentials
interface CallCredentials {}
This cannot be constructed directly. Instead, instances of this class should be created using the factory functions in
grpc.credentials
method compose
compose: (callCredentials: CallCredentials) => CallCredentials;
Creates a new CallCredentials object from properties of both this and another CallCredentials object. This object's metadata generator will be called first.
Parameter callCredentials
The other CallCredentials object.
method generateMetadata
generateMetadata: (options: object) => Promise<Metadata>;
Asynchronously generates a new Metadata object.
Parameter options
Options used in generating the Metadata object.
interface CallOptions
interface CallOptions {}
Options that can be set on a call.
property credentials
credentials?: CallCredentials;
The credentials that should be used to make this particular call.
property deadline
deadline?: Deadline;
The deadline for the entire call to complete.
property host
host?: string;
Server hostname to set on the call. Only meaningful if different from the server address used to construct the client.
property parent
parent?: Call;
Parent call. Used in servers when making a call as part of the process of handling a call. Used to propagate some information automatically, as specified by propagate_flags.
property propagate_flags
propagate_flags?: number;
Indicates which properties of a parent call should propagate to this call. Bitwise combination of flags in
grpc.propagate
.
index signature
[key: string]: any;
Additional custom call options. These can be used to pass additional data per-call to client interceptors
interface Certificate
interface Certificate {}
A certificate as received by the checkServerIdentity callback.
property raw
raw: Buffer;
The raw certificate in DER form.
interface ChannelCredentials
interface ChannelCredentials {}
This cannot be constructed directly. Instead, instances of this class should be created using the factory functions in
grpc.credentials
method compose
compose: (callCredentials: CallCredentials) => ChannelCredentials;
Returns a copy of this object with the included set of per-call credentials expanded to include callCredentials.
Parameter callCredentials
A CallCredentials object to associate with this instance.
interface GenericClientOptions
interface GenericClientOptions {}
Options for generic client constructor.
property deprecatedArgumentOrder
deprecatedArgumentOrder?: boolean;
Indicates that the old argument order should be used for methods, with optional arguments at the end instead of the callback at the end. This option is only a temporary stopgap measure to smooth an API breakage. It is deprecated, and new code should not use it.
interface GoogleOAuth2Client
interface GoogleOAuth2Client {}
This is the required interface from the OAuth2Client object from https://github.com/google/google-auth-library-nodejs lib. The definition is copied from
ts/lib/auth/oauth2client.ts
method getRequestMetadata
getRequestMetadata: ( optUri: string, metadataCallback: (err: Error, headers: any) => void) => void;
interface GrpcObject
interface GrpcObject {}
Map from
.proto
file. - Namespaces become maps from the names of their direct members to those member objects - Service definitions become client constructors for clients for that service. They also have a service member that can be used for constructing servers. - Message definitions become Message constructors like those that ProtoBuf.js would create - Enum definitions become Enum objects like those that ProtoBuf.js would create - Anything else becomes the relevant reflection object that ProtoBuf.js would create
index signature
[name: string]: GrpcObject | typeof Client | ProtobufMessage;
interface KeyCertPair
interface KeyCertPair {}
A private key and certificate pair
property cert_chain
cert_chain: Buffer;
The server's certificate chain
property private_key
private_key: Buffer;
The server's private key
interface Listener
interface Listener {}
property onReceiveMessage
onReceiveMessage?: MessageListener;
property onReceiveMetadata
onReceiveMetadata?: MetadataListener;
property onReceiveStatus
onReceiveStatus?: StatusListener;
interface LoadObjectOptions
interface LoadObjectOptions {}
Options for loading proto object as gRPC object
Parameter
{(number|string)=} [options.protobufjsVersion='detect'] 5 and 6 respectively indicate that an object from the corresponding version of Protobuf.js is provided in the value argument. If the option is 'detect', gRPC will guess what the version is based on the structure of the value.
property binaryAsBase64
binaryAsBase64?: boolean;
Deserialize bytes values as base64 strings instead of Buffers. Defaults to
false
.
property deprecatedArgumentOrder
deprecatedArgumentOrder?: boolean;
use the beta method argument order for client methods, with optional arguments after the callback. This option is only a temporary stopgap measure to smooth an API breakage. It is deprecated, and new code should not use it. Defaults to
false
property enumsAsStrings
enumsAsStrings?: boolean;
Deserialize enum values as strings instead of numbers. Only works with Protobuf.js 6 values. Defaults to
true
.
property longsAsStrings
longsAsStrings?: boolean;
Deserialize long values as strings instead of objects. Defaults to
true
.
property protobufjsVersion
protobufjsVersion?: 5 | 6 | 'detect';
5 and 6 respectively indicate that an object from the corresponding version of Protobuf.js is provided in the value argument. If the option is 'detect', gRPC wll guess what the version is based on the structure of the value.
interface LoadOptions
interface LoadOptions {}
Options for loading proto file as gRPC object
property binaryAsBase64
binaryAsBase64?: boolean;
Deserialize bytes values as base64 strings instead of Buffers. Defaults to
false
.
property convertFieldsToCamelCase
convertFieldsToCamelCase?: boolean;
Load this file with field names in camel case instead of their original case. Defaults to
false
.
property deprecatedArgumentOrder
deprecatedArgumentOrder?: boolean;
Use the beta method argument order for client methods, with optional arguments after the callback. This option is only a temporary stopgap measure to smooth an API breakage. It is deprecated, and new code should not use it. Defaults to
false
property longsAsStrings
longsAsStrings?: boolean;
Deserialize long values as strings instead of objects. Defaults to
true
.
interface MetadataOptions
interface MetadataOptions {}
property cacheableRequest
cacheableRequest?: boolean;
property corked
corked?: boolean;
property idempotentRequest
idempotentRequest?: boolean;
property waitForReady
waitForReady?: boolean;
interface MethodDefinition
interface MethodDefinition<RequestType, ResponseType> {}
An object that completely defines a service method signature.
property path
path: string;
The method's URL path
property requestDeserialize
requestDeserialize: deserialize<RequestType>;
Deserialization function for request data
property requestSerialize
requestSerialize: serialize<RequestType>;
Serialization function for request values
property requestStream
requestStream: boolean;
Indicates whether the method accepts a stream of requests
property responseDeserialize
responseDeserialize: deserialize<ResponseType>;
Deserialization function for repsonse data
property responseSerialize
responseSerialize: serialize<ResponseType>;
Serialization function for response values
property responseStream
responseStream: boolean;
Indicates whether the method returns a stream of responses
interface ProtobufMessage
interface ProtobufMessage {}
method $add
$add: (key: string, value: any, noAssert?: boolean) => ProtobufMessage;
method $get
$get: <T>(key: string) => T;
method $set
$set: ( key: string | { [key: string]: any }, value?: any | boolean, noAssert?: boolean) => void;
method add
add: (key: string, value: any, noAssert?: boolean) => ProtobufMessage;
method calculate
calculate: () => number;
method encode
encode: (buffer?: ByteBuffer | boolean, noVerify?: boolean) => ByteBuffer;
method encode64
encode64: () => string;
method encodeAB
encodeAB: () => ArrayBuffer;
method encodeDelimited
encodeDelimited: ( buffer?: ByteBuffer | boolean, noVerify?: boolean) => ByteBuffer;
method encodeHex
encodeHex: () => string;
method encodeJSON
encodeJSON: () => string;
method encodeNB
encodeNB: () => Buffer;
method get
get: <T>(key: string, noAssert?: boolean) => T;
method set
set: ( key: string | { [key: string]: any }, value?: any | boolean, noAssert?: boolean) => void;
method toArrayBuffer
toArrayBuffer: () => ArrayBuffer;
method toBase64
toBase64: () => string;
method toBuffer
toBuffer: () => Buffer;
method toHex
toHex: () => string;
method toRaw
toRaw: ( binaryAsBase64?: boolean, longsAsStrings?: boolean) => { [key: string]: any };
method toString
toString: () => string;
index signature
[field: string]: any;
interface ProtobufTypeDefinition
interface ProtobufTypeDefinition {}
An object that defines a protobuf type
property fileDescriptorProtos
fileDescriptorProtos: Buffer[];
property format
format: string;
property type
type: object;
interface Requester
interface Requester {}
property cancel
cancel?: CancelRequester;
property getPeer
getPeer?: GetPeerRequester;
property halfClose
halfClose?: CloseRequester;
property sendMessage
sendMessage?: MessageRequester;
property start
start?: MetadataRequester;
interface ServiceError
interface ServiceError extends Error {}
Describes how a request has failed. The member
message
will be the same asdetails
inStatusObject
, andcode
andmetadata
are the same as in that object.
property code
code?: status;
The error code, a key of grpc.status that is not
grpc.status.OK
property details
details?: string;
Original status details string
property metadata
metadata?: Metadata;
Trailing metadata sent with the status, if applicable
interface StatusObject
interface StatusObject {}
Represents the status of a completed request. If
code
isgrpc.status.OK
, then the request has completed successfully. Otherwise, the request has failed,details
will contain a description of the error. Either way,metadata
contains the trailing response metadata sent by the server when it finishes processing the call.
interface VerifyOptions
interface VerifyOptions {}
Additional peer verification options that can be set when creating SSL credentials.
property checkServerIdentity
checkServerIdentity?: CheckServerIdentityCallback;
If set, this callback will be invoked after the usual hostname verification has been performed on the peer certificate.
enum callError
enum callError { OK, ERROR, NOT_ON_SERVER, NOT_ON_CLIENT, ALREADY_INVOKED, NOT_INVOKED, ALREADY_FINISHED, TOO_MANY_OPERATIONS, INVALID_FLAGS, INVALID_METADATA, INVALID_MESSAGE, NOT_SERVER_COMPLETION_QUEUE, BATCH_TOO_BIG, PAYLOAD_TYPE_MISMATCH,}
Call error constants. Call errors almost always indicate bugs in the gRPC library, and these error codes are mainly useful for finding those bugs.
member ALREADY_FINISHED
ALREADY_FINISHED
member ALREADY_INVOKED
ALREADY_INVOKED
member BATCH_TOO_BIG
BATCH_TOO_BIG
member ERROR
ERROR
member INVALID_FLAGS
INVALID_FLAGS
member INVALID_MESSAGE
INVALID_MESSAGE
member INVALID_METADATA
INVALID_METADATA
member NOT_INVOKED
NOT_INVOKED
member NOT_ON_CLIENT
NOT_ON_CLIENT
member NOT_ON_SERVER
NOT_ON_SERVER
member NOT_SERVER_COMPLETION_QUEUE
NOT_SERVER_COMPLETION_QUEUE
member OK
OK
member PAYLOAD_TYPE_MISMATCH
PAYLOAD_TYPE_MISMATCH
member TOO_MANY_OPERATIONS
TOO_MANY_OPERATIONS
enum connectivityState
enum connectivityState { IDLE = 0, CONNECTING = 1, READY = 2, TRANSIENT_FAILURE = 3, SHUTDOWN = 4,}
member CONNECTING
CONNECTING = 1
member IDLE
IDLE = 0
member READY
READY = 2
member SHUTDOWN
SHUTDOWN = 4
member TRANSIENT_FAILURE
TRANSIENT_FAILURE = 3
enum logVerbosity
enum logVerbosity { DEBUG, INFO, ERROR,}
Log verbosity constants. Maps setting names to code numbers.
enum methodTypes
enum methodTypes { UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING,}
Method type constants
member BIDI_STREAMING
BIDI_STREAMING
member CLIENT_STREAMING
CLIENT_STREAMING
member SERVER_STREAMING
SERVER_STREAMING
member UNARY
UNARY
enum propagate
enum propagate { DEADLINE, CENSUS_STATS_CONTEXT, CENSUS_TRACING_CONTEXT, CANCELLATION, DEFAULTS,}
Propagation flags: these can be bitwise or-ed to form the propagation option for calls.
Users are encouraged to write propagation masks as deltas from the default. i.e. write
grpc.propagate.DEFAULTS & ~grpc.propagate.DEADLINE
to disable deadline propagation.
member CANCELLATION
CANCELLATION
member CENSUS_STATS_CONTEXT
CENSUS_STATS_CONTEXT
member CENSUS_TRACING_CONTEXT
CENSUS_TRACING_CONTEXT
member DEADLINE
DEADLINE
member DEFAULTS
DEFAULTS
enum status
enum status { OK = 0, CANCELLED = 1, UNKNOWN = 2, INVALID_ARGUMENT = 3, DEADLINE_EXCEEDED = 4, NOT_FOUND = 5, ALREADY_EXISTS = 6, PERMISSION_DENIED = 7, RESOURCE_EXHAUSTED = 8, FAILED_PRECONDITION = 9, ABORTED = 10, OUT_OF_RANGE = 11, UNIMPLEMENTED = 12, INTERNAL = 13, UNAVAILABLE = 14, DATA_LOSS = 15, UNAUTHENTICATED = 16,}
Enum of status codes that gRPC can return
member ABORTED
ABORTED = 10
The operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.
See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
member ALREADY_EXISTS
ALREADY_EXISTS = 6
Some entity that we attempted to create (e.g., file or directory) already exists.
member CANCELLED
CANCELLED = 1
The operation was cancelled (typically by the caller).
member DATA_LOSS
DATA_LOSS = 15
Unrecoverable data loss or corruption.
member DEADLINE_EXCEEDED
DEADLINE_EXCEEDED = 4
Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.
member FAILED_PRECONDITION
FAILED_PRECONDITION = 9
Operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc.
A litmus test that may help a service implementor in deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
- Use UNAVAILABLE if the client can retry just the failing call. - Use ABORTED if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence). - Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FAILED_PRECONDITION should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it. - Use FAILED_PRECONDITION if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource.
member INTERNAL
INTERNAL = 13
Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken.
member INVALID_ARGUMENT
INVALID_ARGUMENT = 3
Client specified an invalid argument. Note that this differs from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
member NOT_FOUND
NOT_FOUND = 5
Some requested entity (e.g., file or directory) was not found.
member OK
OK = 0
Not an error; returned on success
member OUT_OF_RANGE
OUT_OF_RANGE = 11
Operation was attempted past the valid range. E.g., seeking or reading past end of file.
Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate INVALID_ARGUMENT if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from an offset past the current file size.
There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OUT_OF_RANGE error to detect when they are done.
member PERMISSION_DENIED
PERMISSION_DENIED = 7
The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors). PERMISSION_DENIED must not be used if the caller can not be identified (use UNAUTHENTICATED instead for those errors).
member RESOURCE_EXHAUSTED
RESOURCE_EXHAUSTED = 8
Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
member UNAUTHENTICATED
UNAUTHENTICATED = 16
The request does not have valid authentication credentials for the operation.
member UNAVAILABLE
UNAVAILABLE = 14
The service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff.
See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.
member UNIMPLEMENTED
UNIMPLEMENTED = 12
Operation is not implemented or not supported/enabled in this service.
member UNKNOWN
UNKNOWN = 2
Unknown error. An example of where this error may be returned is if a status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
enum writeFlags
enum writeFlags { BUFFER_HINT = 1, NO_COMPRESS,}
Write flags: these can be bitwise or-ed to form write options that modify how data is written.
member BUFFER_HINT
BUFFER_HINT = 1
Hint that the write may be buffered and need not go out on the wire immediately. GRPC is free to buffer the message until the next non-buffered write, or until writes_done, but it need not buffer completely or at all.
member NO_COMPRESS
NO_COMPRESS
Force compression to be disabled for a particular write
type Call
type Call = | ClientUnaryCall | ClientReadableStream<any> | ClientWritableStream<any> | ClientDuplexStream<any, any>;
Any client call type
type CancelRequester
type CancelRequester = (next: Function) => void;
type CheckServerIdentityCallback
type CheckServerIdentityCallback = ( hostname: string, cert: Certificate) => Error | undefined;
A callback that will receive the expected hostname and presented peer certificate as parameters. The callback should return an error to indicate that the presented certificate is considered invalid and otherwise returned undefined.
type CloseRequester
type CloseRequester = (next: Function) => void;
type Deadline
type Deadline = number | Date;
The deadline of an operation. If it is a date, the deadline is reached at the date and time specified. If it is a finite number, it is treated as a number of milliseconds since the Unix Epoch. If it is Infinity, the deadline will never be reached. If it is -Infinity, the deadline has already passed.
type deserialize
type deserialize<T> = (data: Buffer) => T;
A deserialization function
Parameter data
The byte sequence to deserialize The data deserialized as a value
type Filename
type Filename = string | { root: string; file: string };
A filename
type GetPeerRequester
type GetPeerRequester = (next: Function) => string;
type handleBidiStreamingCall
type handleBidiStreamingCall<RequestType, ResponseType> = ( call: ServerDuplexStream<RequestType, ResponseType>) => void;
User provided method to handle bidirectional streaming calls on the server.
type handleCall
type handleCall<RequestType, ResponseType> = | handleUnaryCall<RequestType, ResponseType> | handleClientStreamingCall<RequestType, ResponseType> | handleServerStreamingCall<RequestType, ResponseType> | handleBidiStreamingCall<RequestType, ResponseType>;
type handleClientStreamingCall
type handleClientStreamingCall<RequestType, ResponseType> = ( call: ServerReadableStream<RequestType>, callback: sendUnaryData<ResponseType>) => void;
User provided method to handle client streaming methods on the server.
type handleServerStreamingCall
type handleServerStreamingCall<RequestType, ResponseType> = ( call: ServerWritableStream<RequestType, ResponseType>) => void;
User provided method to handle server streaming methods on the server.
type handleUnaryCall
type handleUnaryCall<RequestType, ResponseType> = ( call: ServerUnaryCall<RequestType>, callback: sendUnaryData<ResponseType>) => void;
User-provided method to handle unary requests on a server
type MessageListener
type MessageListener = (message: any, next: Function) => void;
type MessageRequester
type MessageRequester = (message: any, next: Function) => void;
type metadataGenerator
type metadataGenerator = ( params: { service_url: string }, callback: (error: Error | null, metadata?: Metadata) => void) => void;
Metadata generator function.
type MetadataListener
type MetadataListener = (metadata: Metadata, next: Function) => void;
type MetadataRequester
type MetadataRequester = ( metadata: Metadata, listener: Listener, next: Function) => void;
type MetadataValue
type MetadataValue = string | Buffer;
type PackageDefinition
type PackageDefinition = { readonly [fullyQualifiedName: string]: | ServiceDefinition<any> | ProtobufTypeDefinition;};
An object that defines a package containing multiple services
type requestCallback
type requestCallback<ResponseType> = ( error: ServiceError | null, value?: ResponseType) => void;
Client request callback
Parameter error
The error, if the call failed
Parameter value
The response value, if the call succeeded
type sendUnaryData
type sendUnaryData<ResponseType> = ( error: ServiceError | null, value: ResponseType | null, trailer?: Metadata, flags?: number) => void;
Callback function passed to server handlers that handle methods with unary responses.
type serialize
type serialize<T> = (value: T) => Buffer;
A serialization function
Parameter value
The value to serialize The value serialized as a byte sequence
type ServerWriteableStream
type ServerWriteableStream< RequestType, ResponseType = unknown> = ServerWritableStream<RequestType, ResponseType>;
type ServiceDefinition
type ServiceDefinition<ImplementationType = UntypedServiceImplementation> = { readonly [I in keyof ImplementationType]: MethodDefinition<any, any>;};
An object that completely defines a service.
type StatusListener
type StatusListener = (status: StatusObject, next: Function) => void;
type UntypedServiceImplementation
type UntypedServiceImplementation = { [name: string]: handleCall<any, any> };
A type that servers as a default for an untyped service.
Package Files (1)
Dependencies (6)
Dev Dependencies (9)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/grpc
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/grpc)
- HTML<a href="https://www.jsdocs.io/package/grpc"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6023 ms. - Missing or incorrect documentation? Open an issue for this package.