3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 var constants = require('./constants');
24 * Wrap a function to pass null-like values through without calling it. If no
25 * function is given, just uses the identity.
27 * @param {?function} func The function to wrap
28 * @return {function} The wrapped function
30 exports.wrapIgnoreNull = function wrapIgnoreNull(func) {
34 return function(arg) {
35 if (arg === null || arg === undefined) {
43 * The logger object for the gRPC module. Defaults to console.
46 exports.logger = console;
49 * The current logging verbosity. 0 corresponds to logging everything
52 exports.logVerbosity = 0;
55 * Log a message if the severity is at least as high as the current verbosity
57 * @param {Number} severity A value of the grpc.logVerbosity map
58 * @param {String} message The message to log
60 exports.log = function log(severity, message) {
61 if (severity >= exports.logVerbosity) {
62 exports.logger.error(message);
67 * Default options for loading proto files into gRPC
68 * @alias grpc~defaultLoadOptions
70 exports.defaultGrpcOptions = {
71 convertFieldsToCamelCase: false,
72 binaryAsBase64: false,
75 deprecatedArgumentOrder: false
79 * Create an Error object from a status object
80 * @param {grpc~StatusObject} status The status object
81 * @return {Error} The resulting Error
83 exports.createStatusError = function(status) {
84 let inverted = Object.keys(constants.status)
85 .reduce((acc, key) => {
86 acc[constants.status[key]] = key;
89 let statusName = inverted[status.code];
90 let message = `${status.code} ${statusName}: ${status.details}`;
91 let error = new Error(message);
92 error.code = status.code;
93 error.metadata = status.metadata;
94 error.details = status.details;
99 * Get a method's type from its definition
100 * @param {grpc~MethodDefinition} method_definition
103 exports.getMethodType = function(method_definition) {
104 if (method_definition.requestStream) {
105 if (method_definition.responseStream) {
106 return constants.methodTypes.BIDI_STREAMING;
108 return constants.methodTypes.CLIENT_STREAMING;
111 if (method_definition.responseStream) {
112 return constants.methodTypes.SERVER_STREAMING;
114 return constants.methodTypes.UNARY;
120 * Iterate over a collection of items, and run the given handler.
121 * Return the results as a flattened array of values.
125 * @param {Array} collection Array of items to process
126 * @param {Function} handler The function to call on each element in the array
127 * @return {Array} A flattened array of results.
129 exports.flatMap = function(collection, handler) {
130 const mapped = collection.map(handler);
131 return mapped.reduce((acc, curr) => acc.concat(curr), []);
135 * Given an array of property names and an array of values,
136 * combine the two into an object map.
137 * Equivalent to _.zipObject.
141 * @param props {Array<String>} Array of property names
142 * @param values {Array} Array of property values
143 * @return {Object} An object with the combined values
145 exports.zipObject = function(props, values) {
146 return props.reduce((acc, curr, idx) => {
147 return Object.assign(acc, { [curr]: values[idx] });
152 * Returns true, if given key is included in the blacklisted
154 * @param key {String} key for check, string.
157 exports.isPrototypePolluted = function(key) {
158 return ['__proto__', 'prototype', 'constructor'].indexOf(key) >= 0;
161 // JSDoc definitions that are used in multiple other modules
164 * Represents the status of a completed request. If `code` is
165 * {@link grpc.status}.OK, then the request has completed successfully.
166 * Otherwise, the request has failed, `details` will contain a description of
167 * the error. Either way, `metadata` contains the trailing response metadata
168 * sent by the server when it finishes processing the call.
169 * @typedef {object} grpc~StatusObject
170 * @property {number} code The error code, a key of {@link grpc.status}
171 * @property {string} details Human-readable description of the status
172 * @property {grpc.Metadata} metadata Trailing metadata sent with the status,
177 * Describes how a request has failed. The member `message` will be the same as
178 * `details` in {@link grpc~StatusObject}, and `code` and `metadata` are the
179 * same as in that object.
180 * @typedef {Error} grpc~ServiceError
181 * @property {number} code The error code, a key of {@link grpc.status} that is
182 * not `grpc.status.OK`
183 * @property {grpc.Metadata} metadata Trailing metadata sent with the status,
188 * The EventEmitter class in the event standard module
189 * @external EventEmitter
190 * @see https://nodejs.org/api/events.html#events_class_eventemitter
194 * The Readable class in the stream standard module
196 * @see https://nodejs.org/api/stream.html#stream_readable_streams
200 * The Writable class in the stream standard module
202 * @see https://nodejs.org/api/stream.html#stream_writable_streams
206 * The Duplex class in the stream standard module
208 * @see https://nodejs.org/api/stream.html#stream_class_stream_duplex
212 * A serialization function
213 * @callback grpc~serialize
214 * @param {*} value The value to serialize
215 * @return {Buffer} The value serialized as a byte sequence
219 * A deserialization function
220 * @callback grpc~deserialize
221 * @param {Buffer} data The byte sequence to deserialize
222 * @return {*} The data deserialized as a value
226 * The deadline of an operation. If it is a date, the deadline is reached at
227 * the date and time specified. If it is a finite number, it is treated as
228 * a number of milliseconds since the Unix Epoch. If it is Infinity, the
229 * deadline will never be reached. If it is -Infinity, the deadline has already
231 * @typedef {(number|Date)} grpc~Deadline
235 * An object that completely defines a service method signature.
236 * @typedef {Object} grpc~MethodDefinition
237 * @property {string} path The method's URL path
238 * @property {boolean} requestStream Indicates whether the method accepts
239 * a stream of requests
240 * @property {boolean} responseStream Indicates whether the method returns
241 * a stream of responses
242 * @property {grpc~serialize} requestSerialize Serialization
243 * function for request values
244 * @property {grpc~serialize} responseSerialize Serialization
245 * function for response values
246 * @property {grpc~deserialize} requestDeserialize Deserialization
247 * function for request data
248 * @property {grpc~deserialize} responseDeserialize Deserialization
249 * function for repsonse data
253 * @function MetadataListener
254 * @param {grpc.Metadata} metadata The response metadata.
255 * @param {function} next Passes metadata to the next interceptor.
259 * @function MessageListener
260 * @param {jspb.Message} message The response message.
261 * @param {function} next Passes a message to the next interceptor.
265 * @function StatusListener
266 * @param {grpc~StatusObject} status The response status.
267 * @param {function} next Passes a status to the next interceptor.
271 * A set of interceptor functions triggered by responses
272 * @typedef {object} grpc~Listener
273 * @property {MetadataListener=} onReceiveMetadata A function triggered by
275 * @property {MessageListener=} onReceiveMessage A function triggered by a
277 * @property {StatusListener=} onReceiveStatus A function triggered by a
282 * @function MetadataRequester
283 * @param {grpc.Metadata} metadata The request metadata.
284 * @param {grpc~Listener} listener A listener wired to the previous layers
285 * in the interceptor stack.
286 * @param {function} next Passes metadata and a listener to the next
291 * @function MessageRequester
292 * @param {jspb.Message} message The request message.
293 * @param {function} next Passes a message to the next interceptor.
297 * @function CloseRequester
298 * @param {function} next Calls the next interceptor.
302 * @function CancelRequester
303 * @param {function} next Calls the next interceptor.
307 * @function GetPeerRequester
308 * @param {function} next Calls the next interceptor.
313 * @typedef {object} grpc~Requester
314 * @param {MetadataRequester=} start A function triggered when the call begins.
315 * @param {MessageRequester=} sendMessage A function triggered by the request
317 * @param {CloseRequester=} halfClose A function triggered when the client
319 * @param {CancelRequester=} cancel A function triggered when the call is
321 * @param {GetPeerRequester=} getPeer A function triggered when the endpoint is
326 * An object that completely defines a service.
327 * @typedef {Object.<string, grpc~MethodDefinition>} grpc~ServiceDefinition
331 * An object that defines a protobuf type
332 * @typedef {object} grpc~ProtobufTypeDefinition
333 * @param {string} format The format of the type definition object
334 * @param {*} type The type definition object
335 * @param {Buffer[]} fileDescriptorProtos Binary protobuf file
336 * descriptors for all files loaded to construct this type
340 * An object that defines a package hierarchy with multiple services
341 * @typedef {Object.<string, grpc~ServiceDefinition|grpc~ProtobufTypeDefinition>} grpc~PackageDefinition
345 * A function for dynamically assigning an interceptor to a call.
346 * @function InterceptorProvider
347 * @param {grpc~MethodDefinition} method_definition The method to provide
348 * an interceptor for.
349 * @return {Interceptor|null} The interceptor to provide or nothing
353 * A function which can modify call options and produce methods to intercept
355 * @function Interceptor
356 * @param {object} options The grpc call options
357 * @param {NextCall} nextCall
358 * @return {InterceptingCall}
362 * A function which produces the next InterceptingCall.
364 * @param {object} options The grpc call options
365 * @return {InterceptingCall|null}