Skip to content

Commit

Permalink
pass response twice
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenplusplus committed Feb 4, 2016
1 parent df149eb commit 625b767
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions lib/common/grpc-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,19 +201,25 @@ GrpcService.prototype.request = function(protoOpts, reqOpts, callback) {
// snakeize and camelize are used to transform camelCase request options to
// snake_case. This is what ProtoBuf.js (via gRPC) expects. Similarly, the
// response is in snake_case, which is why we use camelize to return it to
// camelCase. An option will be added to gRPC to allow us to skip this step:
// https://github.com/GoogleCloudPlatform/gcloud-node/pull/1070#discussion_r51285492
// camelCase.
//
// An option will be added to gRPC to allow us to skip this step:
// https://github.com/grpc/grpc/issues/5005
service[protoOpts.method](snakeize(reqOpts), function(err, resp) {
resp = convertBuffers(camelize(resp));

if (err) {
if (HTTP_ERROR_CODE_MAP[err.code]) {
var httpError = HTTP_ERROR_CODE_MAP[err.code];
err.code = httpError.code;
}

callback(err);
callback(err, null, resp);
return;
}

callback(null, resp, resp);

function convertBuffers(data) {
if (is.array(data)) {
return data.map(convertBuffers);
Expand All @@ -224,11 +230,11 @@ GrpcService.prototype.request = function(protoOpts, reqOpts, callback) {
var value = data[prop];

// An option will be added to gRPC to expose a setting which will
// replace this function (convertBuffers).
// https://github.com/GoogleCloudPlatform/gcloud-node/pull/1070#discussion_r51285492
if (is.object(value) && value.length) {
data[prop] = new Buffer(value).toString('base64');
} else if (is.object(value)) {
// replace this function (convertBuffers):
// https://github.com/grpc/grpc/issues/5006
if (isBufferLike(value)) {
data[prop] = new Buffer(objToArr(value)).toString('base64');
} else {
data[prop] = convertBuffers(value);
}
}
Expand All @@ -237,7 +243,28 @@ GrpcService.prototype.request = function(protoOpts, reqOpts, callback) {
return data;
}

callback(null, convertBuffers(camelize(resp)));
function isBufferLike(value) {
// protobufjs via gRPC returns an object-ified array, like:
// {
// 0: 0,
// 1: 22
// }
//
// This is a crude way to determine if it's a buffer.
return is.object(value) && is.defined(value[0]);
}

function objToArr(obj) {
var arr = [];

for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
arr.push(obj[prop]);
}
}

return arr;
}
}, null, grpcOpts);
};

Expand Down

0 comments on commit 625b767

Please sign in to comment.