0

I have been trying make a function that returns a token by subject with grpc nodejs and mongodb.

proto file

syntax = "proto3";

package tokens;

service tokenService {
    rpc getToken (TokenRequest) returns (TokenReply) {}
}

message TokenRequest {
    string subject = 1;
    string platform = 2;
}

message TokenReply {
   string token = 1;
   string subject = 2;
   string platform = 3;
}

function in server file

register is a mongoose model

server.addService(tokens.tokenService.service, {
  getToken: (call, callback) => {

    register.find({ subject: call.request.subject }, (err, res) => {
      return callback(null, res);
    });

    callback({
      code: grpc.status.NOT_FOUND,
      details: "Not found"
    });

  }
});

when I try to test this with BloomRPC it keeps loading.

and when I put a static object in callback it works. like this.

callback(null, { token: "test", subject: "test", platform: "test" });

so how do I get data from my db and send them with my getToken function ?

abedelhak
  • 1
  • 1

1 Answers1

0

Assuming that register.find is an asynchronous function, your current code is immediately calling the callback with the error, then when find completes it is trying to call the callback again with the result but at that point it is too late because the callback has already been called. You should instead wait for find to complete before calling the callback at all:

server.addService(tokens.tokenService.service, {
  getToken: (call, callback) => {

    register.find({ subject: call.request.subject }, (err, res) => {
      if (err) {
        callback({
          code: grpc.status.NOT_FOUND,
          details: "Not found"
        });
      } else {
        return callback(null, res);
      }
    });

  }
});
murgatroid99
  • 19,007
  • 10
  • 60
  • 95