|
| 1 | +import * as loader from '@grpc/proto-loader'; |
| 2 | +import * as grpc from 'grpc'; |
| 3 | +import get from 'lodash.get'; |
| 4 | +import {getDescriptorRoot} from './descriptor'; |
| 5 | + |
| 6 | +const PROTO_PATH = |
| 7 | + __dirname + '/../static/grpc/reflection/v1alpha/reflection.proto'; |
| 8 | +const PACKAGE_NAME = 'grpc.reflection.v1alpha'; |
| 9 | +const SERVICE_NAME = 'ServerReflection'; |
| 10 | + |
| 11 | +export function createReflectionClient( |
| 12 | + url: string, |
| 13 | + credentials: grpc.ChannelCredentials, |
| 14 | + options?: object |
| 15 | +): grpc.Client { |
| 16 | + const packageDefinition = loader.loadSync(PROTO_PATH, { |
| 17 | + keepCase: true, |
| 18 | + longs: String, |
| 19 | + enums: String, |
| 20 | + defaults: true, |
| 21 | + oneofs: true, |
| 22 | + }); |
| 23 | + const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); // eslint-disable-line no-console |
| 24 | + const reflection = get(protoDescriptor, PACKAGE_NAME); |
| 25 | + const reflectionService = get(reflection, SERVICE_NAME); |
| 26 | + const client = new reflectionService(url, credentials, options); |
| 27 | + return client; |
| 28 | +} |
| 29 | + |
| 30 | +export async function listServices(client: any) { |
| 31 | + return new Promise((resolve, reject) => { |
| 32 | + function dataCallback(response: any) { |
| 33 | + if ('list_services_response' in response) { |
| 34 | + resolve(response.list_services_response.service); |
| 35 | + } else { |
| 36 | + reject(Error()); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + const input = { |
| 41 | + list_services: '*', |
| 42 | + }; |
| 43 | + const callGrpc = client['ServerReflectionInfo']({}); |
| 44 | + callGrpc.on('data', dataCallback); |
| 45 | + callGrpc.write(input); |
| 46 | + callGrpc.end(); |
| 47 | + }); |
| 48 | +} |
| 49 | + |
| 50 | +export async function fileContainingSymbol(service_name: string, client: any) { |
| 51 | + return new Promise((resolve, reject) => { |
| 52 | + function dataCallback(response: any) { |
| 53 | + if ('file_descriptor_response' in response) { |
| 54 | + const root = getDescriptorRoot( |
| 55 | + response.file_descriptor_response.file_descriptor_proto |
| 56 | + ); |
| 57 | + const res = grpc.loadObject(root); |
| 58 | + resolve(res); |
| 59 | + } else { |
| 60 | + reject(Error()); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + const input = { |
| 65 | + file_containing_symbol: service_name, |
| 66 | + }; |
| 67 | + const callGrpc = client['ServerReflectionInfo']({}); |
| 68 | + callGrpc.on('data', dataCallback); |
| 69 | + callGrpc.write(input); |
| 70 | + callGrpc.end(); |
| 71 | + }); |
| 72 | +} |
0 commit comments