mirror of
https://github.com/grpc/grpc-node.git
synced 2026-01-25 14:27:06 +00:00
86 lines
2.5 KiB
JavaScript
86 lines
2.5 KiB
JavaScript
/*
|
|
*
|
|
* Copyright 2025 gRPC authors.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
*/
|
|
|
|
var PROTO_PATH = __dirname + '/../protos/helloworld.proto';
|
|
|
|
var grpc = require('@grpc/grpc-js');
|
|
var protoLoader = require('@grpc/proto-loader');
|
|
var packageDefinition = protoLoader.loadSync(
|
|
PROTO_PATH,
|
|
{
|
|
keepCase: true,
|
|
longs: String,
|
|
enums: String,
|
|
defaults: true,
|
|
oneofs: true
|
|
});
|
|
var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;
|
|
|
|
var {Status, BadRequest} = require('@q42philips/node-grpc-error-details');
|
|
var {Any} = require('google-protobuf/google/protobuf/any_pb');
|
|
|
|
/**
|
|
* Implements the SayHello RPC method.
|
|
*/
|
|
function sayHello(call, callback) {
|
|
if (call.request.name === '') {
|
|
// Create BadRequest detail
|
|
var fieldViolation = new BadRequest.FieldViolation();
|
|
fieldViolation.setField('name');
|
|
fieldViolation.setDescription('Name field is required');
|
|
|
|
var badRequest = new BadRequest();
|
|
badRequest.setFieldViolationsList([fieldViolation]);
|
|
|
|
// Pack into Any
|
|
var anyMessage = new Any();
|
|
anyMessage.pack(badRequest.serializeBinary(), 'google.rpc.BadRequest');
|
|
|
|
// Create Status
|
|
var status = new Status();
|
|
status.setCode(3); // INVALID_ARGUMENT
|
|
status.setMessage('Request argument invalid');
|
|
status.setDetailsList([anyMessage]);
|
|
|
|
// Attach as metadata
|
|
var metadata = new grpc.Metadata();
|
|
metadata.add('grpc-status-details-bin', Buffer.from(status.serializeBinary()));
|
|
|
|
callback({
|
|
code: grpc.status.INVALID_ARGUMENT,
|
|
details: 'Simple Error: The name field was empty.',
|
|
metadata: metadata
|
|
});
|
|
return;
|
|
}
|
|
|
|
callback(null, {message: 'Hello ' + call.request.name});
|
|
}
|
|
|
|
/**
|
|
* Starts an RPC server.
|
|
*/
|
|
function main() {
|
|
var server = new grpc.Server();
|
|
server.addService(hello_proto.Greeter.service, {sayHello: sayHello});
|
|
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
|
|
console.log('Server running at http://0.0.0.0:50051');
|
|
});
|
|
}
|
|
|
|
main(); |