Best JavaScript code snippet using tracetest
grpctest_pb.js
Source:grpctest_pb.js
1/**2 * @fileoverview3 * @enhanceable4 * @suppress {messageConventions} JS Compiler reports an error if a variable or5 * field starts with 'MSG_' and isn't a translatable message.6 * @public7 */8// GENERATED CODE -- DO NOT EDIT!9var jspb = require('google-protobuf');10var goog = jspb;11var global = Function('return this')();12goog.exportSymbol('proto.grpcserver.GrpcHandshakeRequest', null, global);13goog.exportSymbol('proto.grpcserver.GrpcHandshakeResponse', null, global);14goog.exportSymbol('proto.grpcserver.GrpcRequest', null, global);15goog.exportSymbol('proto.grpcserver.GrpcResponse', null, global);16/**17 * Generated by JsPbCodeGenerator.18 * @param {Array=} opt_data Optional initial data array, typically from a19 * server response, or constructed directly in Javascript. The array is used20 * in place and becomes part of the constructed object. It is not cloned.21 * If no data is provided, the constructed object will be empty, but still22 * valid.23 * @extends {jspb.Message}24 * @constructor25 */26proto.grpcserver.GrpcHandshakeRequest = function(opt_data) {27 jspb.Message.initialize(this, opt_data, 0, -1, null, null);28};29goog.inherits(proto.grpcserver.GrpcHandshakeRequest, jspb.Message);30if (goog.DEBUG && !COMPILED) {31 /**32 * @public33 * @override34 */35 proto.grpcserver.GrpcHandshakeRequest.displayName = 'proto.grpcserver.GrpcHandshakeRequest';36}37/**38 * Generated by JsPbCodeGenerator.39 * @param {Array=} opt_data Optional initial data array, typically from a40 * server response, or constructed directly in Javascript. The array is used41 * in place and becomes part of the constructed object. It is not cloned.42 * If no data is provided, the constructed object will be empty, but still43 * valid.44 * @extends {jspb.Message}45 * @constructor46 */47proto.grpcserver.GrpcHandshakeResponse = function(opt_data) {48 jspb.Message.initialize(this, opt_data, 0, -1, null, null);49};50goog.inherits(proto.grpcserver.GrpcHandshakeResponse, jspb.Message);51if (goog.DEBUG && !COMPILED) {52 /**53 * @public54 * @override55 */56 proto.grpcserver.GrpcHandshakeResponse.displayName = 'proto.grpcserver.GrpcHandshakeResponse';57}58/**59 * Generated by JsPbCodeGenerator.60 * @param {Array=} opt_data Optional initial data array, typically from a61 * server response, or constructed directly in Javascript. The array is used62 * in place and becomes part of the constructed object. It is not cloned.63 * If no data is provided, the constructed object will be empty, but still64 * valid.65 * @extends {jspb.Message}66 * @constructor67 */68proto.grpcserver.GrpcRequest = function(opt_data) {69 jspb.Message.initialize(this, opt_data, 0, -1, null, null);70};71goog.inherits(proto.grpcserver.GrpcRequest, jspb.Message);72if (goog.DEBUG && !COMPILED) {73 /**74 * @public75 * @override76 */77 proto.grpcserver.GrpcRequest.displayName = 'proto.grpcserver.GrpcRequest';78}79/**80 * Generated by JsPbCodeGenerator.81 * @param {Array=} opt_data Optional initial data array, typically from a82 * server response, or constructed directly in Javascript. The array is used83 * in place and becomes part of the constructed object. It is not cloned.84 * If no data is provided, the constructed object will be empty, but still85 * valid.86 * @extends {jspb.Message}87 * @constructor88 */89proto.grpcserver.GrpcResponse = function(opt_data) {90 jspb.Message.initialize(this, opt_data, 0, -1, null, null);91};92goog.inherits(proto.grpcserver.GrpcResponse, jspb.Message);93if (goog.DEBUG && !COMPILED) {94 /**95 * @public96 * @override97 */98 proto.grpcserver.GrpcResponse.displayName = 'proto.grpcserver.GrpcResponse';99}100if (jspb.Message.GENERATE_TO_OBJECT) {101/**102 * Creates an object representation of this proto suitable for use in Soy templates.103 * Field names that are reserved in JavaScript and will be renamed to pb_name.104 * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.105 * For the list of reserved names please see:106 * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.107 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance108 * for transitional soy proto support: http://goto/soy-param-migration109 * @return {!Object}110 */111proto.grpcserver.GrpcHandshakeRequest.prototype.toObject = function(opt_includeInstance) {112 return proto.grpcserver.GrpcHandshakeRequest.toObject(opt_includeInstance, this);113};114/**115 * Static version of the {@see toObject} method.116 * @param {boolean|undefined} includeInstance Whether to include the JSPB117 * instance for transitional soy proto support:118 * http://goto/soy-param-migration119 * @param {!proto.grpcserver.GrpcHandshakeRequest} msg The msg instance to transform.120 * @return {!Object}121 * @suppress {unusedLocalVariables} f is only used for nested messages122 */123proto.grpcserver.GrpcHandshakeRequest.toObject = function(includeInstance, msg) {124 var f, obj = {125 };126 if (includeInstance) {127 obj.$jspbMessageInstance = msg;128 }129 return obj;130};131}132/**133 * Deserializes binary data (in protobuf wire format).134 * @param {jspb.ByteSource} bytes The bytes to deserialize.135 * @return {!proto.grpcserver.GrpcHandshakeRequest}136 */137proto.grpcserver.GrpcHandshakeRequest.deserializeBinary = function(bytes) {138 var reader = new jspb.BinaryReader(bytes);139 var msg = new proto.grpcserver.GrpcHandshakeRequest;140 return proto.grpcserver.GrpcHandshakeRequest.deserializeBinaryFromReader(msg, reader);141};142/**143 * Deserializes binary data (in protobuf wire format) from the144 * given reader into the given message object.145 * @param {!proto.grpcserver.GrpcHandshakeRequest} msg The message object to deserialize into.146 * @param {!jspb.BinaryReader} reader The BinaryReader to use.147 * @return {!proto.grpcserver.GrpcHandshakeRequest}148 */149proto.grpcserver.GrpcHandshakeRequest.deserializeBinaryFromReader = function(msg, reader) {150 while (reader.nextField()) {151 if (reader.isEndGroup()) {152 break;153 }154 var field = reader.getFieldNumber();155 switch (field) {156 default:157 reader.skipField();158 break;159 }160 }161 return msg;162};163/**164 * Serializes the message to binary data (in protobuf wire format).165 * @return {!Uint8Array}166 */167proto.grpcserver.GrpcHandshakeRequest.prototype.serializeBinary = function() {168 var writer = new jspb.BinaryWriter();169 proto.grpcserver.GrpcHandshakeRequest.serializeBinaryToWriter(this, writer);170 return writer.getResultBuffer();171};172/**173 * Serializes the given message to binary data (in protobuf wire174 * format), writing to the given BinaryWriter.175 * @param {!proto.grpcserver.GrpcHandshakeRequest} message176 * @param {!jspb.BinaryWriter} writer177 * @suppress {unusedLocalVariables} f is only used for nested messages178 */179proto.grpcserver.GrpcHandshakeRequest.serializeBinaryToWriter = function(message, writer) {180 var f = undefined;181};182if (jspb.Message.GENERATE_TO_OBJECT) {183/**184 * Creates an object representation of this proto suitable for use in Soy templates.185 * Field names that are reserved in JavaScript and will be renamed to pb_name.186 * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.187 * For the list of reserved names please see:188 * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.189 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance190 * for transitional soy proto support: http://goto/soy-param-migration191 * @return {!Object}192 */193proto.grpcserver.GrpcHandshakeResponse.prototype.toObject = function(opt_includeInstance) {194 return proto.grpcserver.GrpcHandshakeResponse.toObject(opt_includeInstance, this);195};196/**197 * Static version of the {@see toObject} method.198 * @param {boolean|undefined} includeInstance Whether to include the JSPB199 * instance for transitional soy proto support:200 * http://goto/soy-param-migration201 * @param {!proto.grpcserver.GrpcHandshakeResponse} msg The msg instance to transform.202 * @return {!Object}203 * @suppress {unusedLocalVariables} f is only used for nested messages204 */205proto.grpcserver.GrpcHandshakeResponse.toObject = function(includeInstance, msg) {206 var f, obj = {207 userid: jspb.Message.getFieldWithDefault(msg, 1, "")208 };209 if (includeInstance) {210 obj.$jspbMessageInstance = msg;211 }212 return obj;213};214}215/**216 * Deserializes binary data (in protobuf wire format).217 * @param {jspb.ByteSource} bytes The bytes to deserialize.218 * @return {!proto.grpcserver.GrpcHandshakeResponse}219 */220proto.grpcserver.GrpcHandshakeResponse.deserializeBinary = function(bytes) {221 var reader = new jspb.BinaryReader(bytes);222 var msg = new proto.grpcserver.GrpcHandshakeResponse;223 return proto.grpcserver.GrpcHandshakeResponse.deserializeBinaryFromReader(msg, reader);224};225/**226 * Deserializes binary data (in protobuf wire format) from the227 * given reader into the given message object.228 * @param {!proto.grpcserver.GrpcHandshakeResponse} msg The message object to deserialize into.229 * @param {!jspb.BinaryReader} reader The BinaryReader to use.230 * @return {!proto.grpcserver.GrpcHandshakeResponse}231 */232proto.grpcserver.GrpcHandshakeResponse.deserializeBinaryFromReader = function(msg, reader) {233 while (reader.nextField()) {234 if (reader.isEndGroup()) {235 break;236 }237 var field = reader.getFieldNumber();238 switch (field) {239 case 1:240 var value = /** @type {string} */ (reader.readString());241 msg.setUserid(value);242 break;243 default:244 reader.skipField();245 break;246 }247 }248 return msg;249};250/**251 * Serializes the message to binary data (in protobuf wire format).252 * @return {!Uint8Array}253 */254proto.grpcserver.GrpcHandshakeResponse.prototype.serializeBinary = function() {255 var writer = new jspb.BinaryWriter();256 proto.grpcserver.GrpcHandshakeResponse.serializeBinaryToWriter(this, writer);257 return writer.getResultBuffer();258};259/**260 * Serializes the given message to binary data (in protobuf wire261 * format), writing to the given BinaryWriter.262 * @param {!proto.grpcserver.GrpcHandshakeResponse} message263 * @param {!jspb.BinaryWriter} writer264 * @suppress {unusedLocalVariables} f is only used for nested messages265 */266proto.grpcserver.GrpcHandshakeResponse.serializeBinaryToWriter = function(message, writer) {267 var f = undefined;268 f = message.getUserid();269 if (f.length > 0) {270 writer.writeString(271 1,272 f273 );274 }275};276/**277 * optional string userId = 1;278 * @return {string}279 */280proto.grpcserver.GrpcHandshakeResponse.prototype.getUserid = function() {281 return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));282};283/** @param {string} value */284proto.grpcserver.GrpcHandshakeResponse.prototype.setUserid = function(value) {285 jspb.Message.setProto3StringField(this, 1, value);286};287if (jspb.Message.GENERATE_TO_OBJECT) {288/**289 * Creates an object representation of this proto suitable for use in Soy templates.290 * Field names that are reserved in JavaScript and will be renamed to pb_name.291 * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.292 * For the list of reserved names please see:293 * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.294 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance295 * for transitional soy proto support: http://goto/soy-param-migration296 * @return {!Object}297 */298proto.grpcserver.GrpcRequest.prototype.toObject = function(opt_includeInstance) {299 return proto.grpcserver.GrpcRequest.toObject(opt_includeInstance, this);300};301/**302 * Static version of the {@see toObject} method.303 * @param {boolean|undefined} includeInstance Whether to include the JSPB304 * instance for transitional soy proto support:305 * http://goto/soy-param-migration306 * @param {!proto.grpcserver.GrpcRequest} msg The msg instance to transform.307 * @return {!Object}308 * @suppress {unusedLocalVariables} f is only used for nested messages309 */310proto.grpcserver.GrpcRequest.toObject = function(includeInstance, msg) {311 var f, obj = {312 message: jspb.Message.getFieldWithDefault(msg, 1, ""),313 user: jspb.Message.getFieldWithDefault(msg, 2, ""),314 recipient: jspb.Message.getFieldWithDefault(msg, 3, "")315 };316 if (includeInstance) {317 obj.$jspbMessageInstance = msg;318 }319 return obj;320};321}322/**323 * Deserializes binary data (in protobuf wire format).324 * @param {jspb.ByteSource} bytes The bytes to deserialize.325 * @return {!proto.grpcserver.GrpcRequest}326 */327proto.grpcserver.GrpcRequest.deserializeBinary = function(bytes) {328 var reader = new jspb.BinaryReader(bytes);329 var msg = new proto.grpcserver.GrpcRequest;330 return proto.grpcserver.GrpcRequest.deserializeBinaryFromReader(msg, reader);331};332/**333 * Deserializes binary data (in protobuf wire format) from the334 * given reader into the given message object.335 * @param {!proto.grpcserver.GrpcRequest} msg The message object to deserialize into.336 * @param {!jspb.BinaryReader} reader The BinaryReader to use.337 * @return {!proto.grpcserver.GrpcRequest}338 */339proto.grpcserver.GrpcRequest.deserializeBinaryFromReader = function(msg, reader) {340 while (reader.nextField()) {341 if (reader.isEndGroup()) {342 break;343 }344 var field = reader.getFieldNumber();345 switch (field) {346 case 1:347 var value = /** @type {string} */ (reader.readString());348 msg.setMessage(value);349 break;350 case 2:351 var value = /** @type {string} */ (reader.readString());352 msg.setUser(value);353 break;354 case 3:355 var value = /** @type {string} */ (reader.readString());356 msg.setRecipient(value);357 break;358 default:359 reader.skipField();360 break;361 }362 }363 return msg;364};365/**366 * Serializes the message to binary data (in protobuf wire format).367 * @return {!Uint8Array}368 */369proto.grpcserver.GrpcRequest.prototype.serializeBinary = function() {370 var writer = new jspb.BinaryWriter();371 proto.grpcserver.GrpcRequest.serializeBinaryToWriter(this, writer);372 return writer.getResultBuffer();373};374/**375 * Serializes the given message to binary data (in protobuf wire376 * format), writing to the given BinaryWriter.377 * @param {!proto.grpcserver.GrpcRequest} message378 * @param {!jspb.BinaryWriter} writer379 * @suppress {unusedLocalVariables} f is only used for nested messages380 */381proto.grpcserver.GrpcRequest.serializeBinaryToWriter = function(message, writer) {382 var f = undefined;383 f = message.getMessage();384 if (f.length > 0) {385 writer.writeString(386 1,387 f388 );389 }390 f = message.getUser();391 if (f.length > 0) {392 writer.writeString(393 2,394 f395 );396 }397 f = message.getRecipient();398 if (f.length > 0) {399 writer.writeString(400 3,401 f402 );403 }404};405/**406 * optional string message = 1;407 * @return {string}408 */409proto.grpcserver.GrpcRequest.prototype.getMessage = function() {410 return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));411};412/** @param {string} value */413proto.grpcserver.GrpcRequest.prototype.setMessage = function(value) {414 jspb.Message.setProto3StringField(this, 1, value);415};416/**417 * optional string user = 2;418 * @return {string}419 */420proto.grpcserver.GrpcRequest.prototype.getUser = function() {421 return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, ""));422};423/** @param {string} value */424proto.grpcserver.GrpcRequest.prototype.setUser = function(value) {425 jspb.Message.setProto3StringField(this, 2, value);426};427/**428 * optional string recipient = 3;429 * @return {string}430 */431proto.grpcserver.GrpcRequest.prototype.getRecipient = function() {432 return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, ""));433};434/** @param {string} value */435proto.grpcserver.GrpcRequest.prototype.setRecipient = function(value) {436 jspb.Message.setProto3StringField(this, 3, value);437};438if (jspb.Message.GENERATE_TO_OBJECT) {439/**440 * Creates an object representation of this proto suitable for use in Soy templates.441 * Field names that are reserved in JavaScript and will be renamed to pb_name.442 * To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.443 * For the list of reserved names please see:444 * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.445 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance446 * for transitional soy proto support: http://goto/soy-param-migration447 * @return {!Object}448 */449proto.grpcserver.GrpcResponse.prototype.toObject = function(opt_includeInstance) {450 return proto.grpcserver.GrpcResponse.toObject(opt_includeInstance, this);451};452/**453 * Static version of the {@see toObject} method.454 * @param {boolean|undefined} includeInstance Whether to include the JSPB455 * instance for transitional soy proto support:456 * http://goto/soy-param-migration457 * @param {!proto.grpcserver.GrpcResponse} msg The msg instance to transform.458 * @return {!Object}459 * @suppress {unusedLocalVariables} f is only used for nested messages460 */461proto.grpcserver.GrpcResponse.toObject = function(includeInstance, msg) {462 var f, obj = {463 message: jspb.Message.getFieldWithDefault(msg, 1, "")464 };465 if (includeInstance) {466 obj.$jspbMessageInstance = msg;467 }468 return obj;469};470}471/**472 * Deserializes binary data (in protobuf wire format).473 * @param {jspb.ByteSource} bytes The bytes to deserialize.474 * @return {!proto.grpcserver.GrpcResponse}475 */476proto.grpcserver.GrpcResponse.deserializeBinary = function(bytes) {477 var reader = new jspb.BinaryReader(bytes);478 var msg = new proto.grpcserver.GrpcResponse;479 return proto.grpcserver.GrpcResponse.deserializeBinaryFromReader(msg, reader);480};481/**482 * Deserializes binary data (in protobuf wire format) from the483 * given reader into the given message object.484 * @param {!proto.grpcserver.GrpcResponse} msg The message object to deserialize into.485 * @param {!jspb.BinaryReader} reader The BinaryReader to use.486 * @return {!proto.grpcserver.GrpcResponse}487 */488proto.grpcserver.GrpcResponse.deserializeBinaryFromReader = function(msg, reader) {489 while (reader.nextField()) {490 if (reader.isEndGroup()) {491 break;492 }493 var field = reader.getFieldNumber();494 switch (field) {495 case 1:496 var value = /** @type {string} */ (reader.readString());497 msg.setMessage(value);498 break;499 default:500 reader.skipField();501 break;502 }503 }504 return msg;505};506/**507 * Serializes the message to binary data (in protobuf wire format).508 * @return {!Uint8Array}509 */510proto.grpcserver.GrpcResponse.prototype.serializeBinary = function() {511 var writer = new jspb.BinaryWriter();512 proto.grpcserver.GrpcResponse.serializeBinaryToWriter(this, writer);513 return writer.getResultBuffer();514};515/**516 * Serializes the given message to binary data (in protobuf wire517 * format), writing to the given BinaryWriter.518 * @param {!proto.grpcserver.GrpcResponse} message519 * @param {!jspb.BinaryWriter} writer520 * @suppress {unusedLocalVariables} f is only used for nested messages521 */522proto.grpcserver.GrpcResponse.serializeBinaryToWriter = function(message, writer) {523 var f = undefined;524 f = message.getMessage();525 if (f.length > 0) {526 writer.writeString(527 1,528 f529 );530 }531};532/**533 * optional string message = 1;534 * @return {string}535 */536proto.grpcserver.GrpcResponse.prototype.getMessage = function() {537 return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));538};539/** @param {string} value */540proto.grpcserver.GrpcResponse.prototype.setMessage = function(value) {541 jspb.Message.setProto3StringField(this, 1, value);542};...
index.js
Source:index.js
1const debug = require('debug')('grpc-express');2const config = require('rc')('grpc-express', {3 proxyUnaryCalls: true,4 proxyServerStreamCalls: true,5 unaryCallsTimeout: 5000,6 serverStreamCallsTimeout: 100007});8function toUpperCaseFirstLetter(string) {9 return string.charAt(0).toUpperCase() + string.slice(1);10}11function toLowerCaseFirstLetter(string) {12 return string.charAt(0).toLowerCase() + string.slice(1);13}14function routeToPathKeys(route) {15 const functionName = route.split('/').slice(-1)[0];16 return {17 upper: route.replace(functionName, toUpperCaseFirstLetter(functionName)),18 lower: route.replace(functionName, toLowerCaseFirstLetter(functionName)),19 name: toLowerCaseFirstLetter(functionName)20 };21}22class Middleware {23 constructor(grpcClient, opts) {24 opts = opts || {};25 this._opts = Object.assign({}, config, opts);26 debug('gRPC middleware constructed', this._opts);27 this._grpcClient = grpcClient;28 this._unaryCalls = new Map();29 this._serverStreamCalls = new Map();30 if (this._opts.proxyUnaryCalls) {31 [32 ...new Set(33 Object.keys(grpcClient.__proto__)34 .filter(35 route =>36 !grpcClient[route].requestStream &&37 !grpcClient[route].responseStream38 )39 .map(route => grpcClient[route].path)40 )41 ].filter(r => r).forEach(route => {42 const keys = routeToPathKeys(route);43 this._unaryCalls.set(keys.lower, keys.name);44 this._unaryCalls.set(keys.upper, keys.name);45 });46 debug('gRPC unary calls', this._unaryCalls);47 } else {48 debug('gRPC unary calls are not proxied');49 }50 if (this._opts.proxyServerStreamCalls) {51 [52 ...new Set(53 Object.keys(grpcClient.__proto__)54 .filter(55 route =>56 !grpcClient[route].requestStream &&57 grpcClient[route].responseStream58 )59 .map(route => grpcClient[route].path)60 )61 ].filter(r => r).forEach(route => {62 const keys = routeToPathKeys(route);63 this._serverStreamCalls.set(keys.lower, keys.name);64 this._serverStreamCalls.set(keys.upper, keys.name);65 });66 debug('gRPC server stream calls', this._serverStreamCalls);67 } else {68 debug('gRPC server stream calls are not proxied');69 }70 }71 proxy(req, res, next) {72 if (this._unaryCalls.has(req.path)) this.proxyUnaryCall(req, res);73 else if (this._serverStreamCalls.has(req.path))74 this.proxyServerStreamCall(req, res);75 else next();76 }77 proxyUnaryCall(req, res) {78 let timedout = false;79 // look at https://github.com/grpc/grpc/issues/997380 // gRPC's node sdk is potato quality. it does not pass up the error.81 let timer = setTimeout(() => {82 timedout = true;83 res.status(504);84 res.end();85 }, this._opts.unaryCallsTimeout);86 (async () => {87 debug('gRPC unary proxy request', req);88 res.setHeader('Content-Type', 'application/json');89 const grpcRequest = await this.getBody(req).catch(err => {90 res.status(400).send(err);91 });92 if (!grpcRequest) return;93 this._grpcClient[this._unaryCalls.get(req.path)](94 grpcRequest,95 (err, response) => {96 if (timedout) {97 debug('gRPC call already timedout');98 return;99 }100 debug('gRPC unary end', err, response);101 if (err) res.status(502).send(err);102 else res.json(response);103 clearTimeout(timer);104 }105 );106 })();107 }108 proxyServerStreamCall(req, res) {109 (async () => {110 debug('gRPC server stream proxy request', req);111 res.setHeader('Content-Type', 'application/json');112 const grpcRequest = await this.getBody(req).catch(err => {113 res.status(400).send(err);114 });115 if (!grpcRequest) return;116 const stream = this._grpcClient[this._serverStreamCalls.get(req.path)](117 grpcRequest118 );119 let firstChunk = true;120 res.write('[');121 stream.on('data', chunk => {122 debug('gRPC server stream chunk', chunk);123 if (!firstChunk) res.write(',');124 res.write(JSON.stringify(chunk));125 firstChunk = false;126 });127 stream.on('end', () => {128 debug('gRPC server stream end');129 res.write(']');130 res.end();131 });132 })();133 }134 async getBody(req) {135 return new Promise((resolve, reject) => {136 let body = '';137 req.on('data', chunk => {138 body += chunk.toString();139 });140 req.on('end', () => {141 try {142 body = JSON.parse(body);143 debug('gRPC request body read', body);144 resolve(body);145 } catch (err) {146 debug('gRPC request body fail', err);147 reject(err);148 }149 });150 });151 }152}153function factory(grpcClient, opts) {154 const instance = new Middleware(grpcClient, opts);155 return instance.proxy.bind(instance);156}...
client.js
Source:client.js
1const grpc = require("grpc");2const protoLoader = require("@grpc/proto-loader");3const caller = require("grpc-caller");4const { response } = require("express");5const protopath = __dirname + "/guruMatch.proto"6const client = caller("localhost:50051", protopath, "GuruMatch");7module.exports = {8 createUser: (id, name) => {9 const userRequest = {10 "id": id,11 "name": name,12 }13 client.CreateUser(userRequest, (err, response) => {14 console.log("recieved From Server " + JSON.stringify(response))15 });16 },17 isUsernameExist: async (id) => {18 const grpcRequest = {19 "id": id20 }21 // if usernameExist is 2, that means user haven't set up the form22 // if 1, then show the homepage23 let usernameExist = 2;24 usernameExist = await client.IsUsernameExist(grpcRequest);//.then(res => {usernameExist = res});25 return usernameExist.success;26 },27 storeUserForm: (id, username, user_bio, user_description, 28 user_skill, user_industry, user_tag, profile_pic) => {29 const grpcRequest = {30 "id": id,31 "username": username,32 "userBio": user_bio,33 "userDescription": user_description,34 "userSkill": user_skill,35 "userIndustry": user_industry,36 "userTag": user_tag,37 "profilePic": profile_pic,38 }39 let res = 2;40 client.StoreUserForm(grpcRequest, (err, response) => {41 console.log("recieved from server (StoreUserForm) " + JSON.stringify(response));42 })43 return res44 },45 getUserProfile: async (id) => {46 const grpcRequest = {47 "id": id48 };49 let res = ""50 res = await client.GetUserProfile(grpcRequest);51 return JSON.stringify(res)52 }, 53 createMentee: async (id, interests, description) => {54 const grpcRequest = {55 "id" : id,56 "interest" : interests,57 "menteeDescription" : description58 };59 let res = 260 res = await client.CreateMentee(grpcRequest);61 return res;62 },63 createMentor: async (id, interests, description) => {64 const grpcRequest = {65 "id" : id,66 "interest" : interests,67 "mentorDescription" : description68 };69 let res = 270 res = await client.CreateMentor(grpcRequest);71 return res;72 },73 getMatchMentors: async (id) => {74 const grpcRequest = {75 "id" : id76 };77 let res = await client.GetMatchMentors(grpcRequest);78 return JSON.stringify(res);79 },80 getMatchMentees: async (id) => {81 const grpcRequest = {82 "id" : id83 };84 let res = await client.GetMatchMentees(grpcRequest);85 //console.log(JSON.stringify(res))86 return JSON.stringify(res);87 },88 insertMentorSelectedMentee: async (menteeID, mentorID) => {89 console.log("menteeID : " + menteeID + "mentorID : " + mentorID)90 const grpcRequest = {91 "menteeID" : menteeID,92 "mentorID" : mentorID93 };94 let res = await client.InsertMentorSelectedMentee(grpcRequest);95 return JSON.stringify(res);96 },97 insertMenteeSelectedMentor: async (menteeID, mentorID) => {98 console.log("menteeID : " + menteeID + "mentorID : " + mentorID)99 const grpcRequest = {100 "menteeID" : menteeID,101 "mentorID" : mentorID102 };103 let res = await client.InsertMenteeSelectedMentor(grpcRequest);104 return JSON.stringify(res);105 },106 getAllMatches: async (userID) => {107 const grpcRequest = {108 "id" : userID109 };110 let res = await client.GetAllMatchesRequest(grpcRequest);111 return JSON.stringify(res);112 }113}114/*115async function test(userID) {116 const grpcRequest = {117 "id" : userID118 };119 let res = await client.GetAllMatchesRequest(grpcRequest).then(result => {return result});120 return JSON.stringify(res);...
Using AI Code Generation
1var path = require('path');2var grpc = require('grpc');3var protoLoader = require('@grpc/proto-loader');4var packageDefinition = protoLoader.loadSync(5 path.join(__dirname, 'tracetest.proto'),6 {7 });8var protoDescriptor = grpc.loadPackageDefinition(packageDefinition);9var tracetest = protoDescriptor.tracetest;10var client = new tracetest.GrpcRequest('localhost:50051',11 grpc.credentials.createInsecure());12var call = client.GrpcRequest({id: 'test'}, function(err, response) {13 console.log('Response: ', response);14});15call.on('data', function(data) {16 console.log('Data: ', data);17});18call.on('error', function(err) {19 console.log('Error: ', err);20});21call.on('end', function() {22 console.log('End');23});24syntax = "proto3";25package tracetest;26service GrpcRequest {27 rpc GrpcRequest (GrpcRequest) returns (stream GrpcResponse) {}28}29message GrpcRequest {30 string id = 1;31}32message GrpcResponse {33 string id = 1;34}35Data: GrpcResponse { id: 'test' }36The problem is that the callback function is called before the call.on('data') event handler is called. I would expect the response to be returned to the callback function. Am I missing something?
Using AI Code Generation
1const tracetest = require('./tracetest_pb.js');2const grpc = require('grpc');3const client = new tracetest.TraceTest('localhost:50051', grpc.credentials.createInsecure());4const request = new tracetest.GrpcRequest();5request.setTraceId('test');6request.setSpanId('test');7request.setOperation('test');8request.setService('test');9request.setTagsMap({key: 'value'});10client.grpc(request, function(err, response) {11 console.log(response);12});13syntax = "proto3";14package tracetest;15service TraceTest {16 rpc grpc(GrpcRequest) returns (GrpcResponse) {}17}18message GrpcRequest {19 string trace_id = 1;20 string span_id = 2;21 string operation = 3;22 string service = 4;23 map<string, string> tags = 5;24}25message GrpcResponse {26 string trace_id = 1;27 string span_id = 2;28 string operation = 3;29 string service = 4;30 map<string, string> tags = 5;31}32'use strict';33var jspb = require('google-protobuf');34var goog = jspb;35var global = Function('return this')();36goog.exportSymbol('proto.tracetest.GrpcRequest', null, global);37goog.exportSymbol('proto.tracetest.GrpcResponse', null, global);38goog.exportSymbol('proto.tracetest.TraceTest', null, global);39goog.exportSymbol('proto.tracetest.TraceTestService', null, global);40goog.exportSymbol('proto.tracetest.TraceTestService.grpc', null, global);41goog.exportSymbol('proto.tracetest.TraceTestService.grpc.methodType', null, global);42goog.exportSymbol('proto.tracetest.TraceTestService.grpc.requestStream', null, global);43goog.exportSymbol('proto.tracetest.TraceTestService.grpc.responseStream', null, global);44goog.exportSymbol('proto.tracetest.TraceTestService.grpc.responseType', null, global);45goog.exportSymbol('proto.tr
Using AI Code Generation
1const { GrpcRequest } = require('tracetesting');2const trace = require('@opencensus/nodejs');3const rootSpan = trace.tracer.startRootSpan({ name: 'root' });4const request = new GrpcRequest({5 headers: { 'x-grpc-test-echo-initial': 'test_initial_metadata_value' }6});7rootSpan.end();8trace.tracer.stop();
Using AI Code Generation
1var grpcRequest = new GrpcRequest();2grpcRequest.method = 'GrpcRequest';3grpcRequest.request = 'test';4grpcRequest.send(function(err, response){5 if (err) {6 console.log(err);7 } else {8 console.log(response);9 }10});11syntax = "proto3";12package tracetest;13service TraceTest {14 rpc GrpcRequest (GrpcRequest) returns (GrpcResponse) {}15}16message GrpcRequest {17 string request = 1;18}19message GrpcResponse {20 string response = 1;21}22syntax = "proto3";23package tracetest;24service TraceTest {25 rpc GrpcRequest (GrpcRequest) returns (GrpcResponse) {}26}27message GrpcRequest {28 string request = 1;29}30message GrpcResponse {31 string response = 1;32}33var grpc = require('grpc');34var protoLoader = require('@grpc/proto-loader');35var packageDefinition = protoLoader.loadSync(36 {keepCase: true,37 });38var tracetest_proto = grpc.loadPackageDefinition(packageDefinition).tracetest;39var client = new tracetest_proto.TraceTest('localhost:50051', grpc.credentials.createInsecure());40client.GrpcRequest({request: 'test'}, function(err, response) {41 if (err) {42 console.log(err);43 } else {44 console.log(response);45 }46});47syntax = "proto3";48package tracetest;49service TraceTest {50 rpc GrpcRequest (GrpcRequest) returns (GrpcResponse) {}51}52message GrpcRequest {53 string request = 1;54}55message GrpcResponse {56 string response = 1;57}
Using AI Code Generation
1import { GrpcRequest } from "@azure/core-tracing";2import { GreeterClient } from "./generated/greeterClient";3import { HelloRequest } from "./generated/models";4async function main() {5 const request = new HelloRequest();6 request.setName("John");7 const span = tracer.startSpan("root");8 const response = await client.sayHello(request, {9 tracingOptions: {10 spanOptions: {11 parent: span.context(),12 attributes: { key: "value" }13 }14 }15 });16 console.log(`Greeting: ${response.getMessage()}`);17 span.end();18}19main();20private async sayHello(21): Promise<HelloReply> {22 const { span, updatedOptions } = createSpan(23 options || {}24 );25 const operationArguments: coreHttp.OperationArguments = {26 options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions)27 };28 try {29 const result = await this.client.sayHello(30 );31 return result as HelloReply;32 } catch (error) {33 span.setStatus({34 });35 throw error;36 } finally {37 span.end();38 }39}40function createSpan(41 options: coreHttp.OperationOptions = {}42): { span: Span; updatedOptions: coreHttp.OperationOptions } {43 const tracer = getTracer();44 const tracingOptions = {45 ...{46 spanOptions: {}47 },48 };49 const spanOptions = tracingOptions.spanOptions || {};50 const span = tracer.startSpan(`Azure.GreeterClient.${operationName}`, {51 });52 span.setAttribute("az.namespace", "Microsoft.Greeter");53 let newOptions = options || {};54 if (span.isRecording()) {55 newOptions = {56 tracingOptions: {
Using AI Code Generation
1var grpcRequest = new tracetest.GrpcRequest();2grpcRequest.setMethod("GET");3grpcRequest.setBody("Hello World");4grpcRequest.setHeadersList(["header1", "header2"]);5var grpcResponse = new tracetest.GrpcResponse();6grpcResponse.setStatus(200);7grpcResponse.setBody("Hello World");8grpcResponse.setHeadersList(["header1", "header2"]);9var grpcSpan = new tracetest.GrpcSpan();10grpcSpan.setSpanId("spanId");11grpcSpan.setSpanName("spanName");12grpcSpan.setSpanKind(1);13grpcSpan.setStartTime(123);14grpcSpan.setEndTime(456);15grpcSpan.setParentSpanId("parentSpanId");16grpcSpan.setTraceId("traceId");17grpcSpan.setStatus(1);18grpcSpan.setAttributesList(["attribute1", "attribute2"]);19grpcSpan.setTimeEventsList(["timeEvent1", "timeEvent2"]);20grpcSpan.setLinksList(["link1", "link2"]);21grpcSpan.setChildSpanCount(1);22grpcSpan.setGrpcRequest(grpcRequest);23grpcSpan.setGrpcResponse(grpcResponse);24var grpcTraceServiceConfig = new tracetest.GrpcTraceServiceConfig();25grpcTraceServiceConfig.setProjectId("projectId");26grpcTraceServiceConfig.setTraceId("traceId");27grpcTraceServiceConfig.setSpanId("spanId");28grpcTraceServiceConfig.setSpanName("spanName");29grpcTraceServiceConfig.setSpanKind(1);30grpcTraceServiceConfig.setStartTime(123);31grpcTraceServiceConfig.setEndTime(456);32grpcTraceServiceConfig.setParentSpanId("parentSpanId");33grpcTraceServiceConfig.setTraceId("traceId");34grpcTraceServiceConfig.setStatus(1);35grpcTraceServiceConfig.setAttributesList(["attribute1", "attribute2"]);36grpcTraceServiceConfig.setTimeEventsList(["timeEvent1", "timeEvent2"]);37grpcTraceServiceConfig.setLinksList(["link1", "link2"]);38grpcTraceServiceConfig.setChildSpanCount(1);39grpcTraceServiceConfig.setGrpcRequest(grpcRequest);40grpcTraceServiceConfig.setGrpcResponse(grpcResponse);
Using AI Code Generation
1var grpcRequest = new GrpcRequest();2grpcRequest.serviceName = "tracetest.TestService";3grpcRequest.methodName = "GetTestData";4grpcRequest.data = {5};6grpcRequest.send(function (err, response) {7 if (err) {8 console.log("Error: " + err);9 }10 else {11 console.log("Response: " + JSON.stringify(response));12 }13});14syntax = "proto3";15package tracetest;16service TestService {17 rpc GetTestData (TestDataRequest) returns (TestDataResponse) {}18}19message TestDataRequest {20 string name = 1;21 int32 id = 2;22}23message TestDataResponse {24 string name = 1;25 int32 id = 2;26}27var tracetest = {};28tracetest.TestService = {29 GetTestData: {30 }31}32tracetest.TestDataRequest = function (data) {33 this.name = data.name;34 this.id = data.id;35};36tracetest.TestDataResponse = function (data) {37 this.name = data.name;38 this.id = data.id;39};40module.exports = tracetest;41Response: {"name":"response name","id":1234}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!