@probitas/client-grpc
gRPC client for Probitas scenario testing framework.
This package provides a gRPC client with Server Reflection support, designed for
integration testing of gRPC services. It is a thin wrapper around
@probitas/client-connectrpc with
protocol: "grpc" pre-configured.
Features
- Native gRPC: Uses gRPC protocol (HTTP/2 with binary protobuf)
- Server Reflection: Auto-discover services and methods at runtime
- TLS Support: Configure secure connections with custom certificates
- Duration Tracking: Built-in timing for performance monitoring
- Error Handling: Test error responses without throwing exceptions
- Resource Management: Implements
AsyncDisposablefor proper cleanup
Installation
deno add jsr:@probitas/client-grpc
Quick Start
import { createGrpcClient } from "@probitas/client-grpc";
// Create client (uses reflection by default)
const client = createGrpcClient({
url: "http://localhost:50051",
});
// Call a method
const response = await client.call(
"echo.EchoService",
"echo",
{ message: "Hello!" }
);
console.log(response.data());
await client.close();
Service Discovery
// Discover available services
const services = await client.reflection.listServices();
console.log("Services:", services);
// Get method information
const info = await client.reflection.getServiceInfo("echo.EchoService");
console.log("Methods:", info.methods);
Using with using Statement
await using client = createGrpcClient({ url: "http://localhost:50051" });
const res = await client.call("echo.EchoService", "echo", { message: "test" });
console.log(res.data());
// Client automatically closed when block exits
Related Packages
| Package | Description |
|---|---|
@probitas/client |
Core utilities and types |
@probitas/client-connectrpc |
ConnectRPC client (supports Connect, gRPC, gRPC-Web) |
Links
Installation
deno add jsr:@probitas/client-grpcClasses
#GrpcError
class GrpcError extends ClientErrorClientErrorBase error class for ConnectRPC/gRPC errors.
Constructor
new GrpcError(message: string, code: ConnectRpcStatusCode, rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
namestring - readonly
kind"connectrpc" - readonly
rawMessagestring - readonly
metadata?Record<string, string>
#GrpcInternalError
class GrpcInternalError extends ConnectRpcErrorConnectRpcErrorError thrown for internal server errors (code 13).
Constructor
new GrpcInternalError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcInternalError" - readonly
code13
#GrpcNotFoundError
class GrpcNotFoundError extends ConnectRpcErrorConnectRpcErrorError thrown when the requested resource is not found (code 5).
Constructor
new GrpcNotFoundError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcNotFoundError" - readonly
code5
#GrpcPermissionDeniedError
class GrpcPermissionDeniedError extends ConnectRpcErrorConnectRpcErrorError thrown when the client lacks permission (code 7).
Constructor
new GrpcPermissionDeniedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcPermissionDeniedError" - readonly
code7
#GrpcResourceExhaustedError
class GrpcResourceExhaustedError extends ConnectRpcErrorConnectRpcErrorError thrown when a resource is exhausted (code 8).
Constructor
new GrpcResourceExhaustedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcResourceExhaustedError" - readonly
code8
#GrpcUnauthenticatedError
class GrpcUnauthenticatedError extends ConnectRpcErrorConnectRpcErrorError thrown when the client is not authenticated (code 16).
Constructor
new GrpcUnauthenticatedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcUnauthenticatedError" - readonly
code16
Interfaces
#ErrorDetail
interface ErrorDetailRich error detail from google.rpc.Status.
ConnectRPC errors can include structured details encoded in error responses. These details follow the google.protobuf.Any format with a type URL and value.
Properties
- readonly
typeUrlstringType URL identifying the error detail type. Common types include:
- "type.googleapis.com/google.rpc.BadRequest"
- "type.googleapis.com/google.rpc.DebugInfo"
- "type.googleapis.com/google.rpc.RetryInfo"
- "type.googleapis.com/google.rpc.QuotaFailure"
- readonly
valueunknownDecoded error detail value. The structure depends on the typeUrl.
#GrpcClient
interface GrpcClient extends AsyncDisposableConnectRPC client interface.
| Name | Description |
|---|---|
config | Client configuration |
reflection | Reflection API (only available when schema: "reflection") |
call() | Make a unary RPC call. |
serverStream() | Make a server streaming RPC call. |
clientStream() | Make a client streaming RPC call. |
bidiStream() | Make a bidirectional streaming RPC call. |
close() | Close the client connection. |
Properties
Client configuration
Reflection API (only available when schema: "reflection")
Methods
call<TRequest = unknown>(serviceName: string, methodName: string, request: TRequest, options?: ConnectRpcOptions): Promise<ConnectRpcResponse>Make a unary RPC call.
Parameters
serviceNamestring- Service name (e.g., "echo.EchoService")
methodNamestring- Method name (e.g., "echo")
requestTRequest- Request message
options?ConnectRpcOptions- Call options
serverStream<TRequest = unknown>(serviceName: string, methodName: string, request: TRequest, options?: ConnectRpcOptions): AsyncIterable<ConnectRpcResponse>Make a server streaming RPC call.
Parameters
serviceNamestring- Service name
methodNamestring- Method name
requestTRequest- Request message
options?ConnectRpcOptions- Call options
clientStream<TRequest = unknown>(serviceName: string, methodName: string, requests: AsyncIterable<TRequest>, options?: ConnectRpcOptions): Promise<ConnectRpcResponse>Make a client streaming RPC call.
Parameters
serviceNamestring- Service name
methodNamestring- Method name
requestsAsyncIterable<TRequest>- Async iterable of request messages
options?ConnectRpcOptions- Call options
bidiStream<TRequest = unknown>(serviceName: string, methodName: string, requests: AsyncIterable<TRequest>, options?: ConnectRpcOptions): AsyncIterable<ConnectRpcResponse>Make a bidirectional streaming RPC call.
Parameters
serviceNamestring- Service name
methodNamestring- Method name
requestsAsyncIterable<TRequest>- Async iterable of request messages
options?ConnectRpcOptions- Call options
close(): Promise<void>Close the client connection.
#GrpcClientConfig
interface GrpcClientConfig extends Omit<ConnectRpcClientConfig, "protocol">Configuration for creating a gRPC client.
This is a subset of ConnectRpcClientConfig with protocol fixed to "grpc".
#GrpcErrorOptions
interface GrpcErrorOptions extends ErrorOptionsOptions for ConnectRpcError construction.
| Name | Description |
|---|---|
metadata | Headers/metadata from the ConnectRPC response. |
details | Rich error details from google.rpc.Status. |
Properties
- readonly
metadata?Record<string, string>Headers/metadata from the ConnectRPC response.
Rich error details from google.rpc.Status.
#GrpcOptions
interface GrpcOptions extends CommonOptionsOptions for individual ConnectRPC calls.
| Name | Description |
|---|---|
metadata | Metadata to send with the request. |
throwOnError | Whether to throw ConnectRpcError on non-OK responses (code !== 0). |
Properties
- readonly
metadata?Record<string, string>Metadata to send with the request.
- readonly
throwOnError?booleanWhether to throw ConnectRpcError on non-OK responses (code !== 0). Overrides ConnectRpcClientConfig.throwOnError.
#GrpcResponse
interface GrpcResponseConnectRPC response interface.
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the request was successful (code === 0). |
code | ConnectRPC/gRPC status code. |
message | Status message (empty string for successful responses). |
headers | Response headers |
trailers | Response trailers (sent at end of RPC) |
duration | Response time in milliseconds. |
data() | Get deserialized response data. |
raw() | Get raw response message. |
Properties
- readonly
type"connectrpc"Result type identifier
- readonly
okbooleanWhether the request was successful (code === 0).
ConnectRPC/gRPC status code.
- readonly
messagestringStatus message (empty string for successful responses).
- readonly
headersRecord<string, string>Response headers
- readonly
trailersRecord<string, string>Response trailers (sent at end of RPC)
- readonly
durationnumberResponse time in milliseconds.
Methods
data<T = any>(): T | nullGet deserialized response data. Returns the response message as-is (already deserialized by Connect). Returns null if the response is an error or has no data.
raw(): unknownGet raw response message.
#MethodInfo
interface MethodInfoMethod information from reflection.
| Name | Description |
|---|---|
name | Method name (e.g., "Echo") |
localName | Local name (camelCase) |
kind | Method kind |
inputType | Input message type name |
outputType | Output message type name |
idempotent | Whether the method is idempotent |
Properties
- readonly
namestringMethod name (e.g., "Echo")
- readonly
localNamestringLocal name (camelCase)
- readonly
kind"unary" | "server_streaming" | "client_streaming" | "bidi_streaming"Method kind
- readonly
inputTypestringInput message type name
- readonly
outputTypestringOutput message type name
- readonly
idempotentbooleanWhether the method is idempotent
#ReflectionApi
interface ReflectionApiReflection API for ConnectRPC client. Only available when client is created with schema: "reflection".
| Name | Description |
|---|---|
enabled | Check if reflection is enabled. |
listServices() | List all available services on the server. |
getServiceInfo() | Get detailed information about a specific service. |
listMethods() | Get methods for a specific service. |
hasService() | Check if a service exists. |
Properties
- readonly
enabledbooleanCheck if reflection is enabled.
Methods
listServices(): Promise<ServiceInfo[]>List all available services on the server.
getServiceInfo(serviceName: string): Promise<ServiceDetail>Get detailed information about a specific service.
Parameters
serviceNamestring- Fully qualified service name (e.g., "echo.EchoService")
listMethods(serviceName: string): Promise<MethodInfo[]>Get methods for a specific service.
Parameters
serviceNamestring- Fully qualified service name
hasService(serviceName: string): Promise<boolean>Check if a service exists.
Parameters
serviceNamestring- Fully qualified service name
#ServiceDetail
interface ServiceDetailDetailed service information.
| Name | Description |
|---|---|
name | Service name |
fullName | Fully qualified service name |
packageName | Package name |
protoFile | Proto file name |
methods | All methods |
Properties
- readonly
namestringService name
- readonly
fullNamestringFully qualified service name
- readonly
packageNamestringPackage name
- readonly
protoFilestringProto file name
All methods
#ServiceInfo
interface ServiceInfoService information from reflection.
Properties
- readonly
namestringFully qualified service name (e.g., "echo.EchoService")
- readonly
filestringProto file name
#TlsConfig
interface TlsConfigTLS configuration for ConnectRPC connections.
| Name | Description |
|---|---|
rootCerts | Root CA certificate (PEM format). |
clientCert | Client certificate (PEM format). |
clientKey | Client private key (PEM format). |
insecure | Skip server certificate verification (use only for testing). |
Properties
- readonly
rootCerts?Uint8ArrayRoot CA certificate (PEM format).
- readonly
clientCert?Uint8ArrayClient certificate (PEM format).
- readonly
clientKey?Uint8ArrayClient private key (PEM format).
- readonly
insecure?booleanSkip server certificate verification (use only for testing).
Functions
#createGrpcClient
function createGrpcClient(config: GrpcClientConfig): ConnectRpcClientCreate a new gRPC client instance.
This is a thin wrapper around createConnectRpcClient with protocol: "grpc" fixed.
The client provides Server Reflection support for runtime service discovery.
Parameters
configGrpcClientConfig- Client configuration including server address
Returns
ConnectRpcClient — A new gRPC client instance
Examples
Basic usage with reflection
const client = createGrpcClient({
url: "http://localhost:50051",
});
// Call a method
const response = await client.call(
"echo.EchoService",
"echo",
{ message: "Hello!" }
);
console.log(response.data());
await client.close();
Service discovery with reflection
const client = createGrpcClient({
url: "http://localhost:50051",
});
// Discover available services
const services = await client.reflection.listServices();
console.log("Available services:", services);
// Get method information
const info = await client.reflection.getServiceInfo("echo.EchoService");
console.log("Methods:", info.methods);
await client.close();
Testing error responses
const response = await client.call(
"user.UserService",
"getUser",
{ id: "non-existent" },
{ throwOnError: false }
);
if (!response.ok) {
console.log("Error code:", response.code); // NOT_FOUND = 5
}
Using await using for automatic cleanup
await using client = createGrpcClient({
url: "http://localhost:50051",
});
const res = await client.call("echo.EchoService", "echo", { message: "test" });
console.log(res.data());
// Client automatically closed when scope exits
#getGrpcStatusName
function getGrpcStatusName(code: ConnectRpcStatusCode): stringGet the name of a ConnectRPC/gRPC status code.
Parameters
Examples
getStatusName(0); // "OK"
getStatusName(5); // "NOT_FOUND"
getStatusName(16); // "UNAUTHENTICATED"
#isGrpcStatusCode
function isGrpcStatusCode(code: number): code is ConnectRpcStatusCodeCheck if a number is a valid ConnectRPC/gRPC status code.
Parameters
codenumber
Examples
isConnectRpcStatusCode(0); // true
isConnectRpcStatusCode(16); // true
isConnectRpcStatusCode(99); // false
Type Aliases
#FileDescriptorSet
type FileDescriptorSet = MessageShape<FileDescriptorSetSchema>FileDescriptorSet message type from @bufbuild/protobuf. This is the decoded protobuf message containing file descriptors.
#GrpcStatusCode
type GrpcStatusCode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16ConnectRPC/gRPC status codes. These codes are used by both gRPC and ConnectRPC protocols.
Variables
#GrpcStatus
const GrpcStatus: { OK: number; CANCELLED: number; UNKNOWN: number; INVALID_ARGUMENT: number; DEADLINE_EXCEEDED: number; NOT_FOUND: number; ALREADY_EXISTS: number; PERMISSION_DENIED: number; RESOURCE_EXHAUSTED: number; FAILED_PRECONDITION: number; ABORTED: number; OUT_OF_RANGE: number; UNIMPLEMENTED: number; INTERNAL: number; UNAVAILABLE: number; DATA_LOSS: number; UNAUTHENTICATED: number }Human-readable names for ConnectRPC/gRPC status codes.
