google.protobuf.Value metadata = 4;
}
message GetUserRequest {
string email = 1;
}
service UserService {
rpc GetUser(GetUserRequest) returns (User);
}
server.js:
const path = require('path')
const grpc = require('grpc')
const PROTO_PATH = path.resolve(__dirname, './user.proto')
const UserService = grpc.load(PROTO_PATH).user.UserService
const data = {
"firstName": "Bob",
"lastName": "Smith",
},
"firstName": "Jane",
"lastName": "Smith"
}
}
function getUser(call, callback) {
const user = data[call.request.email]
if (!user) {
return callback(new Error('User Not Found'))
}
return callback(null, user)
}
function main() {
const server = new grpc.Server()
server.addProtoService(UserService.service, { getUser })
server.bind(HOSTPORT, grpc.ServerCredentials.createInsecure())
server.start()
console.log(`User service running @ ${HOSTPORT}`)
}
main()
client.js
const path = require('path')
const grpc = require('grpc')
const PROTO_PATH = path.resolve(__dirname, './user.proto')
const UserService = grpc.load(PROTO_PATH).user.UserService
const client = new UserService(HOSTPORT, grpc.credentials.createInsecure())
console.log(user)
process.exit()
})
Run the server using command:
node server.js
Run the client:
node client.js
firstName: 'Jane',
lastName: 'Smith',
metadata: null }
/Users/bojand/dev/nodejs/grpctest/node_modules/protobufjs/dist/protobuf.js:2472
throw Error(this+"#"+keyOrObj+" is not a field: undefined");
^
Error: .google.protobuf.Value#foo is not a field: undefined
at Error (native)
...
Within the server part once we load proto we do have a constructor for the User class, and I've tried playing around with trying to create an instance of that in different ways and it crashes when trying to create that instance. I've also tried to encode from stringified JSON and still fails. When there is "metadata" it crashes. I think I am doing something dumb but I am not sure what.
Thanks.