@probitas/expect
Type-safe expectation library for Probitas scenario testing with specialized assertions for various client types.
This module provides a unified expect() function that automatically dispatches to the appropriate
expectation based on the input type, along with specialized expectations for each client type.
Features
- Type-safe expectations: Compile-time safety with TypeScript
- Unified API: Single
expect()function that dispatches to specialized expectations - Client-specific assertions: Tailored expectations for HTTP, GraphQL, SQL, Redis, MongoDB, and more
- Method chaining: Fluent API for readable test assertions
- Consistent naming: All methods follow
toBeXxxortoHaveXxxpatterns - Generic fallback: Chainable wrapper for @std/expect matchers
Usage
Unified expect Function
The expect() function automatically dispatches to the appropriate expectation based on the input type:
Installation
deno add jsr:@probitas/expectClasses
#ConnectRpcError
class ConnectRpcError extends ClientErrorClientErrorBase error class for ConnectRPC/gRPC errors.
Constructor
new ConnectRpcError(message: string, code: ConnectRpcStatusCode, rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
namestring - readonly
kind"connectrpc" - readonly
rawMessagestring - readonly
metadata?Record<string, string>
#ConnectRpcInternalError
class ConnectRpcInternalError extends ConnectRpcErrorConnectRpcErrorError thrown for internal server errors (code 13).
Constructor
new ConnectRpcInternalError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcInternalError" - readonly
code13
#ConnectRpcNotFoundError
class ConnectRpcNotFoundError extends ConnectRpcErrorConnectRpcErrorError thrown when the requested resource is not found (code 5).
Constructor
new ConnectRpcNotFoundError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcNotFoundError" - readonly
code5
#ConnectRpcPermissionDeniedError
class ConnectRpcPermissionDeniedError extends ConnectRpcErrorConnectRpcErrorError thrown when the client lacks permission (code 7).
Constructor
new ConnectRpcPermissionDeniedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcPermissionDeniedError" - readonly
code7
#ConnectRpcResourceExhaustedError
class ConnectRpcResourceExhaustedError extends ConnectRpcErrorConnectRpcErrorError thrown when a resource is exhausted (code 8).
Constructor
new ConnectRpcResourceExhaustedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcResourceExhaustedError" - readonly
code8
#ConnectRpcResponseImpl
class ConnectRpcResponseImpl implements ConnectRpcResponseConnectRpcResponseImplementation of ConnectRpcResponse.
Constructor
new ConnectRpcResponseImpl(options: ConnectRpcResponseOptions)Properties
- readonly
type"connectrpc" - readonly
okboolean - readonly
messagestring - readonly
headersRecord<string, string> - readonly
trailersRecord<string, string> - readonly
durationnumber
Methods
data(): unknownraw(): unknown#ConnectRpcUnauthenticatedError
class ConnectRpcUnauthenticatedError extends ConnectRpcErrorConnectRpcErrorError thrown when the client is not authenticated (code 16).
Constructor
new ConnectRpcUnauthenticatedError(rawMessage: string, options?: ConnectRpcErrorOptions)Properties
- readonly
name"ConnectRpcUnauthenticatedError" - readonly
code16
#ConstraintError
class ConstraintError extends SqlErrorSqlErrorError thrown when a constraint violation occurs.
| Name | Description |
|---|---|
name | — |
kind | — |
constraint | — |
Constructor
new ConstraintError(message: string, constraint: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"constraint" - readonly
constraintstring
#DeadlockError
class DeadlockError extends SqlErrorSqlErrorError thrown when a deadlock is detected.
Constructor
new DeadlockError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"deadlock"
#DenoKvAtomicBuilderImpl
class DenoKvAtomicBuilderImpl implements DenoKvAtomicBuilderDenoKvAtomicBuilderImplementation of DenoKvAtomicBuilder.
Constructor
new DenoKvAtomicBuilderImpl(kv: Deno.Kv)Methods
check(): unknownset(): unknowndelete(): unknownsum(): unknownmin(): unknownmax(): unknowncommit(): unknown#DenoKvAtomicCheckError
class DenoKvAtomicCheckError extends DenoKvErrorDenoKvErrorError thrown when an atomic operation fails due to check failures.
| Name | Description |
|---|---|
name | — |
kind | — |
failedChecks | The keys whose checks failed. |
Constructor
new DenoKvAtomicCheckError(message: string, failedChecks: readonly Deno.KvKey[], options?: ErrorOptions)Properties
- readonly
namestring - readonly
kind"atomic_check" - readonly
failedChecksreadonly Deno.KvKey[]The keys whose checks failed.
#DenoKvError
class DenoKvError extends ClientErrorClientErrorBase error class for Deno KV operations.
| Name | Description |
|---|---|
name | — |
Constructor
new DenoKvError(message: string, _: unknown, options?: ErrorOptions)Properties
- readonly
namestring
#DenoKvQuotaError
class DenoKvQuotaError extends DenoKvErrorDenoKvErrorError thrown when a quota limit is exceeded.
Constructor
new DenoKvQuotaError(message: string, options?: ErrorOptions)Properties
- readonly
namestring - readonly
kind"quota"
#GraphqlError
class GraphqlError extends ClientErrorClientErrorBase GraphQL error class.
| Name | Description |
|---|---|
name | — |
kind | — |
errors | GraphQL errors from response |
response | Associated GraphQL response (if available) |
Constructor
new GraphqlError(message: string, errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)Properties
- readonly
namestring - readonly
kind"graphql" GraphQL errors from response
Associated GraphQL response (if available)
#GraphqlExecutionError
class GraphqlExecutionError extends GraphqlErrorGraphqlErrorError thrown for GraphQL execution errors.
| Name | Description |
|---|---|
name | — |
Constructor
new GraphqlExecutionError(errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)Properties
- readonly
namestring
#GraphqlNetworkError
class GraphqlNetworkError extends GraphqlErrorGraphqlErrorError thrown for network/HTTP errors before GraphQL processing.
| Name | Description |
|---|---|
name | — |
Constructor
new GraphqlNetworkError(message: string, options?: ErrorOptions)Properties
- readonly
namestring
#GraphqlValidationError
class GraphqlValidationError extends GraphqlErrorGraphqlErrorError thrown for GraphQL validation errors.
| Name | Description |
|---|---|
name | — |
Constructor
new GraphqlValidationError(errors: readonly GraphqlErrorItem[], options?: GraphqlErrorOptions)Properties
- readonly
namestring
#HttpBadRequestError
class HttpBadRequestError extends HttpErrorHttpErrorHTTP 400 Bad Request error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpBadRequestError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status400 - readonly
statusTextstring
#HttpConflictError
class HttpConflictError extends HttpErrorHttpErrorHTTP 409 Conflict error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpConflictError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status409 - readonly
statusTextstring
#HttpError
class HttpError extends ClientErrorClientErrorBase HTTP error class.
| Name | Description |
|---|---|
name | — |
kind | — |
status | HTTP status code |
statusText | HTTP status text |
response | Associated HTTP response (if available) |
Constructor
new HttpError(message: string, status: number, statusText: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
kind"http" - readonly
statusnumberHTTP status code
- readonly
statusTextstringHTTP status text
Associated HTTP response (if available)
#HttpForbiddenError
class HttpForbiddenError extends HttpErrorHttpErrorHTTP 403 Forbidden error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpForbiddenError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status403 - readonly
statusTextstring
#HttpInternalServerError
class HttpInternalServerError extends HttpErrorHttpErrorHTTP 500 Internal Server Error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpInternalServerError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status500 - readonly
statusTextstring
#HttpNotFoundError
class HttpNotFoundError extends HttpErrorHttpErrorHTTP 404 Not Found error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpNotFoundError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status404 - readonly
statusTextstring
#HttpTooManyRequestsError
class HttpTooManyRequestsError extends HttpErrorHttpErrorHTTP 429 Too Many Requests error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpTooManyRequestsError(message: string, options?: HttpErrorOptions)Properties
- readonly
namestring - readonly
status429 - readonly
statusTextstring
#HttpUnauthorizedError
class HttpUnauthorizedError extends HttpErrorHttpErrorHTTP 401 Unauthorized error.
| Name | Description |
|---|---|
name | — |
status | — |
statusText | — |
Constructor
new HttpUnauthorizedError(message: string, options?: HttpErrorOptions)Properties
#MongoConnectionError
class MongoConnectionError extends MongoErrorMongoErrorError thrown when a MongoDB connection cannot be established.
Constructor
new MongoConnectionError(message: string, options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#MongoDuplicateKeyError
class MongoDuplicateKeyError extends MongoErrorMongoErrorError thrown when a duplicate key constraint is violated.
| Name | Description |
|---|---|
name | — |
kind | — |
keyPattern | — |
keyValue | — |
Constructor
new MongoDuplicateKeyError(message: string, keyPattern: Record<string, number>, keyValue: Record<string, unknown>, options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"duplicate_key" - readonly
keyPatternRecord<string, number> - readonly
keyValueRecord<string, unknown>
#MongoError
class MongoError extends ClientErrorClientErrorBase error class for MongoDB client errors.
Constructor
new MongoError(message: string, _: unknown, options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
code?number
#MongoNotFoundError
class MongoNotFoundError extends MongoErrorMongoErrorError thrown when a document is not found (for firstOrThrow, lastOrThrow).
Constructor
new MongoNotFoundError(message: string, options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"not_found"
#MongoQueryError
class MongoQueryError extends MongoErrorMongoErrorError thrown when a MongoDB query fails.
| Name | Description |
|---|---|
name | — |
kind | — |
collection | — |
Constructor
new MongoQueryError(message: string, collection: string, options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"query" - readonly
collectionstring
#MongoValidationError
class MongoValidationError extends MongoErrorMongoErrorError thrown when document validation fails.
| Name | Description |
|---|---|
name | — |
kind | — |
validationErrors | — |
Constructor
new MongoValidationError(message: string, validationErrors: readonly string[], options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"validation" - readonly
validationErrorsreadonly string[]
#MongoWriteError
class MongoWriteError extends MongoErrorMongoErrorError thrown when a write operation fails.
| Name | Description |
|---|---|
name | — |
kind | — |
writeErrors | — |
Constructor
new MongoWriteError(message: string, writeErrors: readonly { index: number; code: number; message: string }[], options?: MongoErrorOptions)Properties
- readonly
namestring - readonly
kind"write" - readonly
writeErrorsreadonly { index: number; code: number; message: string }[]
#QuerySyntaxError
class QuerySyntaxError extends SqlErrorSqlErrorError thrown when a SQL query has syntax errors.
Constructor
new QuerySyntaxError(message: string, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
kind"query"
#RabbitMqChannelError
class RabbitMqChannelError extends RabbitMqErrorRabbitMqErrorError thrown when a RabbitMQ channel operation fails.
Constructor
new RabbitMqChannelError(message: string, options?: RabbitMqChannelErrorOptions)Properties
- readonly
namestring - readonly
kind"channel" - readonly
channelId?number
#RabbitMqConnectionError
class RabbitMqConnectionError extends RabbitMqErrorRabbitMqErrorError thrown when a RabbitMQ connection cannot be established.
Constructor
new RabbitMqConnectionError(message: string, options?: RabbitMqErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#RabbitMqError
class RabbitMqError extends ClientErrorClientErrorBase error class for RabbitMQ client errors.
Constructor
new RabbitMqError(message: string, _: unknown, options?: RabbitMqErrorOptions)Properties
- readonly
namestring - readonly
code?number
#RabbitMqNotFoundError
class RabbitMqNotFoundError extends RabbitMqErrorRabbitMqErrorError thrown when a RabbitMQ resource (queue or exchange) is not found.
Constructor
new RabbitMqNotFoundError(message: string, options: RabbitMqNotFoundErrorOptions)Properties
- readonly
namestring - readonly
kind"not_found" - readonly
resourcestring
#RabbitMqPreconditionFailedError
class RabbitMqPreconditionFailedError extends RabbitMqErrorRabbitMqErrorError thrown when a RabbitMQ precondition check fails.
Constructor
new RabbitMqPreconditionFailedError(message: string, options: RabbitMqPreconditionFailedErrorOptions)Properties
- readonly
namestring - readonly
kind"precondition_failed" - readonly
reasonstring
#RedisCommandError
class RedisCommandError extends RedisErrorRedisErrorError thrown when a Redis command fails.
Constructor
new RedisCommandError(message: string, options: RedisCommandErrorOptions)Properties
- readonly
namestring - readonly
kind"command" - readonly
commandstring
#RedisConnectionError
class RedisConnectionError extends RedisErrorRedisErrorError thrown when a Redis connection cannot be established.
Constructor
new RedisConnectionError(message: string, options?: RedisErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#RedisError
class RedisError extends ClientErrorClientErrorBase error class for Redis client errors.
Constructor
new RedisError(message: string, _: unknown, options?: RedisErrorOptions)Properties
- readonly
namestring - readonly
code?string
#RedisScriptError
class RedisScriptError extends RedisErrorRedisErrorError thrown when a Redis Lua script fails.
Constructor
new RedisScriptError(message: string, options: RedisScriptErrorOptions)Properties
- readonly
namestring - readonly
kind"script" - readonly
scriptstring
#SqlError
class SqlError extends ClientErrorClientErrorBase error class for SQL-specific errors. Extends ClientError with SQL-specific properties.
Constructor
new SqlError(message: string, kind: SqlErrorKind, options?: SqlErrorOptions)Properties
- readonly
namestring - readonly
sqlState?string
#SqlQueryResult
class SqlQueryResult<T = Record<string, any>>SQL query result with rows, metadata, and transformation methods.
| Name | Description |
|---|---|
type | — |
ok | — |
rows | — |
rowCount | — |
duration | — |
metadata | — |
map() | Map rows to a new type. |
as() | Create class instances from rows. |
Constructor
new SqlQueryResult(init: SqlQueryResultInit<T>)Properties
- readonly
type"sql" - readonly
okboolean - readonly
rowCountnumber - readonly
durationnumber
Methods
map(): unknownMap rows to a new type.
as(): unknownCreate class instances from rows.
#SqlRows
class SqlRows<T> extends Array<T>Array<T>Row array with first/last helper methods.
Implements ReadonlyArray
| Name | Description |
|---|---|
first() | Get the first row, or undefined if empty. |
firstOrThrow() | Get the first row, or throw if empty. |
last() | Get the last row, or undefined if empty. |
lastOrThrow() | Get the last row, or throw if empty. |
Constructor
new SqlRows(items: readonly T[])Methods
first(): unknownGet the first row, or undefined if empty.
firstOrThrow(): unknownGet the first row, or throw if empty.
last(): unknownGet the last row, or undefined if empty.
lastOrThrow(): unknownGet the last row, or throw if empty.
#SqsBatchError
class SqsBatchError extends SqsErrorSqsErrorError thrown when a batch operation partially fails.
| Name | Description |
|---|---|
name | — |
kind | — |
failedCount | — |
Constructor
new SqsBatchError(message: string, failedCount: number, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
kind"batch" - readonly
failedCountnumber
#SqsCommandError
class SqsCommandError extends SqsErrorSqsErrorError thrown when an SQS command fails.
Constructor
new SqsCommandError(message: string, options: SqsCommandErrorOptions)Properties
- readonly
namestring - readonly
kind"command" - readonly
operationstring
#SqsConnectionError
class SqsConnectionError extends SqsErrorSqsErrorError thrown when an SQS connection cannot be established.
Constructor
new SqsConnectionError(message: string, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
kind"connection"
#SqsError
class SqsError extends ClientErrorClientErrorBase error class for SQS client errors.
Constructor
new SqsError(message: string, _: unknown, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
code?string
#SqsMessageNotFoundError
class SqsMessageNotFoundError extends SqsErrorSqsErrorError thrown when a message is not found or receipt handle is invalid.
Constructor
new SqsMessageNotFoundError(message: string, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
kind"message_not_found"
#SqsMessageTooLargeError
class SqsMessageTooLargeError extends SqsErrorSqsErrorError thrown when a message exceeds the size limit.
Constructor
new SqsMessageTooLargeError(message: string, size: number, maxSize: number, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
kind"message_too_large" - readonly
sizenumber - readonly
maxSizenumber
#SqsQueueNotFoundError
class SqsQueueNotFoundError extends SqsErrorSqsErrorError thrown when a queue is not found.
Constructor
new SqsQueueNotFoundError(message: string, queueUrl: string, options?: SqsErrorOptions)Properties
- readonly
namestring - readonly
kind"queue_not_found" - readonly
queueUrlstring
Interfaces
#AnythingExpectation
interface AnythingExpectationChainable expectation interface for any value using @std/expect matchers.
Unlike @std/expect which returns void from matchers, this interface returns
this to enable method chaining.
| Name | Description |
|---|---|
not | Negates the next assertion. |
toBe() | Asserts that the value is strictly equal (`===`) to the expected value. |
toEqual() | Asserts that the value is deeply equal to the expected value. |
toStrictEqual() | Asserts that the value is strictly deeply equal to the expected value. |
toMatch() | Asserts that the string matches the expected pattern. |
toMatchObject() | Asserts that the object matches a subset of properties. |
toBeDefined() | Asserts that the value is not `undefined`. |
toBeUndefined() | Asserts that the value is `undefined`. |
toBeNull() | Asserts that the value is `null`. |
toBeNaN() | Asserts that the value is `NaN`. |
toBeTruthy() | Asserts that the value is truthy (not `false`, `0`, `""`, `null`, `undefined`, or `NaN`). |
toBeFalsy() | Asserts that the value is falsy (`false`, `0`, `""`, `null`, `undefined`, or `NaN`). |
toContain() | Asserts that an array or string contains the expected item or substring. |
toContainEqual() | Asserts that an array contains an item equal to the expected value. |
toHaveLength() | Asserts that the array or string has the expected length. |
toBeGreaterThan() | Asserts that the number is greater than the expected value. |
toBeGreaterThanOrEqual() | Asserts that the number is greater than or equal to the expected value. |
toBeLessThan() | Asserts that the number is less than the expected value. |
toBeLessThanOrEqual() | Asserts that the number is less than or equal to the expected value. |
toBeCloseTo() | Asserts that the number is close to the expected value within a certain precision. |
toBeInstanceOf() | Asserts that the value is an instance of the expected class. |
toThrow() | Asserts that a function throws an error matching the expected pattern. |
toHaveProperty() | Asserts that the object has a property at the specified path. |
toHaveBeenCalled() | Asserts that a mock function was called at least once. |
toHaveBeenCalledTimes() | Asserts that a mock function was called exactly the specified number of times. |
toHaveBeenCalledWith() | Asserts that a mock function was called with the specified arguments. |
toHaveBeenLastCalledWith() | Asserts that a mock function was last called with the specified arguments. |
toHaveBeenNthCalledWith() | Asserts that the nth call of a mock function was with the specified arguments. |
toHaveReturned() | Asserts that a mock function returned successfully at least once. |
toHaveReturnedTimes() | Asserts that a mock function returned successfully the specified number of times. |
toHaveReturnedWith() | Asserts that a mock function returned the specified value at least once. |
toHaveLastReturnedWith() | Asserts that a mock function last returned the specified value. |
toHaveNthReturnedWith() | Asserts that the nth call of a mock function returned the specified value. |
Properties
- readonly
notthisNegates the next assertion.
Methods
toBe(expected: unknown): thisAsserts that the value is strictly equal (===) to the expected value.
Parameters
expectedunknown- The expected value
toEqual(expected: unknown): thisAsserts that the value is deeply equal to the expected value.
Parameters
expectedunknown- The expected value
toStrictEqual(expected: unknown): thisAsserts that the value is strictly deeply equal to the expected value.
Unlike toEqual, this checks object types and undefined properties.
Parameters
expectedunknown- The expected value
toMatch(expected: string | RegExp): thisAsserts that the string matches the expected pattern.
Parameters
expectedstring | RegExp- A string or RegExp pattern
toMatchObject(expected: Record<string, unknown>): thisAsserts that the object matches a subset of properties.
Parameters
expectedRecord<string, unknown>- An object containing expected properties
toBeDefined(): thisAsserts that the value is not undefined.
toBeUndefined(): thisAsserts that the value is undefined.
toBeNull(): thisAsserts that the value is null.
toBeNaN(): thisAsserts that the value is NaN.
toBeTruthy(): thisAsserts that the value is truthy (not false, 0, "", null, undefined, or NaN).
toBeFalsy(): thisAsserts that the value is falsy (false, 0, "", null, undefined, or NaN).
toContain(expected: unknown): thisAsserts that an array or string contains the expected item or substring.
Parameters
expectedunknown- The item or substring to check for
toContainEqual(expected: unknown): thisAsserts that an array contains an item equal to the expected value.
Parameters
expectedunknown- The item to check for equality
toHaveLength(expected: number): thisAsserts that the array or string has the expected length.
Parameters
expectednumber- The expected length
toBeGreaterThan(expected: number): thisAsserts that the number is greater than the expected value.
Parameters
expectednumber- The value to compare against
toBeGreaterThanOrEqual(expected: number): thisAsserts that the number is greater than or equal to the expected value.
Parameters
expectednumber- The value to compare against
toBeLessThan(expected: number): thisAsserts that the number is less than the expected value.
Parameters
expectednumber- The value to compare against
toBeLessThanOrEqual(expected: number): thisAsserts that the number is less than or equal to the expected value.
Parameters
expectednumber- The value to compare against
toBeCloseTo(expected: number, numDigits?: number): thisAsserts that the number is close to the expected value within a certain precision.
Parameters
expectednumber- The expected value
numDigits?number- Number of decimal digits to check (default: 2)
toBeInstanceOf(expected: (_: any[]) => unknown): thisAsserts that the value is an instance of the expected class.
Parameters
expected(_: any[]) => unknown- The expected constructor/class
toThrow(expected?: string | RegExp | Error): thisAsserts that a function throws an error matching the expected pattern.
Parameters
expected?string | RegExp | Error- Optional string, RegExp, or Error to match
toHaveProperty(keyPath: string | string[], expectedValue?: unknown): thisAsserts that the object has a property at the specified path.
Parameters
keyPathstring | string[]- The property path (string or array of strings)
expectedValue?unknown- Optional expected value at the path
toHaveBeenCalled(): thisAsserts that a mock function was called at least once.
toHaveBeenCalledTimes(expected: number): thisAsserts that a mock function was called exactly the specified number of times.
Parameters
expectednumber- The expected number of calls
toHaveBeenCalledWith(_: unknown[]): thisAsserts that a mock function was called with the specified arguments.
Parameters
_unknown[]
toHaveBeenLastCalledWith(_: unknown[]): thisAsserts that a mock function was last called with the specified arguments.
Parameters
_unknown[]
toHaveBeenNthCalledWith(n: number, _: unknown[]): thisAsserts that the nth call of a mock function was with the specified arguments.
Parameters
nnumber- The call index (1-based)
_unknown[]
toHaveReturned(): thisAsserts that a mock function returned successfully at least once.
toHaveReturnedTimes(expected: number): thisAsserts that a mock function returned successfully the specified number of times.
Parameters
expectednumber- The expected number of successful returns
toHaveReturnedWith(expected: unknown): thisAsserts that a mock function returned the specified value at least once.
Parameters
expectedunknown- The expected return value
toHaveLastReturnedWith(expected: unknown): thisAsserts that a mock function last returned the specified value.
Parameters
expectedunknown- The expected return value
toHaveNthReturnedWith(n: number, expected: unknown): thisAsserts that the nth call of a mock function returned the specified value.
Parameters
nnumber- The call index (1-based)
expectedunknown- The expected return value
#ConnectRpcClient
interface ConnectRpcClient 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.
#ConnectRpcClientConfig
interface ConnectRpcClientConfig extends CommonOptionsConfiguration for creating a ConnectRPC client.
| Name | Description |
|---|---|
url | Server URL for ConnectRPC connections. |
protocol | Protocol to use. |
httpVersion | HTTP version to use. |
tls | TLS configuration. |
metadata | Default metadata to send with every request. |
schema | Schema resolution configuration. |
useBinaryFormat | Whether to use binary format for messages. |
throwOnError | Whether to throw ConnectRpcError on non-OK responses (code !== 0). |
Properties
Server URL for ConnectRPC connections.
Can be a URL string or a connection configuration object.
Protocol to use.
HTTP version to use.
TLS configuration. If not provided, uses insecure credentials.
- readonly
metadata?Record<string, string>Default metadata to send with every request.
Schema resolution configuration.
- "reflection": Use Server Reflection to discover services dynamically (default)
- string: Path to FileDescriptorSet binary file (from
buf build --output set.binpb) - Uint8Array: FileDescriptorSet binary data
- FileDescriptorSet: Pre-parsed FileDescriptorSet message object
- readonly
useBinaryFormat?booleanWhether to use binary format for messages.
- readonly
throwOnError?booleanWhether to throw ConnectRpcError on non-OK responses (code !== 0). Can be overridden per-request via ConnectRpcOptions.throwOnError.
#ConnectRpcConnectionConfig
interface ConnectRpcConnectionConfig extends CommonConnectionConfigConnectRPC connection configuration.
Extends CommonConnectionConfig with ConnectRPC-specific options.
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringService path prefix.
#ConnectRpcErrorOptions
interface ConnectRpcErrorOptions 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.
#ConnectRpcOptions
interface ConnectRpcOptions 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.
#ConnectRpcResponse
interface ConnectRpcResponseConnectRPC 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.
#ConnectRpcResponseOptions
interface ConnectRpcResponseOptionsOptions for creating a ConnectRpcResponse.
Properties
- readonly
messagestring - readonly
headersRecord<string, string> - readonly
trailersRecord<string, string> - readonly
durationnumber - readonly
responseMessageunknown
#CookieConfig
interface CookieConfigCookie handling configuration.
| Name | Description |
|---|---|
disabled | Disable automatic cookie handling. |
initial | Initial cookies to populate the cookie jar. |
Properties
- readonly
disabled?booleanDisable automatic cookie handling. When disabled, cookies are not stored or sent automatically.
- readonly
initial?Record<string, string>Initial cookies to populate the cookie jar.
#DenoKvAtomicBuilder
interface DenoKvAtomicBuilderBuilder for atomic KV operations.
| Name | Description |
|---|---|
check() | Add version checks to the atomic operation. |
set() | Set a value in the KV store. |
delete() | Delete a key from the KV store. |
sum() | Atomically add to a bigint value (Deno.KvU64). |
min() | Atomically set to minimum of current and provided value. |
max() | Atomically set to maximum of current and provided value. |
commit() | Commit the atomic operation. |
Methods
check(_: Deno.AtomicCheck[]): thisAdd version checks to the atomic operation. If any check fails, the entire operation will fail.
Parameters
_Deno.AtomicCheck[]
set<T>(key: Deno.KvKey, value: T, options?: { expireIn?: number }): thisSet a value in the KV store.
Parameters
keyDeno.KvKeyvalueToptions?{ expireIn?: number }
delete(key: Deno.KvKey): thisDelete a key from the KV store.
Parameters
keyDeno.KvKey
sum(key: Deno.KvKey, n: bigint): thisAtomically add to a bigint value (Deno.KvU64).
Parameters
keyDeno.KvKeynbigint
min(key: Deno.KvKey, n: bigint): thisAtomically set to minimum of current and provided value.
Parameters
keyDeno.KvKeynbigint
max(key: Deno.KvKey, n: bigint): thisAtomically set to maximum of current and provided value.
Parameters
keyDeno.KvKeynbigint
commit(): Promise<DenoKvAtomicResult>Commit the atomic operation.
#DenoKvAtomicResult
interface DenoKvAtomicResultResult of an atomic operation.
| Name | Description |
|---|---|
type | — |
ok | — |
versionstamp | — |
duration | — |
Properties
- readonly
type"deno-kv:atomic" - readonly
okboolean - readonly
versionstamp?string - readonly
durationnumber
#DenoKvClient
interface DenoKvClient extends AsyncDisposableDeno KV client for Probitas scenario testing.
| Name | Description |
|---|---|
config | Client configuration. |
get() | Get a single value by key. |
getMany() | Get multiple values by keys. |
set() | Set a value. |
delete() | Delete a key. |
list() | List entries by selector. |
atomic() | Create an atomic operation builder. |
close() | Close the KV connection. |
Properties
Client configuration.
Methods
get<T>(key: Deno.KvKey, options?: CommonOptions): Promise<DenoKvGetResult<T>>Get a single value by key.
Parameters
keyDeno.KvKeyoptions?CommonOptions
getMany<T extends readonly unknown[]>(keys: readonly [unknown], options?: CommonOptions): Promise<unknown>Get multiple values by keys.
Parameters
keysreadonly [unknown]options?CommonOptions
set<T>(key: Deno.KvKey, value: T, options?: DenoKvSetOptions): Promise<DenoKvSetResult>Set a value.
Parameters
keyDeno.KvKeyvalueToptions?DenoKvSetOptions
delete(key: Deno.KvKey, options?: CommonOptions): Promise<DenoKvDeleteResult>Delete a key.
Parameters
keyDeno.KvKeyoptions?CommonOptions
list<T>(selector: Deno.KvListSelector, options?: DenoKvListOptions): Promise<DenoKvListResult<T>>List entries by selector.
Parameters
selectorDeno.KvListSelectoroptions?DenoKvListOptions
atomic(): DenoKvAtomicBuilderCreate an atomic operation builder.
close(): Promise<void>Close the KV connection.
#DenoKvClientConfig
interface DenoKvClientConfig extends CommonOptionsConfiguration for DenoKvClient.
| Name | Description |
|---|---|
path | Path to the KV database file. |
Properties
- readonly
path?stringPath to the KV database file. If not specified, uses in-memory storage or Deno Deploy's KV.
#DenoKvDeleteResult
interface DenoKvDeleteResultResult of a delete operation.
Properties
- readonly
type"deno-kv:delete" - readonly
okboolean - readonly
durationnumber
#DenoKvEntries
interface DenoKvEntries<T> extends ReadonlyArray<DenoKvEntry<T>>Collection of KV entries with helper methods.
| Name | Description |
|---|---|
first() | Returns the first entry, or undefined if empty. |
firstOrThrow() | Returns the first entry, or throws if empty. |
last() | Returns the last entry, or undefined if empty. |
lastOrThrow() | Returns the last entry, or throws if empty. |
Methods
first(): DenoKvEntry<T> | undefinedReturns the first entry, or undefined if empty.
firstOrThrow(): DenoKvEntry<T>Returns the first entry, or throws if empty.
last(): DenoKvEntry<T> | undefinedReturns the last entry, or undefined if empty.
lastOrThrow(): DenoKvEntry<T>Returns the last entry, or throws if empty.
#DenoKvEntry
interface DenoKvEntry<T>A single entry in the KV store.
| Name | Description |
|---|---|
key | — |
value | — |
versionstamp | — |
Properties
- readonly
keyDeno.KvKey - readonly
valueT - readonly
versionstampstring
#DenoKvGetResult
interface DenoKvGetResult<T>Result of a get operation.
Properties
- readonly
type"deno-kv:get" - readonly
okboolean - readonly
keyDeno.KvKey - readonly
valueT | null - readonly
versionstampstring | null - readonly
durationnumber
#DenoKvListOptions
interface DenoKvListOptions extends CommonOptionsOptions for list operations.
| Name | Description |
|---|---|
limit | Maximum number of entries to return. |
cursor | Cursor for pagination. |
reverse | Whether to iterate in reverse order. |
Properties
- readonly
limit?numberMaximum number of entries to return.
- readonly
cursor?stringCursor for pagination.
- readonly
reverse?booleanWhether to iterate in reverse order.
#DenoKvListResult
interface DenoKvListResult<T>Result of a list operation.
Properties
- readonly
type"deno-kv:list" - readonly
okboolean - readonly
durationnumber
#DenoKvSetOptions
interface DenoKvSetOptions extends CommonOptionsOptions for set operations.
| Name | Description |
|---|---|
expireIn | Time-to-live in milliseconds. |
Properties
- readonly
expireIn?numberTime-to-live in milliseconds. The entry will automatically expire after this duration.
#DenoKvSetResult
interface DenoKvSetResultResult of a set operation.
| Name | Description |
|---|---|
type | — |
ok | — |
versionstamp | — |
duration | — |
Properties
- readonly
type"deno-kv:set" - readonly
okboolean - readonly
versionstampstring - readonly
durationnumber
#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.
#GraphqlClient
interface GraphqlClient extends AsyncDisposableGraphQL client interface.
| Name | Description |
|---|---|
config | Client configuration |
query() | Execute a GraphQL query |
mutation() | Execute a GraphQL mutation |
execute() | Execute a GraphQL document (query or mutation) |
subscribe() | Subscribe to a GraphQL subscription via WebSocket |
close() | Close the client and release resources |
Properties
Client configuration
Methods
query<TData = any, TVariables = Record<string, any>>(query: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>Execute a GraphQL query
Parameters
querystringvariables?TVariablesoptions?GraphqlOptions
mutation<TData = any, TVariables = Record<string, any>>(mutation: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>Execute a GraphQL mutation
Parameters
mutationstringvariables?TVariablesoptions?GraphqlOptions
execute<TData = any, TVariables = Record<string, any>>(document: string, variables?: TVariables, options?: GraphqlOptions): Promise<GraphqlResponse<TData>>Execute a GraphQL document (query or mutation)
Parameters
documentstringvariables?TVariablesoptions?GraphqlOptions
subscribe<TData = any, TVariables = Record<string, any>>(document: string, variables?: TVariables, options?: GraphqlOptions): AsyncIterable<GraphqlResponse<TData>>Subscribe to a GraphQL subscription via WebSocket
Parameters
documentstringvariables?TVariablesoptions?GraphqlOptions
close(): Promise<void>Close the client and release resources
#GraphqlClientConfig
interface GraphqlClientConfig extends CommonOptionsGraphQL client configuration.
| Name | Description |
|---|---|
url | GraphQL endpoint URL. |
headers | Default headers for all requests |
wsEndpoint | WebSocket endpoint URL (for subscriptions) |
fetch | Custom fetch implementation (for testing/mocking) |
throwOnError | Whether to throw GraphqlError when response contains errors. |
Properties
GraphQL endpoint URL.
Can be a URL string or a connection configuration object.
- readonly
headers?Record<string, string>Default headers for all requests
- readonly
wsEndpoint?stringWebSocket endpoint URL (for subscriptions)
- readonly
fetch?fetchCustom fetch implementation (for testing/mocking)
- readonly
throwOnError?booleanWhether to throw GraphqlError when response contains errors. Can be overridden per-request via GraphqlOptions.
#GraphqlConnectionConfig
interface GraphqlConnectionConfig extends CommonConnectionConfigGraphQL connection configuration.
Extends CommonConnectionConfig with GraphQL-specific options.
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringGraphQL endpoint path.
#GraphqlErrorItem
interface GraphqlErrorItemGraphQL error item as per GraphQL specification.
| Name | Description |
|---|---|
message | Error message |
locations | Location(s) in the GraphQL document where the error occurred |
path | Path to the field that caused the error |
extensions | Additional error metadata |
Properties
- readonly
messagestringError message
- readonly
locations?readonly { line: number; column: number }[]Location(s) in the GraphQL document where the error occurred
- readonly
path?readonly unknown[]Path to the field that caused the error
- readonly
extensions?Record<string, unknown>Additional error metadata
#GraphqlErrorOptions
interface GraphqlErrorOptions extends ErrorOptionsOptions for GraphqlError constructor.
| Name | Description |
|---|---|
response | Associated GraphQL response |
Properties
Associated GraphQL response
#GraphqlOptions
interface GraphqlOptions extends CommonOptionsOptions for individual GraphQL requests.
| Name | Description |
|---|---|
headers | Additional request headers |
operationName | Operation name (for documents with multiple operations) |
throwOnError | Whether to throw GraphqlError when response contains errors. |
Properties
- readonly
headers?Record<string, string>Additional request headers
- readonly
operationName?stringOperation name (for documents with multiple operations)
- readonly
throwOnError?booleanWhether to throw GraphqlError when response contains errors.
#GraphqlResponse
interface GraphqlResponse<T = any>GraphQL response interface with pre-loaded body.
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the request was successful (no errors) |
errors | GraphQL errors array (null if no errors) |
extensions | Response extensions |
duration | Response time in milliseconds |
status | HTTP status code |
headers | Headers from the HTTP response |
raw | Raw Web standard Response (for streaming or special cases) |
data() | Get response data (null if no data). |
Properties
- readonly
type"graphql"Result type identifier
- readonly
okbooleanWhether the request was successful (no errors)
GraphQL errors array (null if no errors)
- readonly
extensions?Record<string, unknown>Response extensions
- readonly
durationnumberResponse time in milliseconds
- readonly
statusnumberHTTP status code
- readonly
headersHeadersHeaders from the HTTP response
- readonly
rawglobalThis.ResponseRaw Web standard Response (for streaming or special cases)
Methods
data<U = T>(): U | nullGet response data (null if no data). Does not throw even if errors are present.
#GraphqlResponseOptions
interface GraphqlResponseOptions<T>Options for creating a GraphqlResponse.
Properties
- readonly
dataT | null - readonly
extensions?Record<string, unknown> - readonly
durationnumber - readonly
statusnumber - readonly
rawglobalThis.Response
#GrpcClientConfig
interface GrpcClientConfig extends Omit<ConnectRpcClientConfig, "protocol">Configuration for creating a gRPC client.
This is a subset of ConnectRpcClientConfig with protocol fixed to "grpc".
#HttpClient
interface HttpClient extends AsyncDisposableHTTP client interface.
| Name | Description |
|---|---|
config | Client configuration |
get() | Send GET request |
post() | Send POST request |
put() | Send PUT request |
patch() | Send PATCH request |
delete() | Send DELETE request |
request() | Send request with arbitrary method |
getCookies() | Get all cookies in the cookie jar. |
setCookie() | Set a cookie in the cookie jar. |
clearCookies() | Clear all cookies from the cookie jar. |
close() | Close the client and release resources |
Properties
Client configuration
Methods
get(path: string, options?: HttpOptions): Promise<HttpResponse>Send GET request
Parameters
pathstringoptions?HttpOptions
post(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>Send POST request
Parameters
pathstringbody?BodyInitoptions?HttpOptions
put(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>Send PUT request
Parameters
pathstringbody?BodyInitoptions?HttpOptions
patch(path: string, body?: BodyInit, options?: HttpOptions): Promise<HttpResponse>Send PATCH request
Parameters
pathstringbody?BodyInitoptions?HttpOptions
delete(path: string, options?: HttpOptions): Promise<HttpResponse>Send DELETE request
Parameters
pathstringoptions?HttpOptions
request(method: string, path: string, options?: HttpOptions & { body?: BodyInit }): Promise<HttpResponse>Send request with arbitrary method
Parameters
methodstringpathstringoptions?HttpOptions & { body?: BodyInit }
getCookies(): Record<string, string>Get all cookies in the cookie jar. Returns empty object if cookies are disabled.
setCookie(name: string, value: string): voidSet a cookie in the cookie jar.
Parameters
namestringvaluestring
clearCookies(): voidClear all cookies from the cookie jar. No-op if cookies are disabled.
close(): Promise<void>Close the client and release resources
#HttpClientConfig
interface HttpClientConfig extends CommonOptionsHTTP client configuration.
| Name | Description |
|---|---|
url | Base URL for all requests. |
headers | Default headers for all requests |
fetch | Custom fetch implementation (for testing/mocking) |
redirect | Default redirect handling mode. |
throwOnError | Whether to throw HttpError for non-2xx responses. |
cookies | Cookie handling configuration. |
Properties
Base URL for all requests.
Can be a URL string or a connection configuration object.
- readonly
headers?Record<string, string>Default headers for all requests
- readonly
fetch?fetchCustom fetch implementation (for testing/mocking)
Default redirect handling mode. Can be overridden per-request via HttpOptions.
- readonly
throwOnError?booleanWhether to throw HttpError for non-2xx responses. Can be overridden per-request via HttpOptions.
#HttpConnectionConfig
interface HttpConnectionConfig extends CommonConnectionConfigHTTP connection configuration.
Extends CommonConnectionConfig with HTTP-specific options.
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringBase path prefix for all requests.
#HttpErrorOptions
interface HttpErrorOptions extends ErrorOptionsOptions for HttpError constructor.
| Name | Description |
|---|---|
response | Associated HTTP response |
Properties
Associated HTTP response
#HttpOptions
interface HttpOptions extends CommonOptionsOptions for individual HTTP requests.
| Name | Description |
|---|---|
query | Query parameters (arrays for multi-value params) |
headers | Additional request headers |
redirect | Redirect handling mode. |
throwOnError | Whether to throw HttpError for non-2xx responses. |
Properties
Query parameters (arrays for multi-value params)
- readonly
headers?Record<string, string>Additional request headers
Redirect handling mode.
- readonly
throwOnError?booleanWhether to throw HttpError for non-2xx responses. When false, non-2xx responses are returned as HttpResponse.
#HttpResponse
interface HttpResponseHTTP response with pre-loaded body for synchronous access.
Wraps Web standard Response, allowing body to be read synchronously and multiple times (unlike the streaming-based standard Response).
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the response was successful (status 200-299) |
status | HTTP status code |
statusText | HTTP status text |
headers | Response headers |
url | Request URL |
body | Response body as raw bytes (null if no body) |
duration | Response time in milliseconds |
raw | Raw Web standard Response (for streaming or special cases) |
arrayBuffer() | Get body as ArrayBuffer (null if no body) |
blob() | Get body as Blob (null if no body) |
text() | Get body as text (null if no body) |
data() | Get body as parsed JSON (null if no body) |
Properties
- readonly
type"http"Result type identifier
- readonly
okbooleanWhether the response was successful (status 200-299)
- readonly
statusnumberHTTP status code
- readonly
statusTextstringHTTP status text
- readonly
headersHeadersResponse headers
- readonly
urlstringRequest URL
- readonly
bodyUint8Array | nullResponse body as raw bytes (null if no body)
- readonly
durationnumberResponse time in milliseconds
- readonly
rawglobalThis.ResponseRaw Web standard Response (for streaming or special cases)
Methods
arrayBuffer(): ArrayBuffer | nullGet body as ArrayBuffer (null if no body)
blob(): Blob | nullGet body as Blob (null if no body)
text(): string | nullGet body as text (null if no body)
data<T = any>(): T | nullGet body as parsed JSON (null if no body)
#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
#MongoClient
interface MongoClient extends AsyncDisposableMongoDB client interface
| Name | Description |
|---|---|
config | — |
collection() | — |
db() | — |
transaction() | — |
close() | — |
Properties
Methods
collection<T extends Document = Document>(name: string): MongoCollection<T>Parameters
namestring
db(name: string): MongoClientParameters
namestring
transaction<T>(fn: (session: MongoSession) => unknown): Promise<T>Parameters
fn(session: MongoSession) => unknown
close(): Promise<void>#MongoClientConfig
interface MongoClientConfig extends CommonOptionsMongoDB client configuration.
Examples
Using a connection string
const config: MongoClientConfig = {
url: "mongodb://localhost:27017",
database: "testdb",
};
Using a configuration object
const config: MongoClientConfig = {
url: {
host: "localhost",
port: 27017,
username: "admin",
password: "secret",
authSource: "admin",
},
database: "testdb",
};
| Name | Description |
|---|---|
url | MongoDB connection URL or configuration object. |
database | Database name to connect to. |
Properties
MongoDB connection URL or configuration object.
- readonly
databasestringDatabase name to connect to.
#MongoCollection
interface MongoCollection<T extends Document>MongoDB collection interface
| Name | Description |
|---|---|
find() | — |
findOne() | — |
insertOne() | — |
insertMany() | — |
updateOne() | — |
updateMany() | — |
deleteOne() | — |
deleteMany() | — |
aggregate() | — |
countDocuments() | — |
Methods
find(filter?: Filter, options?: MongoFindOptions): Promise<MongoFindResult<T>>Parameters
filter?Filteroptions?MongoFindOptions
findOne(filter: Filter, options?: CommonOptions): Promise<MongoFindOneResult<T>>Parameters
filterFilteroptions?CommonOptions
insertOne(doc: Omit<T, "_id">, options?: CommonOptions): Promise<MongoInsertOneResult>Parameters
docOmit<T, "_id">options?CommonOptions
insertMany(docs: Omit<T, "_id">[], options?: CommonOptions): Promise<MongoInsertManyResult>Parameters
docsOmit<T, "_id">[]options?CommonOptions
updateOne(filter: Filter, update: UpdateFilter, options?: MongoUpdateOptions): Promise<MongoUpdateResult>Parameters
filterFilterupdateUpdateFilteroptions?MongoUpdateOptions
updateMany(filter: Filter, update: UpdateFilter, options?: MongoUpdateOptions): Promise<MongoUpdateResult>Parameters
filterFilterupdateUpdateFilteroptions?MongoUpdateOptions
deleteOne(filter: Filter, options?: CommonOptions): Promise<MongoDeleteResult>Parameters
filterFilteroptions?CommonOptions
deleteMany(filter: Filter, options?: CommonOptions): Promise<MongoDeleteResult>Parameters
filterFilteroptions?CommonOptions
aggregate<R = T>(pipeline: Document[], options?: CommonOptions): Promise<MongoFindResult<R>>Parameters
pipelineDocument[]options?CommonOptions
countDocuments(filter?: Filter, options?: CommonOptions): Promise<MongoCountResult>Parameters
filter?Filteroptions?CommonOptions
#MongoConnectionConfig
interface MongoConnectionConfig extends CommonConnectionConfigMongoDB connection configuration.
Extends CommonConnectionConfig with MongoDB-specific options.
| Name | Description |
|---|---|
database | Database name to connect to. |
authSource | Authentication database. |
replicaSet | Replica set name. |
Properties
- readonly
database?stringDatabase name to connect to.
- readonly
authSource?stringAuthentication database.
- readonly
replicaSet?stringReplica set name.
#MongoCountResult
interface MongoCountResultCount result
Properties
- readonly
type"mongo:count" - readonly
okboolean - readonly
countnumber - readonly
durationnumber
#MongoDeleteResult
interface MongoDeleteResultDelete result
| Name | Description |
|---|---|
type | — |
ok | — |
deletedCount | — |
duration | — |
Properties
- readonly
type"mongo:delete" - readonly
okboolean - readonly
deletedCountnumber - readonly
durationnumber
#MongoDocs
interface MongoDocs<T> extends ReadonlyArray<T>Document array with first/last methods
| Name | Description |
|---|---|
first() | — |
firstOrThrow() | — |
last() | — |
lastOrThrow() | — |
Methods
first(): T | undefinedfirstOrThrow(): Tlast(): T | undefinedlastOrThrow(): T#MongoErrorOptions
interface MongoErrorOptions extends ErrorOptionsOptions for MongoDB errors.
| Name | Description |
|---|---|
code | — |
Properties
- readonly
code?number
#MongoFindOneResult
interface MongoFindOneResult<T = Document>FindOne result
Properties
- readonly
type"mongo:find-one" - readonly
okboolean - readonly
docT | undefined - readonly
durationnumber
#MongoFindOptions
interface MongoFindOptions extends CommonOptionsMongoDB find options
| Name | Description |
|---|---|
sort | — |
limit | — |
skip | — |
projection | — |
Properties
- readonly
sort?Record<string, 1 | -1> - readonly
limit?number - readonly
skip?number - readonly
projection?Record<string, 0 | 1>
#MongoFindResult
interface MongoFindResult<T = Document>Query result (find, aggregate)
Properties
- readonly
type"mongo:find" - readonly
okboolean - readonly
durationnumber
#MongoInsertManyResult
interface MongoInsertManyResultInsert many result
| Name | Description |
|---|---|
type | — |
ok | — |
insertedIds | — |
insertedCount | — |
duration | — |
Properties
- readonly
type"mongo:insert" - readonly
okboolean - readonly
insertedIdsreadonly string[] - readonly
insertedCountnumber - readonly
durationnumber
#MongoInsertOneResult
interface MongoInsertOneResultInsert one result
| Name | Description |
|---|---|
type | — |
ok | — |
insertedId | — |
duration | — |
Properties
- readonly
type"mongo:insert" - readonly
okboolean - readonly
insertedIdstring - readonly
durationnumber
#MongoSession
interface MongoSessionMongoDB session interface (for transactions)
| Name | Description |
|---|---|
collection() | — |
Methods
collection<T extends Document = Document>(name: string): MongoCollection<T>Parameters
namestring
#MongoUpdateOptions
interface MongoUpdateOptions extends CommonOptionsMongoDB update options
| Name | Description |
|---|---|
upsert | — |
Properties
- readonly
upsert?boolean
#MongoUpdateResult
interface MongoUpdateResultUpdate result
| Name | Description |
|---|---|
type | — |
ok | — |
matchedCount | — |
modifiedCount | — |
upsertedId | — |
duration | — |
Properties
- readonly
type"mongo:update" - readonly
okboolean - readonly
matchedCountnumber - readonly
modifiedCountnumber - readonly
upsertedId?string - readonly
durationnumber
#RabbitMqAckResult
interface RabbitMqAckResultAck/Nack result.
Properties
- readonly
type"rabbitmq:ack" - readonly
okboolean - readonly
durationnumber
#RabbitMqChannel
interface RabbitMqChannel extends AsyncDisposableRabbitMQ channel interface.
| Name | Description |
|---|---|
assertExchange() | — |
deleteExchange() | — |
assertQueue() | — |
deleteQueue() | — |
purgeQueue() | — |
bindQueue() | — |
unbindQueue() | — |
publish() | — |
sendToQueue() | — |
get() | — |
consume() | — |
ack() | — |
nack() | — |
reject() | — |
prefetch() | — |
close() | — |
Methods
assertExchange(name: string, type: RabbitMqExchangeType, options?: RabbitMqExchangeOptions): Promise<RabbitMqExchangeResult>Parameters
namestringoptions?RabbitMqExchangeOptions
deleteExchange(name: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>Parameters
namestringoptions?CommonOptions
assertQueue(name: string, options?: RabbitMqQueueOptions): Promise<RabbitMqQueueResult>Parameters
namestringoptions?RabbitMqQueueOptions
deleteQueue(name: string, options?: CommonOptions): Promise<RabbitMqQueueResult>Parameters
namestringoptions?CommonOptions
purgeQueue(name: string, options?: CommonOptions): Promise<RabbitMqQueueResult>Parameters
namestringoptions?CommonOptions
bindQueue(queue: string, exchange: string, routingKey: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>Parameters
queuestringexchangestringroutingKeystringoptions?CommonOptions
unbindQueue(queue: string, exchange: string, routingKey: string, options?: CommonOptions): Promise<RabbitMqExchangeResult>Parameters
queuestringexchangestringroutingKeystringoptions?CommonOptions
publish(exchange: string, routingKey: string, content: Uint8Array, options?: RabbitMqPublishOptions): Promise<RabbitMqPublishResult>Parameters
exchangestringroutingKeystringcontentUint8Arrayoptions?RabbitMqPublishOptions
sendToQueue(queue: string, content: Uint8Array, options?: RabbitMqPublishOptions): Promise<RabbitMqPublishResult>Parameters
queuestringcontentUint8Arrayoptions?RabbitMqPublishOptions
get(queue: string, options?: CommonOptions): Promise<RabbitMqConsumeResult>Parameters
queuestringoptions?CommonOptions
consume(queue: string, options?: RabbitMqConsumeOptions): AsyncIterable<RabbitMqMessage>Parameters
queuestringoptions?RabbitMqConsumeOptions
ack(message: RabbitMqMessage, options?: CommonOptions): Promise<RabbitMqAckResult>Parameters
messageRabbitMqMessageoptions?CommonOptions
nack(message: RabbitMqMessage, options?: RabbitMqNackOptions): Promise<RabbitMqAckResult>Parameters
messageRabbitMqMessageoptions?RabbitMqNackOptions
reject(message: RabbitMqMessage, requeue?: boolean): Promise<RabbitMqAckResult>Parameters
messageRabbitMqMessagerequeue?boolean
prefetch(count: number): Promise<void>Parameters
countnumber
close(): Promise<void>#RabbitMqChannelErrorOptions
interface RabbitMqChannelErrorOptions extends RabbitMqErrorOptionsOptions for RabbitMQ channel errors.
| Name | Description |
|---|---|
channelId | — |
Properties
- readonly
channelId?number
#RabbitMqClient
interface RabbitMqClient extends AsyncDisposableRabbitMQ client interface.
Properties
Methods
channel(): Promise<RabbitMqChannel>close(): Promise<void>#RabbitMqClientConfig
interface RabbitMqClientConfig extends CommonOptionsRabbitMQ client configuration.
| Name | Description |
|---|---|
url | RabbitMQ connection URL or configuration object. |
heartbeat | Heartbeat interval in seconds |
prefetch | Default prefetch count for channels |
Properties
RabbitMQ connection URL or configuration object.
- readonly
heartbeat?numberHeartbeat interval in seconds
- readonly
prefetch?numberDefault prefetch count for channels
#RabbitMqConnectionConfig
interface RabbitMqConnectionConfig extends CommonConnectionConfigRabbitMQ connection configuration.
Extends CommonConnectionConfig with RabbitMQ-specific options.
| Name | Description |
|---|---|
vhost | Virtual host. |
Properties
- readonly
vhost?stringVirtual host.
#RabbitMqConsumeOptions
interface RabbitMqConsumeOptions extends CommonOptionsConsume options.
Properties
- readonly
noAck?boolean - readonly
exclusive?boolean - readonly
priority?number
#RabbitMqConsumeResult
interface RabbitMqConsumeResultConsume result (single message retrieval).
Properties
- readonly
type"rabbitmq:consume" - readonly
okboolean - readonly
durationnumber
#RabbitMqErrorOptions
interface RabbitMqErrorOptions extends ErrorOptionsOptions for RabbitMQ errors.
| Name | Description |
|---|---|
code | — |
Properties
- readonly
code?number
#RabbitMqExchangeOptions
interface RabbitMqExchangeOptions extends CommonOptionsExchange options.
| Name | Description |
|---|---|
durable | — |
autoDelete | — |
internal | — |
arguments | — |
Properties
- readonly
durable?boolean - readonly
autoDelete?boolean - readonly
internal?boolean - readonly
arguments?Record<string, unknown>
#RabbitMqExchangeResult
interface RabbitMqExchangeResultExchange declaration result.
Properties
- readonly
type"rabbitmq:exchange" - readonly
okboolean - readonly
durationnumber
#RabbitMqMessage
interface RabbitMqMessageRabbitMQ message.
| Name | Description |
|---|---|
content | — |
properties | — |
fields | — |
Properties
- readonly
contentUint8Array
#RabbitMqMessageFields
interface RabbitMqMessageFieldsRabbitMQ message fields.
| Name | Description |
|---|---|
deliveryTag | — |
redelivered | — |
exchange | — |
routingKey | — |
Properties
- readonly
deliveryTagbigint - readonly
redeliveredboolean - readonly
exchangestring - readonly
routingKeystring
#RabbitMqMessageProperties
interface RabbitMqMessagePropertiesRabbitMQ message properties.
| Name | Description |
|---|---|
contentType | — |
contentEncoding | — |
headers | — |
deliveryMode | 1: non-persistent, 2: persistent |
priority | — |
correlationId | — |
replyTo | — |
expiration | — |
messageId | — |
timestamp | — |
type | — |
userId | — |
appId | — |
Properties
- readonly
contentType?string - readonly
contentEncoding?string - readonly
headers?Record<string, unknown> - readonly
deliveryMode?1 | 21: non-persistent, 2: persistent
- readonly
priority?number - readonly
correlationId?string - readonly
replyTo?string - readonly
expiration?string - readonly
messageId?string - readonly
timestamp?number - readonly
type?string - readonly
userId?string - readonly
appId?string
#RabbitMqNackOptions
interface RabbitMqNackOptions extends CommonOptionsNack options.
Properties
- readonly
requeue?boolean - readonly
allUpTo?boolean
#RabbitMqNotFoundErrorOptions
interface RabbitMqNotFoundErrorOptions extends RabbitMqErrorOptionsOptions for RabbitMQ not found errors.
| Name | Description |
|---|---|
resource | — |
Properties
- readonly
resourcestring
#RabbitMqPreconditionFailedErrorOptions
interface RabbitMqPreconditionFailedErrorOptions extends RabbitMqErrorOptionsOptions for RabbitMQ precondition failed errors.
| Name | Description |
|---|---|
reason | — |
Properties
- readonly
reasonstring
#RabbitMqPublishOptions
interface RabbitMqPublishOptions extends CommonOptionsPublish options.
| Name | Description |
|---|---|
persistent | — |
contentType | — |
contentEncoding | — |
headers | — |
correlationId | — |
replyTo | — |
expiration | — |
messageId | — |
priority | — |
Properties
- readonly
persistent?boolean - readonly
contentType?string - readonly
contentEncoding?string - readonly
headers?Record<string, unknown> - readonly
correlationId?string - readonly
replyTo?string - readonly
expiration?string - readonly
messageId?string - readonly
priority?number
#RabbitMqPublishResult
interface RabbitMqPublishResultPublish result.
Properties
- readonly
type"rabbitmq:publish" - readonly
okboolean - readonly
durationnumber
#RabbitMqQueueOptions
interface RabbitMqQueueOptions extends CommonOptionsQueue options.
| Name | Description |
|---|---|
durable | — |
exclusive | — |
autoDelete | — |
arguments | — |
messageTtl | — |
maxLength | — |
deadLetterExchange | — |
deadLetterRoutingKey | — |
Properties
- readonly
durable?boolean - readonly
exclusive?boolean - readonly
autoDelete?boolean - readonly
arguments?Record<string, unknown> - readonly
messageTtl?number - readonly
maxLength?number - readonly
deadLetterExchange?string - readonly
deadLetterRoutingKey?string
#RabbitMqQueueResult
interface RabbitMqQueueResultQueue declaration result.
| Name | Description |
|---|---|
type | — |
ok | — |
queue | — |
messageCount | — |
consumerCount | — |
duration | — |
Properties
- readonly
type"rabbitmq:queue" - readonly
okboolean - readonly
queuestring - readonly
messageCountnumber - readonly
consumerCountnumber - readonly
durationnumber
#RedisArrayResult
interface RedisArrayResult<T = string> extends RedisResultBase<readonly T[]>Redis array result (LRANGE, SMEMBERS, etc.)
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:array"
#RedisClient
interface RedisClient extends AsyncDisposableRedis client interface
Properties
Methods
get(key: string, options?: CommonOptions): Promise<RedisGetResult>Parameters
keystringoptions?CommonOptions
set(key: string, value: string, options?: RedisSetOptions): Promise<RedisSetResult>Parameters
keystringvaluestringoptions?RedisSetOptions
del(_: string[]): Promise<RedisCountResult>Parameters
_string[]
incr(key: string): Promise<RedisCountResult>Parameters
keystring
decr(key: string): Promise<RedisCountResult>Parameters
keystring
hget(key: string, field: string, options?: CommonOptions): Promise<RedisGetResult>Parameters
keystringfieldstringoptions?CommonOptions
hset(key: string, field: string, value: string, options?: CommonOptions): Promise<RedisCountResult>Parameters
keystringfieldstringvaluestringoptions?CommonOptions
hgetall(key: string, options?: CommonOptions): Promise<RedisHashResult>Parameters
keystringoptions?CommonOptions
hdel(key: string, _: string[]): Promise<RedisCountResult>Parameters
keystring_string[]
lpush(key: string, _: string[]): Promise<RedisCountResult>Parameters
keystring_string[]
rpush(key: string, _: string[]): Promise<RedisCountResult>Parameters
keystring_string[]
lpop(key: string): Promise<RedisGetResult>Parameters
keystring
rpop(key: string): Promise<RedisGetResult>Parameters
keystring
lrange(key: string, start: number, stop: number, options?: CommonOptions): Promise<RedisArrayResult>Parameters
keystringstartnumberstopnumberoptions?CommonOptions
llen(key: string): Promise<RedisCountResult>Parameters
keystring
sadd(key: string, _: string[]): Promise<RedisCountResult>Parameters
keystring_string[]
srem(key: string, _: string[]): Promise<RedisCountResult>Parameters
keystring_string[]
smembers(key: string, options?: CommonOptions): Promise<RedisArrayResult>Parameters
keystringoptions?CommonOptions
sismember(key: string, member: string): Promise<RedisCommonResult<boolean>>Parameters
keystringmemberstring
zadd(key: string, _: { score: number; member: string }[]): Promise<RedisCountResult>Parameters
keystring_{ score: number; member: string }[]
zrange(key: string, start: number, stop: number, options?: CommonOptions): Promise<RedisArrayResult>Parameters
keystringstartnumberstopnumberoptions?CommonOptions
zscore(key: string, member: string): Promise<RedisCommonResult<number | null>>Parameters
keystringmemberstring
publish(channel: string, message: string): Promise<RedisCountResult>Parameters
channelstringmessagestring
subscribe(channel: string): AsyncIterable<RedisMessage>Parameters
channelstring
multi(): RedisTransactioncommand<T = unknown>(cmd: string, _: unknown[]): Promise<RedisCommonResult<T>>Parameters
cmdstring_unknown[]
close(): Promise<void>#RedisClientConfig
interface RedisClientConfig extends CommonOptionsRedis client configuration.
| Name | Description |
|---|---|
url | Redis connection URL or configuration object. |
Properties
Redis connection URL or configuration object.
#RedisCommandErrorOptions
interface RedisCommandErrorOptions extends RedisErrorOptionsOptions for Redis command errors.
| Name | Description |
|---|---|
command | — |
Properties
- readonly
commandstring
#RedisCommonResult
interface RedisCommonResult<T = unknown> extends RedisResultBase<T>Redis operation result (common/generic)
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:common"
#RedisConnectionConfig
interface RedisConnectionConfig extends CommonConnectionConfigRedis connection configuration.
Extends CommonConnectionConfig with Redis-specific options.
| Name | Description |
|---|---|
db | Database index. |
Properties
- readonly
db?numberDatabase index.
#RedisCountResult
interface RedisCountResult extends RedisResultBase<number>Redis numeric result (DEL, LPUSH, SADD, etc.)
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:count"
#RedisErrorOptions
interface RedisErrorOptions extends ErrorOptionsOptions for Redis errors.
| Name | Description |
|---|---|
code | — |
Properties
- readonly
code?string
#RedisGetResult
interface RedisGetResult extends RedisResultBase<string | null>Redis GET result
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:get"
#RedisHashResult
interface RedisHashResult extends RedisResultBase<Record<string, string>>Redis hash result (HGETALL)
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:hash"
#RedisMessage
interface RedisMessageRedis Pub/Sub message
Properties
- readonly
channelstring - readonly
messagestring
#RedisResultBase
interface RedisResultBase<T = unknown>Base interface for Redis operation results. All Redis result types extend this interface.
Properties
- readonly
typestring - readonly
okboolean - readonly
valueT - readonly
durationnumber
#RedisScriptErrorOptions
interface RedisScriptErrorOptions extends RedisErrorOptionsOptions for Redis script errors.
| Name | Description |
|---|---|
script | — |
Properties
- readonly
scriptstring
#RedisSetOptions
interface RedisSetOptions extends CommonOptionsRedis SET options
| Name | Description |
|---|---|
ex | Expiration in seconds |
px | Expiration in milliseconds |
nx | Only set if key does not exist |
xx | Only set if key exists |
Properties
- readonly
ex?numberExpiration in seconds
- readonly
px?numberExpiration in milliseconds
- readonly
nx?booleanOnly set if key does not exist
- readonly
xx?booleanOnly set if key exists
#RedisSetResult
interface RedisSetResult extends RedisResultBase<"OK">Redis SET result
| Name | Description |
|---|---|
type | — |
Properties
- readonly
type"redis:set"
#RedisTransaction
interface RedisTransactionRedis transaction interface
Methods
get(key: string): thisParameters
keystring
set(key: string, value: string, options?: RedisSetOptions): thisParameters
keystringvaluestringoptions?RedisSetOptions
del(_: string[]): thisParameters
_string[]
incr(key: string): thisParameters
keystring
decr(key: string): thisParameters
keystring
hget(key: string, field: string): thisParameters
keystringfieldstring
hset(key: string, field: string, value: string): thisParameters
keystringfieldstringvaluestring
hgetall(key: string): thisParameters
keystring
hdel(key: string, _: string[]): thisParameters
keystring_string[]
lpush(key: string, _: string[]): thisParameters
keystring_string[]
rpush(key: string, _: string[]): thisParameters
keystring_string[]
lpop(key: string): thisParameters
keystring
rpop(key: string): thisParameters
keystring
lrange(key: string, start: number, stop: number): thisParameters
keystringstartnumberstopnumber
llen(key: string): thisParameters
keystring
sadd(key: string, _: string[]): thisParameters
keystring_string[]
srem(key: string, _: string[]): thisParameters
keystring_string[]
smembers(key: string): thisParameters
keystring
sismember(key: string, member: string): thisParameters
keystringmemberstring
zadd(key: string, _: { score: number; member: string }[]): thisParameters
keystring_{ score: number; member: string }[]
zrange(key: string, start: number, stop: number): thisParameters
keystringstartnumberstopnumber
zscore(key: string, member: string): thisParameters
keystringmemberstring
exec(): Promise<RedisArrayResult<unknown>>discard(): void#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
#SqlErrorOptions
interface SqlErrorOptions extends ErrorOptionsOptions for SqlError constructor.
| Name | Description |
|---|---|
sqlState | SQL State code (e.g., "23505" for unique violation) |
Properties
- readonly
sqlState?stringSQL State code (e.g., "23505" for unique violation)
#SqlQueryResultExpectation
interface SqlQueryResultExpectation<T>Expectation interface for SQL query results.
All methods return this for chaining.
| Name | Description |
|---|---|
not | Negates the next assertion. |
toBeSuccessful() | Asserts that the query succeeded. |
toHaveContent() | Asserts that the result has at least one row. |
toHaveLength() | Asserts that the row count matches the expected value. |
toHaveLengthGreaterThanOrEqual() | Asserts that the row count is at least the expected value. |
toHaveLengthLessThanOrEqual() | Asserts that the row count is at most the expected value. |
toHaveRowCount() | Asserts that the affected row count matches the expected value. |
toHaveRowCountGreaterThanOrEqual() | Asserts that the affected row count is at least the expected value. |
toHaveRowCountLessThanOrEqual() | Asserts that the affected row count is at most the expected value. |
toMatchObject() | Asserts that at least one row contains the given subset of properties. |
toSatisfy() | Validates the rows using a custom matcher function. |
toHaveMapContaining() | Asserts that at least one mapped row contains the given subset. |
toHaveMapMatching() | Validates the mapped rows using a custom matcher function. |
toHaveInstanceContaining() | Asserts that at least one instance created from rows contains the given subset. |
toHaveInstanceMatching() | Validates instances created from rows using a custom matcher function. |
toHaveLastInsertId() | Asserts that the lastInsertId matches the expected value. |
toHaveLastInsertId() | Asserts that the lastInsertId is present. |
toHaveDurationLessThan() | Asserts that the query duration is less than the threshold. |
toHaveDurationLessThanOrEqual() | Asserts that the query duration is at most the threshold. |
toHaveDurationGreaterThan() | Asserts that the query duration is greater than the threshold. |
toHaveDurationGreaterThanOrEqual() | Asserts that the query duration is at least the threshold. |
Properties
- readonly
notthisNegates the next assertion.
Methods
toBeSuccessful(): thisAsserts that the query succeeded.
toHaveContent(): thisAsserts that the result has at least one row.
toHaveLength(expected: number): thisAsserts that the row count matches the expected value.
Parameters
expectednumber- The expected number of rows
toHaveLengthGreaterThanOrEqual(expected: number): thisAsserts that the row count is at least the expected value.
Parameters
expectednumber- The minimum expected number of rows
toHaveLengthLessThanOrEqual(expected: number): thisAsserts that the row count is at most the expected value.
Parameters
expectednumber- The maximum expected number of rows
toHaveRowCount(count: number): thisAsserts that the affected row count matches the expected value.
Parameters
countnumber- The expected affected row count
toHaveRowCountGreaterThanOrEqual(count: number): thisAsserts that the affected row count is at least the expected value.
Parameters
countnumber- The minimum expected affected row count
toHaveRowCountLessThanOrEqual(count: number): thisAsserts that the affected row count is at most the expected value.
Parameters
countnumber- The maximum expected affected row count
toMatchObject(subset: Partial<T>): thisAsserts that at least one row contains the given subset of properties.
Parameters
subsetPartial<T>- The partial object to match against rows
toSatisfy(matcher: (rows: SqlRows<T>) => unknown): thisValidates the rows using a custom matcher function.
Parameters
matcher(rows: SqlRows<T>) => unknown- A function that receives the rows and performs assertions
toHaveMapContaining<U>(mapper: (row: T) => unknown, subset: Partial<U>): thisAsserts that at least one mapped row contains the given subset.
Parameters
mapper(row: T) => unknown- A function to transform each row
subsetPartial<U>- The partial object to match against mapped rows
toHaveMapMatching<U>(mapper: (row: T) => unknown, matcher: (mapped: U[]) => unknown): thisValidates the mapped rows using a custom matcher function.
Parameters
mapper(row: T) => unknown- A function to transform each row
matcher(mapped: U[]) => unknown- A function that receives the mapped rows and performs assertions
toHaveInstanceContaining<U>(ctor: (row: T) => unknown, subset: Partial<U>): thisAsserts that at least one instance created from rows contains the given subset.
Parameters
ctor(row: T) => unknown- The constructor to instantiate with each row
subsetPartial<U>- The partial object to match against instances
toHaveInstanceMatching<U>(ctor: (row: T) => unknown, matcher: (instances: U[]) => unknown): thisValidates instances created from rows using a custom matcher function.
Parameters
ctor(row: T) => unknown- The constructor to instantiate with each row
matcher(instances: U[]) => unknown- A function that receives the instances and performs assertions
toHaveLastInsertId(expected: bigint | string): thisAsserts that the lastInsertId matches the expected value.
Parameters
expectedbigint | string- The expected lastInsertId value
toHaveLastInsertId(): thisAsserts that the lastInsertId is present.
toHaveDurationLessThan(ms: number): thisAsserts that the query duration is less than the threshold.
Parameters
msnumber- The maximum duration in milliseconds (exclusive)
toHaveDurationLessThanOrEqual(ms: number): thisAsserts that the query duration is at most the threshold.
Parameters
msnumber- The maximum duration in milliseconds (inclusive)
toHaveDurationGreaterThan(ms: number): thisAsserts that the query duration is greater than the threshold.
Parameters
msnumber- The minimum duration in milliseconds (exclusive)
toHaveDurationGreaterThanOrEqual(ms: number): thisAsserts that the query duration is at least the threshold.
Parameters
msnumber- The minimum duration in milliseconds (inclusive)
#SqlQueryResultInit
interface SqlQueryResultInit<T>Options for creating a SqlQueryResult.
| Name | Description |
|---|---|
ok | Whether the query succeeded |
rows | The result rows |
rowCount | Number of affected rows (for INSERT/UPDATE/DELETE) |
duration | Query execution duration in milliseconds |
metadata | Additional metadata |
Properties
- readonly
okbooleanWhether the query succeeded
- readonly
rowsreadonly T[]The result rows
- readonly
rowCountnumberNumber of affected rows (for INSERT/UPDATE/DELETE)
- readonly
durationnumberQuery execution duration in milliseconds
Additional metadata
#SqlQueryResultMetadata
interface SqlQueryResultMetadataMetadata for SQL query results.
| Name | Description |
|---|---|
lastInsertId | Last inserted ID (for INSERT statements) |
warnings | Warning messages from the database |
Properties
- readonly
lastInsertId?bigint | stringLast inserted ID (for INSERT statements)
- readonly
warnings?readonly string[]Warning messages from the database
#SqlTransaction
interface SqlTransactionSQL transaction interface. Implementations should provide actual database-specific transaction handling.
| Name | Description |
|---|---|
query() | Execute a query within the transaction. |
queryOne() | Execute a query and return the first row or undefined. |
commit() | Commit the transaction. |
rollback() | Rollback the transaction. |
Methods
query<T = Record<string, any>>(sql: string, params?: unknown[]): Promise<SqlQueryResult<T>>Execute a query within the transaction.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
queryOne<T = Record<string, any>>(sql: string, params?: unknown[]): Promise<T | undefined>Execute a query and return the first row or undefined.
Parameters
sqlstring- SQL query string
params?unknown[]- Optional query parameters
commit(): Promise<void>Commit the transaction.
rollback(): Promise<void>Rollback the transaction.
#SqlTransactionOptions
interface SqlTransactionOptionsOptions for starting a transaction.
| Name | Description |
|---|---|
isolationLevel | Isolation level for the transaction |
Properties
Isolation level for the transaction
#SqsBatchFailedEntry
interface SqsBatchFailedEntryFailed batch entry.
Properties
- readonly
idstring - readonly
codestring - readonly
messagestring
#SqsBatchMessage
interface SqsBatchMessageBatch message for sendBatch.
| Name | Description |
|---|---|
id | — |
body | — |
delaySeconds | — |
messageAttributes | — |
Properties
- readonly
idstring - readonly
bodystring - readonly
delaySeconds?number
#SqsBatchSuccessEntry
interface SqsBatchSuccessEntrySuccessful batch send entry.
Properties
- readonly
messageIdstring - readonly
idstring
#SqsClient
interface SqsClient extends AsyncDisposableSQS client interface.
| Name | Description |
|---|---|
config | — |
queueUrl | The current queue URL. |
setQueueUrl() | Set the queue URL for subsequent operations. |
ensureQueue() | Ensure a queue exists. |
deleteQueue() | Delete a queue by URL. |
send() | Send a message to the queue. |
sendBatch() | Send multiple messages to the queue in a single request. |
receive() | Receive messages from the queue. |
delete() | Delete a message from the queue. |
deleteBatch() | Delete multiple messages from the queue in a single request. |
purge() | Purge all messages from the queue. |
close() | Close the client and release resources. |
Properties
- readonly
queueUrlstring | undefinedThe current queue URL. Can be set via config, ensureQueue(), or setQueueUrl().
Methods
setQueueUrl(queueUrl: string): voidSet the queue URL for subsequent operations.
Parameters
queueUrlstring
ensureQueue(queueName: string, options?: SqsEnsureQueueOptions): Promise<SqsEnsureQueueResult>Ensure a queue exists. Creates the queue if it doesn't exist. If the queue already exists with the same attributes, returns the existing queue URL. Also sets the queue URL for subsequent operations.
Parameters
queueNamestringoptions?SqsEnsureQueueOptions
deleteQueue(queueUrl: string, options?: CommonOptions): Promise<SqsDeleteQueueResult>Delete a queue by URL.
Parameters
queueUrlstringoptions?CommonOptions
send(body: string, options?: SqsSendOptions): Promise<SqsSendResult>Send a message to the queue.
Parameters
bodystringoptions?SqsSendOptions
sendBatch(messages: SqsBatchMessage[]): Promise<SqsSendBatchResult>Send multiple messages to the queue in a single request.
Parameters
messagesSqsBatchMessage[]
receive(options?: SqsReceiveOptions): Promise<SqsReceiveResult>Receive messages from the queue.
Parameters
options?SqsReceiveOptions
delete(receiptHandle: string, options?: CommonOptions): Promise<SqsDeleteResult>Delete a message from the queue.
Parameters
receiptHandlestringoptions?CommonOptions
deleteBatch(receiptHandles: string[], options?: CommonOptions): Promise<SqsDeleteBatchResult>Delete multiple messages from the queue in a single request.
Parameters
receiptHandlesstring[]options?CommonOptions
purge(options?: CommonOptions): Promise<SqsDeleteResult>Purge all messages from the queue.
Parameters
options?CommonOptions
close(): Promise<void>Close the client and release resources.
#SqsClientConfig
interface SqsClientConfig extends CommonOptionsSQS client configuration.
| Name | Description |
|---|---|
region | AWS region |
credentials | AWS credentials |
queueUrl | SQS queue URL (optional - can be set later or used with ensureQueue) |
url | SQS endpoint URL (e.g., "http://localhost:4566" for LocalStack). |
Properties
- readonly
regionstringAWS region
- readonly
credentials?{ accessKeyId: string; secretAccessKey: string }AWS credentials
- readonly
queueUrl?stringSQS queue URL (optional - can be set later or used with ensureQueue)
SQS endpoint URL (e.g., "http://localhost:4566" for LocalStack). Can be a string URL or a connection config object. Optional for real AWS (uses default endpoint), required for LocalStack.
#SqsCommandErrorOptions
interface SqsCommandErrorOptions extends SqsErrorOptionsOptions for SQS command errors.
| Name | Description |
|---|---|
operation | — |
Properties
- readonly
operationstring
#SqsConnectionConfig
interface SqsConnectionConfig extends CommonConnectionConfigSQS connection configuration.
Extends CommonConnectionConfig with SQS-specific options.
| Name | Description |
|---|---|
protocol | Protocol to use. |
path | Custom path (for LocalStack or custom endpoints). |
region | AWS region (required for AWS, optional for LocalStack). |
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringCustom path (for LocalStack or custom endpoints).
- readonly
region?stringAWS region (required for AWS, optional for LocalStack).
#SqsDeleteBatchResult
interface SqsDeleteBatchResultResult of batch deleting messages.
| Name | Description |
|---|---|
type | — |
ok | — |
successful | — |
failed | — |
duration | — |
Properties
- readonly
type"sqs:delete-batch" - readonly
okboolean - readonly
successfulreadonly string[] - readonly
durationnumber
#SqsDeleteQueueResult
interface SqsDeleteQueueResultResult of deleting a queue.
Properties
- readonly
type"sqs:delete-queue" - readonly
okboolean - readonly
durationnumber
#SqsDeleteResult
interface SqsDeleteResultResult of deleting a message.
Properties
- readonly
type"sqs:delete" - readonly
okboolean - readonly
durationnumber
#SqsEnsureQueueOptions
interface SqsEnsureQueueOptions extends CommonOptionsOptions for ensuring a queue exists.
| Name | Description |
|---|---|
attributes | Queue attributes (e.g., DelaySeconds, MessageRetentionPeriod) |
tags | Queue tags |
Properties
- readonly
attributes?Record<string, string>Queue attributes (e.g., DelaySeconds, MessageRetentionPeriod)
#SqsEnsureQueueResult
interface SqsEnsureQueueResultResult of ensuring a queue exists.
Properties
- readonly
type"sqs:ensure-queue" - readonly
okboolean - readonly
queueUrlstring - readonly
durationnumber
#SqsErrorOptions
interface SqsErrorOptions extends ErrorOptionsOptions for SQS errors.
| Name | Description |
|---|---|
code | — |
Properties
- readonly
code?string
#SqsMessage
interface SqsMessageSQS message received from a queue.
| Name | Description |
|---|---|
messageId | — |
body | — |
receiptHandle | — |
attributes | — |
messageAttributes | — |
md5OfBody | — |
Properties
- readonly
messageIdstring - readonly
bodystring - readonly
receiptHandlestring - readonly
attributesRecord<string, string> - readonly
md5OfBodystring
#SqsMessageAttribute
interface SqsMessageAttributeSQS message attributes.
| Name | Description |
|---|---|
dataType | — |
stringValue | — |
binaryValue | — |
Properties
- readonly
dataType"String" | "Number" | "Binary" - readonly
stringValue?string - readonly
binaryValue?Uint8Array
#SqsMessages
interface SqsMessages extends ReadonlyArray<SqsMessage>Message array with helper methods.
| Name | Description |
|---|---|
first() | Get the first message or undefined if empty |
firstOrThrow() | Get the first message or throw if empty |
last() | Get the last message or undefined if empty |
lastOrThrow() | Get the last message or throw if empty |
Methods
first(): SqsMessage | undefinedGet the first message or undefined if empty
firstOrThrow(): SqsMessageGet the first message or throw if empty
last(): SqsMessage | undefinedGet the last message or undefined if empty
lastOrThrow(): SqsMessageGet the last message or throw if empty
#SqsReceiveOptions
interface SqsReceiveOptions extends CommonOptionsOptions for receiving messages.
| Name | Description |
|---|---|
maxMessages | Maximum number of messages to receive (1-10, default: 1) |
waitTimeSeconds | Wait time in seconds for long polling (0-20) |
visibilityTimeout | Visibility timeout in seconds (0-43200) |
attributeNames | System attribute names to retrieve |
messageAttributeNames | Message attribute names to retrieve |
Properties
- readonly
maxMessages?numberMaximum number of messages to receive (1-10, default: 1)
- readonly
waitTimeSeconds?numberWait time in seconds for long polling (0-20)
- readonly
visibilityTimeout?numberVisibility timeout in seconds (0-43200)
- readonly
attributeNames?readonly string[]System attribute names to retrieve
- readonly
messageAttributeNames?readonly string[]Message attribute names to retrieve
#SqsReceiveResult
interface SqsReceiveResultResult of receiving messages.
Properties
- readonly
type"sqs:receive" - readonly
okboolean - readonly
durationnumber
#SqsSendBatchResult
interface SqsSendBatchResultResult of batch sending messages.
| Name | Description |
|---|---|
type | — |
ok | — |
successful | — |
failed | — |
duration | — |
Properties
- readonly
type"sqs:send-batch" - readonly
okboolean - readonly
durationnumber
#SqsSendOptions
interface SqsSendOptions extends CommonOptionsOptions for sending a message.
| Name | Description |
|---|---|
delaySeconds | Delay in seconds before the message becomes visible (0-900) |
messageAttributes | Message attributes |
messageGroupId | Message group ID (required for FIFO queues) |
messageDeduplicationId | Message deduplication ID (required for FIFO queues without content-based deduplication) |
Properties
- readonly
delaySeconds?numberDelay in seconds before the message becomes visible (0-900)
Message attributes
- readonly
messageGroupId?stringMessage group ID (required for FIFO queues)
- readonly
messageDeduplicationId?stringMessage deduplication ID (required for FIFO queues without content-based deduplication)
#SqsSendResult
interface SqsSendResultResult of sending a message.
Properties
- readonly
type"sqs:send" - readonly
okboolean - readonly
messageIdstring - readonly
md5OfBodystring - readonly
sequenceNumber?string - readonly
durationnumber
#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
#buildErrorMessage
function buildErrorMessage(header: string, diffs: string[], expected: unknown, actual: unknown): stringBuilds a structured error message with diffs.
Parameters
headerstring- The error header message
diffsstring[]- Array of diff lines from formatDifferences (includes [Diff] header and colors)
expectedunknown- The expected value
actualunknown- The actual value
Returns
string — Formatted error message
#containsSubarray
function containsSubarray(arr: Uint8Array, sub: Uint8Array): booleanCheck if an array contains a contiguous subarray.
Parameters
arrUint8Array- The array to search
subUint8Array- The subarray to find
Returns
boolean — True if arr contains sub as a contiguous sequence
#containsSubset
function containsSubset(obj: unknown, subset: unknown): booleanCheck if an object contains all properties from subset (deep partial match).
Parameters
objunknown- The object to check
subsetunknown- The subset of properties to match
Returns
boolean — True if obj contains all properties from subset
#createConnectRpcClient
function createConnectRpcClient(config: ConnectRpcClientConfig): ConnectRpcClientCreate a new ConnectRPC client instance.
The client supports multiple protocols (Connect, gRPC, gRPC-Web) and provides Server Reflection for runtime service discovery without compile-time code generation.
Parameters
configConnectRpcClientConfig- Client configuration including server URL and protocol options
Returns
ConnectRpcClient — A new ConnectRPC client instance
Examples
Basic usage with reflection
const client = createConnectRpcClient({
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 = createConnectRpcClient({
url: "http://localhost:50051",
});
// 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);
await client.close();
Using different protocols
// Connect protocol (HTTP/1.1 or HTTP/2)
const connectClient = createConnectRpcClient({
url: "http://localhost:8080",
protocol: "connect",
});
// gRPC protocol (HTTP/2 with binary protobuf)
const grpcClient = createConnectRpcClient({
url: "http://localhost:50051",
protocol: "grpc",
});
// gRPC-Web protocol (for browser compatibility)
const grpcWebClient = createConnectRpcClient({
url: "http://localhost:8080",
protocol: "grpc-web",
});
Using connection config object
const client = createConnectRpcClient({
url: {
host: "grpc.example.com",
port: 443,
protocol: "https",
},
});
Using await using for automatic cleanup
await using client = createConnectRpcClient({
url: "http://localhost:50051",
});
const res = await client.call("echo.EchoService", "echo", { message: "test" });
// Client automatically closed when scope exits
#createDenoKvClient
async function createDenoKvClient(config?: DenoKvClientConfig): Promise<DenoKvClient>Create a new Deno KV client instance.
The client provides key-value operations with support for atomic transactions, time-to-live (TTL), and prefix-based listing.
Parameters
config?DenoKvClientConfig- Deno KV client configuration (optional)
Returns
Promise<DenoKvClient> — A promise resolving to a new Deno KV client instance
Examples
Basic usage with in-memory database
const kv = await createDenoKvClient();
await kv.set(["users", "123"], { name: "Alice", email: "alice@example.com" });
const result = await kv.get<User>(["users", "123"]);
console.log(result.value); // { name: "Alice", email: "alice@example.com" }
await kv.close();
Using persistent storage
const kv = await createDenoKvClient({
path: "./data.kv",
});
Set with expiration (TTL)
await kv.set(["sessions", sessionId], sessionData, {
expireIn: 3600_000, // Expire in 1 hour
});
List entries by prefix
const result = await kv.list<User>({ prefix: ["users"] });
for (const entry of result.entries) {
console.log(entry.key, entry.value);
}
Atomic transactions
const atomicResult = await kv.atomic()
.check({ key: ["counter"], versionstamp: null })
.set(["counter"], 1)
.commit();
Using await using for automatic cleanup
await using kv = await createDenoKvClient();
await kv.set(["test"], "value");
// Client automatically closed when scope exits
#createDenoKvEntries
function createDenoKvEntries<T>(entries: DenoKvEntry<T>[]): DenoKvEntries<T>Creates a DenoKvEntries instance from an array of entries.
Parameters
entriesDenoKvEntry<T>[]
#createGraphqlClient
function createGraphqlClient(config: GraphqlClientConfig): GraphqlClientCreate a new GraphQL client instance.
The client provides methods for executing GraphQL queries, mutations, and subscriptions with automatic error handling and response parsing.
Parameters
configGraphqlClientConfig- Client configuration including URL and default options
Returns
GraphqlClient — A new GraphQL client instance
Examples
Basic query
const client = createGraphqlClient({
url: "http://localhost:4000/graphql",
});
const response = await client.query(`
query GetUser($id: ID!) {
user(id: $id) { id name email }
}
`, { id: "123" });
console.log(response.data());
await client.close();
Using connection config object
const client = createGraphqlClient({
url: { host: "api.example.com", port: 443, protocol: "https" },
});
Mutation with error handling
const response = await client.mutation(`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) { id }
}
`, { input: { name: "Alice", email: "alice@example.com" } });
if (response.ok) {
console.log("Created user:", response.data().createUser.id);
}
Using await using for automatic cleanup
await using client = createGraphqlClient({
url: "http://localhost:4000/graphql",
});
const response = await client.query(`{ __typename }`);
// Client automatically closed when scope exits
#createGraphqlResponse
function createGraphqlResponse<T>(options: GraphqlResponseOptions<T>): GraphqlResponse<T>Create a GraphqlResponse from parsed response data.
Parameters
optionsGraphqlResponseOptions<T>
#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
#createHttpClient
function createHttpClient(config: HttpClientConfig): HttpClientCreate a new HTTP client instance.
The client provides methods for making HTTP requests with automatic cookie handling, response body pre-loading, and error handling.
Parameters
configHttpClientConfig- Client configuration including URL and default options
Returns
HttpClient — A new HTTP client instance
Examples
Basic usage with string URL
const http = createHttpClient({ url: "http://localhost:3000" });
const response = await http.get("/users/123");
console.log(response.data());
await http.close();
With connection config object
const http = createHttpClient({
url: { host: "api.example.com", port: 443, protocol: "https" },
});
With default headers
const http = createHttpClient({
url: "http://localhost:3000",
headers: {
"Authorization": "Bearer token123",
"Accept": "application/json",
},
});
Using await using for automatic cleanup
await using http = createHttpClient({ url: "http://localhost:3000" });
const response = await http.get("/health");
// Client automatically closed when scope exits
#createHttpResponse
async function createHttpResponse(raw: globalThis.Response, duration: number): Promise<HttpResponse>Create HttpResponse from raw Response.
Consumes the response body and creates a reusable HttpResponse.
Parameters
rawglobalThis.Responsedurationnumber
#createMongoClient
async function createMongoClient(config: MongoClientConfig): Promise<MongoClient>Create a new MongoDB client instance.
The client provides typed collection access, aggregation pipelines, transaction support, and comprehensive CRUD operations.
Parameters
configMongoClientConfig- MongoDB client configuration
Returns
Promise<MongoClient> — A promise resolving to a new MongoDB client instance
Examples
Basic usage with connection string
const mongo = await createMongoClient({
url: "mongodb://localhost:27017",
database: "testdb",
});
const users = mongo.collection<{ name: string; age: number }>("users");
const result = await users.find({ age: { $gte: 18 } });
console.log(result.docs.first());
await mongo.close();
Using connection config object
const mongo = await createMongoClient({
url: {
host: "localhost",
port: 27017,
username: "admin",
password: "secret",
authSource: "admin",
},
database: "testdb",
});
Insert and query documents
const users = mongo.collection<User>("users");
// Insert a document
const insertResult = await users.insertOne({ name: "Alice", age: 30 });
console.log("Inserted ID:", insertResult.insertedId);
// Find documents with projection and sorting
const findResult = await users.find(
{ age: { $gte: 25 } },
{ sort: { name: 1 }, limit: 10 }
);
console.log("Found:", findResult.documents.length);
Transaction with auto-commit/rollback
await mongo.transaction(async (session) => {
const users = session.collection<User>("users");
await users.insertOne({ name: "Bob", age: 25 });
await users.updateOne({ name: "Alice" }, { $inc: { age: 1 } });
});
Aggregation pipeline
const result = await users.aggregate<{ _id: string; avgAge: number }>([
{ $group: { _id: "$department", avgAge: { $avg: "$age" } } },
{ $sort: { avgAge: -1 } },
]);
Using await using for automatic cleanup
await using mongo = await createMongoClient({
url: "mongodb://localhost:27017",
database: "testdb",
});
const result = await mongo.collection("users").find({});
// Client automatically closed when scope exits
#createMongoDocs
function createMongoDocs<T>(items: T[]): MongoDocs<T>Create a MongoDocs array from a regular array.
Parameters
itemsT[]
#createRabbitMqClient
async function createRabbitMqClient(config: RabbitMqClientConfig): Promise<RabbitMqClient>Create a new RabbitMQ client instance.
The client provides queue and exchange management, message publishing and consumption, and acknowledgment handling via AMQP protocol.
Parameters
configRabbitMqClientConfig- RabbitMQ client configuration
Returns
Promise<RabbitMqClient> — A promise resolving to a new RabbitMQ client instance
Examples
Basic usage with string URL
const rabbit = await createRabbitMqClient({
url: "amqp://guest:guest@localhost:5672",
});
const channel = await rabbit.channel();
await channel.assertQueue("my-queue", { durable: true });
const content = new TextEncoder().encode(JSON.stringify({ type: "ORDER" }));
await channel.sendToQueue("my-queue", content, { persistent: true });
await channel.close();
await rabbit.close();
With connection config object
const rabbit = await createRabbitMqClient({
url: {
host: "localhost",
port: 5672,
username: "guest",
password: "guest",
vhost: "/",
},
});
Exchange and binding
// Create exchange and queue
await channel.assertExchange("events", "topic", { durable: true });
await channel.assertQueue("user-events");
await channel.bindQueue("user-events", "events", "user.*");
// Publish to exchange
await channel.publish("events", "user.created", content);
Consuming messages
for await (const message of channel.consume("my-queue")) {
console.log("Received:", new TextDecoder().decode(message.content));
await channel.ack(message);
}
Get single message (polling)
const result = await channel.get("my-queue");
if (result.message) {
await channel.ack(result.message);
}
Using await using for automatic cleanup
await using rabbit = await createRabbitMqClient({
url: "amqp://localhost:5672",
});
const channel = await rabbit.channel();
// Client automatically closed when scope exits
#createRedisClient
async function createRedisClient(config: RedisClientConfig): Promise<RedisClient>Create a new Redis client instance.
The client provides comprehensive Redis data structure support including strings, hashes, lists, sets, sorted sets, pub/sub, and transactions.
Parameters
configRedisClientConfig- Redis client configuration
Returns
Promise<RedisClient> — A promise resolving to a new Redis client instance
Examples
Using URL string
const client = await createRedisClient({
url: "redis://localhost:6379/0",
});
await client.set("key", "value");
const result = await client.get("key");
console.log(result.value); // "value"
await client.close();
Using connection config object
const client = await createRedisClient({
url: {
host: "localhost",
port: 6379,
password: "secret",
db: 0,
},
});
Set with expiration
// Set key with 1 hour TTL
await client.set("session", sessionData, { ex: 3600 });
// Set key with 5 second TTL in milliseconds
await client.set("temp", data, { px: 5000 });
Hash operations
await client.hset("user:123", "name", "Alice");
await client.hset("user:123", "email", "alice@example.com");
const user = await client.hgetall("user:123");
console.log(user.value); // { name: "Alice", email: "alice@example.com" }
Pub/Sub
// Subscribe to channel
for await (const message of client.subscribe("events")) {
console.log("Received:", message.message);
}
// In another session
await client.publish("events", JSON.stringify({ type: "user.created" }));
Using await using for automatic cleanup
await using client = await createRedisClient({
url: "redis://localhost:6379",
});
await client.set("test", "value");
// Client automatically closed when scope exits
#createSqsClient
function createSqsClient(config: SqsClientConfig): Promise<SqsClient>Create a new Amazon SQS client instance.
The client provides queue management, message publishing and consumption, batch operations, and supports both standard and FIFO queues via AWS SDK.
Parameters
configSqsClientConfig- SQS client configuration
Returns
Promise<SqsClient> — A promise resolving to a new SQS client instance
Examples
Basic usage with existing queue
const sqs = await createSqsClient({
region: "ap-northeast-1",
queueUrl: "https://sqs.ap-northeast-1.amazonaws.com/123456789/my-queue",
});
// Send a message
const sendResult = await sqs.send(JSON.stringify({
type: "ORDER",
orderId: "123",
}));
console.log("Message ID:", sendResult.messageId);
await sqs.close();
Using LocalStack for local development
const sqs = await createSqsClient({
region: "us-east-1",
url: "http://localhost:4566",
credentials: {
accessKeyId: "test",
secretAccessKey: "test",
},
});
// Create queue dynamically (also sets queueUrl)
const result = await sqs.ensureQueue("test-queue");
console.log(result.queueUrl); // http://localhost:4566/000000000000/test-queue
Receiving messages with long polling
// Long polling waits up to 20 seconds for messages
const receiveResult = await sqs.receive({
maxMessages: 10,
waitTimeSeconds: 20,
visibilityTimeout: 30,
});
console.log("Received:", receiveResult.messages.length);
// Process and acknowledge messages
for (const msg of receiveResult.messages) {
const data = JSON.parse(msg.body);
console.log("Processing:", data);
// Delete after successful processing
await sqs.delete(msg.receiptHandle);
}
Batch operations for high throughput
// Send multiple messages in a single API call
const batchResult = await sqs.sendBatch([
{ id: "1", body: JSON.stringify({ event: "user.created", userId: "a1" }) },
{ id: "2", body: JSON.stringify({ event: "user.created", userId: "a2" }) },
{ id: "3", body: JSON.stringify({ event: "user.updated", userId: "a3" }) },
]);
console.log(`Sent: ${batchResult.successful.length}`);
console.log(`Failed: ${batchResult.failed.length}`);
// Batch delete processed messages
const handles = receiveResult.messages.map(m => m.receiptHandle);
await sqs.deleteBatch(handles);
FIFO queue with deduplication
const sqs = await createSqsClient({
region: "ap-northeast-1",
queueUrl: "https://sqs.ap-northeast-1.amazonaws.com/123456789/orders.fifo",
});
// FIFO queues require MessageGroupId and optionally MessageDeduplicationId
await sqs.send(JSON.stringify({ orderId: "order-123" }), {
messageGroupId: "orders",
messageDeduplicationId: "order-123-v1",
});
Using await using for automatic cleanup
await using sqs = await createSqsClient({
region: "us-east-1",
url: "http://localhost:4566",
});
await sqs.ensureQueue("test-queue");
await sqs.send("Hello, SQS!");
// Client automatically closed when scope exits
#createSqsMessages
function createSqsMessages(messages: SqsMessage[]): SqsMessagesCreate an SqsMessages array with helper methods.
Parameters
messagesSqsMessage[]
#expect(11 overloads)
function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.
Parameters
valueT
Examples
// HTTP response
const httpRes = await http.get("/users");
expect(httpRes).toBeSuccessful().toHaveContentContaining({ users: [] });
// GraphQL response
const gqlRes = await graphql.query("{ users { id name } }");
expect(gqlRes).toBeSuccessful().toHaveContent();
// SQL query result
const sqlRes = await db.query("SELECT * FROM users");
expect(sqlRes).toBeSuccessful().toHaveCount(10);
// MongoDB result
const mongoRes = await mongo.find({ status: "active" });
expect(mongoRes).toBeSuccessful().toHaveLength(10);
// Falls back to expectAnything (chainable @std/expect) for other values
expect(42).toBe(42).toBeGreaterThan(40);
Show all 11 overloads
function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.
Parameters
valueT
function expect<T extends ConnectRpcResponse>(value: T): ReturnType<expectConnectRpcResponse>Parameters
valueT
function expect<T extends GraphqlResponse>(value: T): ReturnType<expectGraphqlResponse>Parameters
valueT
function expect<T extends SqlQueryResult>(value: T): SqlQueryResultExpectation<ExtractSqlRowType<T>>Parameters
valueT
function expect<T extends DenoKvResult>(value: T): ReturnType<expectDenoKvResult>Parameters
valueT
function expect<T extends RedisResult>(value: T): ReturnType<expectRedisResult>Parameters
valueT
function expect<T extends MongoResult>(value: T): ReturnType<expectMongoResult>Parameters
valueT
function expect<T extends RabbitMqResult>(value: T): ReturnType<expectRabbitMqResult>Parameters
valueT
function expect<T extends SqsResult>(value: T): ReturnType<expectSqsResult>Parameters
valueT
function expect(value: unknown): AnythingExpectationParameters
valueunknown
function expect(value: unknown): unknownParameters
valueunknown
#expectAnything
function expectAnything<T>(value: T, _: unknown): AnythingExpectationCreates a chainable expectation for any value using @std/expect matchers.
This wrapper allows method chaining, unlike @std/expect which returns void.
Parameters
valueT- Value to test
_unknown
Returns
AnythingExpectation — Chainable expectation interface
Examples
import { expectAnything } from "@probitas/expect/anything";
// Method chaining
expectAnything(42)
.toBeDefined()
.toBeGreaterThan(40)
.toBeLessThan(50);
// Negation with continued chaining
expectAnything("hello")
.not.toBe("world")
.not.toBeNull()
.toContain("hello");
#expectConnectRpcResponse
function expectConnectRpcResponse(response: ConnectRpcResponse, _: unknown): ConnectRpcResponseExpectationCreate a fluent assertion chain for ConnectRPC response validation.
Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.
Parameters
responseConnectRpcResponse- The ConnectRPC response to validate
_unknown
Returns
ConnectRpcResponseExpectation — A fluent expectation chain
Examples
Basic assertions
const response = await client.call(
"echo.EchoService",
"echo",
{ message: "Hello!" }
);
expectConnectRpcResponse(response)
.toBeSuccessful()
.toHaveContent()
.toMatchObject({ message: "Hello!" });
Error status assertions
const response = await client.call(
"user.UserService",
"getUser",
{ id: "non-existent" },
{ throwOnError: false }
);
expectConnectRpcResponse(response)
.not.toBeSuccessful()
.toHaveCode(5) // NOT_FOUND
.toHaveErrorContaining("not found");
Header and trailer assertions
expectConnectRpcResponse(response)
.toBeSuccessful()
.toHaveHeader("x-request-id")
.toHaveTrailer("grpc-status");
Performance assertions
expectConnectRpcResponse(response)
.toBeSuccessful()
.toHaveDurationLessThan(500); // Must respond within 500ms
#expectDenoKvResult
function expectDenoKvResult<R extends DenoKvResult<any>>(result: R): DenoKvExpectation<R>Create a fluent expectation chain for any Deno KV result validation.
This unified function accepts any Deno KV result type and returns the appropriate expectation interface based on the result's type discriminator.
Parameters
resultR
Examples
// For GET result - returns DenoKvGetResultExpectation<T>
const getResult = await kv.get(["users", "1"]);
expectDenoKvResult(getResult).toBeSuccessful().toHaveContent().toMatchObject({ name: "Alice" });
// For SET result - returns DenoKvSetResultExpectation
const setResult = await kv.set(["users", "1"], { name: "Alice" });
expectDenoKvResult(setResult).toBeSuccessful().toHaveVersionstamp();
// For LIST result - returns DenoKvListResultExpectation<T>
const listResult = await kv.list({ prefix: ["users"] });
expectDenoKvResult(listResult).toBeSuccessful().toHaveLength(3);
// For DELETE result - returns DenoKvDeleteResultExpectation
const deleteResult = await kv.delete(["users", "1"]);
expectDenoKvResult(deleteResult).toBeSuccessful();
// For ATOMIC result - returns DenoKvAtomicResultExpectation
const atomicResult = await kv.atomic().set(["counter"], 1).commit();
expectDenoKvResult(atomicResult).toBeSuccessful().toHaveVersionstamp();
#expectGraphqlResponse
function expectGraphqlResponse(response: GraphqlResponse, _: unknown): GraphqlResponseExpectationCreate a fluent expectation chain for GraphQL response validation.
Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.
Parameters
responseGraphqlResponse- The GraphQL response to validate
_unknown
Returns
GraphqlResponseExpectation — A fluent expectation chain
Examples
Basic assertions
const response = await client.query(`
query GetUser($id: ID!) {
user(id: $id) { id name }
}
`, { id: "123" });
expectGraphqlResponse(response)
.toBeSuccessful()
.toHaveContent()
.toMatchObject({ user: { name: "Alice" } });
Error assertions
const response = await client.query(`
query { invalidField }
`, undefined, { throwOnError: false });
expectGraphqlResponse(response)
.not.toBeSuccessful()
.toHaveErrorContaining("Cannot query field");
Mutation with custom matcher
const response = await client.mutation(`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) { id name }
}
`, { input: { name: "Bob" } });
expectGraphqlResponse(response)
.toBeSuccessful()
.toSatisfy((data) => {
assertEquals(data.createUser.name, "Bob");
});
Performance assertions
expectGraphqlResponse(response)
.toBeSuccessful()
.toHaveDurationLessThan(500); // Must respond within 500ms
#expectGrpcResponse
function expectGrpcResponse(response: GrpcResponse, _: unknown): GrpcResponseExpectationCreates an expectation for a gRPC response.
Parameters
responseGrpcResponse- gRPC response to test
_unknown
Returns
GrpcResponseExpectation — Fluent expectation interface
Examples
import { expectGrpcResponse } from "@probitas/expect/grpc";
const response = await client.call("GetUser", { id: "1" });
expectGrpcResponse(response)
.toBeSuccessful()
.toHaveCode(0)
.toHaveContent()
.toHaveDataContaining({ id: "1", name: "Alice" });
#expectHttpResponse
function expectHttpResponse(response: HttpResponse, _: unknown): HttpResponseExpectationCreate a fluent expectation chain for HTTP response validation.
Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.
Parameters
responseHttpResponse- The HTTP response to validate
_unknown
Returns
HttpResponseExpectation — A fluent expectation chain
Examples
Basic assertions
const response = await http.get("/users/123");
expectHttpResponse(response)
.toBeSuccessful()
.toHaveContentType("application/json")
.toMatchObject({ id: 123, name: "Alice" });
Error response assertions
const response = await http.get("/not-found", { throwOnError: false });
expectHttpResponse(response)
.not.toBeSuccessful()
.toHaveStatus(404);
Performance assertions
expectHttpResponse(response)
.toBeSuccessful()
.toHaveDurationLessThan(1000); // Must respond within 1 second
#expectMongoResult
function expectMongoResult<R extends MongoResult<any>>(result: R): MongoExpectation<R>Create a fluent expectation chain for any MongoDB result validation.
This unified function accepts any MongoDB result type and returns the appropriate expectation interface based on the result's type discriminator.
Parameters
resultR
Examples
// For find result - returns MongoFindResultExpectation
const findResult = await users.find({ age: { $gte: 30 } });
expectMongoResult(findResult).toBeSuccessful().toHaveContent().toHaveLength(2);
// For insert result - returns MongoInsertResultExpectation
const insertResult = await users.insertOne({ name: "Alice", age: 30 });
expectMongoResult(insertResult).toBeSuccessful().toHaveInsertedId();
// For update result - returns MongoUpdateResultExpectation
const updateResult = await users.updateOne({ name: "Alice" }, { $set: { age: 31 } });
expectMongoResult(updateResult).toBeSuccessful().toHaveMatchedCount(1).toHaveModifiedCount(1);
// For delete result - returns MongoDeleteResultExpectation
const deleteResult = await users.deleteOne({ name: "Alice" });
expectMongoResult(deleteResult).toBeSuccessful().toHaveDeletedCount(1);
// For findOne result - returns MongoFindOneResultExpectation
const findOneResult = await users.findOne({ name: "Alice" });
expectMongoResult(findOneResult).toBeSuccessful().toHaveContent().toMatchObject({ name: "Alice" });
// For count result - returns MongoCountResultExpectation
const countResult = await users.countDocuments();
expectMongoResult(countResult).toBeSuccessful().toHaveLength(10);
#expectRabbitMqResult
function expectRabbitMqResult<R extends RabbitMqResult>(result: R): RabbitMqExpectation<R>Create a fluent expectation chain for any RabbitMQ result validation.
This unified function accepts any RabbitMQ result type and returns the appropriate expectation interface based on the result's type discriminator.
Parameters
resultR
Examples
// For publish result - returns RabbitMqPublishResultExpectation
const publishResult = await channel.sendToQueue(queue, content);
expectRabbitMqResult(publishResult).toBeSuccessful();
// For consume result - returns RabbitMqConsumeResultExpectation
const consumeResult = await channel.get(queue);
expectRabbitMqResult(consumeResult).toBeSuccessful().toHaveContent().routingKey("key");
// For queue result - returns RabbitMqQueueResultExpectation
const queueResult = await channel.assertQueue("my-queue");
expectRabbitMqResult(queueResult).toBeSuccessful().messageCount(0);
// For exchange result - returns RabbitMqExchangeResultExpectation
const exchangeResult = await channel.assertExchange("my-exchange", "direct");
expectRabbitMqResult(exchangeResult).toBeSuccessful();
// For ack result - returns RabbitMqAckResultExpectation
const ackResult = await channel.ack(message);
expectRabbitMqResult(ackResult).toBeSuccessful();
#expectRedisResult
function expectRedisResult<R extends RedisResult<any>>(result: R): RedisExpectation<R>Create a fluent expectation chain for any Redis result validation.
This unified function accepts any Redis result type and returns the appropriate expectation interface based on the result's type discriminator.
Parameters
resultR
Examples
// For GET result - returns RedisResultExpectation<string | null>
const getResult = await client.get("key");
expectRedisResult(getResult).toBeSuccessful().toHaveValue("expected");
// For COUNT result - returns RedisCountResultExpectation
const countResult = await client.del("key");
expectRedisResult(countResult).toBeSuccessful().toHaveCount(1);
// For ARRAY result - returns RedisArrayResultExpectation
const arrayResult = await client.lrange("list", 0, -1);
expectRedisResult(arrayResult).toBeSuccessful().toHaveLength(3).toContain("item");
#expectSqlQueryResult
function expectSqlQueryResult<T = Record<string, any>>(result: SqlQueryResult<T>, _: unknown): SqlQueryResultExpectation<T>Create a fluent expectation chain for SQL query result validation.
Returns an expectation object with chainable assertion methods. Each assertion throws an Error if it fails, making it ideal for testing.
Parameters
resultSqlQueryResult<T>- The SQL query result to validate
_unknown
Returns
SqlQueryResultExpectation<T> — A fluent expectation chain
Examples
Basic assertions
const result = await client.query("SELECT * FROM users WHERE active = true");
expectSqlQueryResult(result)
.toBeSuccessful()
.toHaveLengthGreaterThanOrEqual(1)
.toMatchObject({ name: "Alice" });
Insert/Update assertions
const result = await client.query(
"INSERT INTO users (name, email) VALUES ($1, $2)",
["Bob", "bob@example.com"]
);
expectSqlQueryResult(result)
.toBeSuccessful()
.toHaveRowCount(1)
.toHaveLastInsertId();
Custom matcher with mapped data
expectSqlQueryResult(result)
.toBeSuccessful()
.toHaveMapMatching(
(row) => row.name.toUpperCase(),
(names) => assertEquals(names, ["ALICE", "BOB"])
);
Performance assertions
expectSqlQueryResult(result)
.toBeSuccessful()
.toHaveDurationLessThan(100); // Must complete within 100ms
#expectSqsMessage
function expectSqsMessage(message: SqsMessage): SqsMessageExpectationCreate a fluent expectation chain for SQS message validation.
Parameters
messageSqsMessage
#expectSqsResult
function expectSqsResult<R extends SqsResult>(result: R): SqsExpectation<R>Create a fluent expectation chain for any SQS result validation.
This unified function accepts any SQS result type and returns the appropriate expectation interface based on the result's type discriminator. Supports send, sendBatch, receive, delete, deleteBatch, ensureQueue, and deleteQueue results.
Parameters
resultR- The SQS result to create expectations for
Returns
SqsExpectation<R> — A typed expectation object matching the result type
Examples
Send result validation
const sendResult = await sqs.send(JSON.stringify({ orderId: "123" }));
expectSqsResult(sendResult)
.toBeSuccessful()
.hasMessageId()
.toHaveDurationLessThan(1000);
Receive result validation
const receiveResult = await sqs.receive({ maxMessages: 10 });
expectSqsResult(receiveResult)
.toBeSuccessful()
.toHaveContent()
.countAtLeast(1)
.toMatchObject({ body: "orderId" });
Batch operations
// Send batch
const batchResult = await sqs.sendBatch([
{ id: "1", body: "msg1" },
{ id: "2", body: "msg2" },
]);
expectSqsResult(batchResult)
.toBeSuccessful()
.allSuccessful()
.noFailures();
// Delete batch
const deleteResult = await sqs.deleteBatch(receiptHandles);
expectSqsResult(deleteResult)
.toBeSuccessful()
.successfulCount(2);
Queue management
// Ensure queue exists
const ensureResult = await sqs.ensureQueue("test-queue");
expectSqsResult(ensureResult)
.toBeSuccessful()
.hasQueueUrl()
.queueUrlContains("test-queue");
// Delete queue
const deleteResult = await sqs.deleteQueue(queueUrl);
expectSqsResult(deleteResult).toBeSuccessful();
Individual message validation
const receiveResult = await sqs.receive();
for (const msg of receiveResult.messages) {
expectSqsMessage(msg)
.bodyJsonContains({ type: "ORDER" })
.hasAttribute("correlationId");
}
#formatDifferences
function formatDifferences(actual: unknown, expected: unknown): string[]Generates a diff between actual and expected values using LCS algorithm.
This uses @std/internal/diff which implements a Longest Common Subsequence algorithm for intelligent diff generation. This produces much more readable output than simple line-by-line comparison, especially for arrays and nested objects.
Parameters
actualunknown- The actual value
expectedunknown- The expected value
Returns
string[] — Array of formatted diff lines (includes [Diff] header)
#formatValue
function formatValue(value: unknown): stringFormats a value for display in error messages.
Uses @std/internal/format for consistent formatting that matches Deno's built-in assertion library.
Parameters
valueunknown- The value to format
Returns
string — Formatted string representation
#fromConnectError
function fromConnectError(error: ConnectError, metadata?: Record<string, string>): ConnectRpcErrorConvert ConnectRPC's ConnectError to ConnectRpcError.
Parameters
errorConnectError- The ConnectError from @connectrpc/connect
metadata?Record<string, string>- Optional metadata from the response
Returns
ConnectRpcError — Appropriate ConnectRpcError subclass based on error code
#getStatusName
function getStatusName(code: ConnectRpcStatusCode): stringGet the name of a ConnectRPC/gRPC status code.
Parameters
Examples
getStatusName(0); // "OK"
getStatusName(5); // "NOT_FOUND"
getStatusName(16); // "UNAUTHENTICATED"
#isConnectRpcStatusCode
function isConnectRpcStatusCode(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
#stripAnsi
function stripAnsi(text: string): stringStrips ANSI escape sequences from a string. Useful for testing error messages.
Parameters
textstring- Text with ANSI codes
Returns
string — Text without ANSI codes
Type Aliases
#BodyInit
type BodyInit = string | Uint8Array | Record<string, unknown> | FormData | URLSearchParamsRequest body type.
#ConnectProtocol
type ConnectProtocol = "connect" | "grpc" | "grpc-web"Protocol to use for ConnectRPC transport.
#ConnectRpcStatusCode
type ConnectRpcStatusCode = 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.
#DenoKvResult
type DenoKvResult<T = unknown> = DenoKvGetResult<T> | DenoKvSetResult | DenoKvDeleteResult | DenoKvListResult<T> | DenoKvAtomicResultUnion of all Deno KV result types.
#FileDescriptorSet
type FileDescriptorSet = MessageShape<FileDescriptorSetSchema>FileDescriptorSet message type from @bufbuild/protobuf. This is the decoded protobuf message containing file descriptors.
#Filter
type Filter = Record<string, any>MongoDB filter type (simplified for compatibility with mongodb driver) Allows query operators like $gte, $lt, $in, etc.
#MongoResult
type MongoResult<T = any> = MongoFindResult<T> | MongoInsertOneResult | MongoInsertManyResult | MongoUpdateResult | MongoDeleteResult | MongoFindOneResult<T> | MongoCountResultUnion of all MongoDB result types.
#RabbitMqExchangeType
type RabbitMqExchangeType = "direct" | "topic" | "fanout" | "headers"Exchange type.
#RabbitMqResult
type RabbitMqResult = RabbitMqPublishResult | RabbitMqConsumeResult | RabbitMqAckResult | RabbitMqQueueResult | RabbitMqExchangeResultUnion of all RabbitMQ result types.
#RedirectMode
type RedirectMode = "follow" | "manual" | "error"Redirect handling mode.
- "follow": Automatically follow redirects (default)
- "manual": Return redirect response without following
- "error": Throw error on redirect
#RedisResult
type RedisResult<T = unknown> = RedisCommonResult<T> | RedisGetResult | RedisSetResult | RedisCountResult | RedisArrayResult<T> | RedisHashResultUnion of all Redis result types.
#SqlErrorKind
type SqlErrorKind = "query" | "constraint" | "deadlock" | "unknown"SQL-specific error kinds.
#SqlIsolationLevel
type SqlIsolationLevel = "read_uncommitted" | "read_committed" | "repeatable_read" | "serializable"Transaction isolation level.
#SqsResult
type SqsResult = SqsSendResult | SqsSendBatchResult | SqsReceiveResult | SqsDeleteResult | SqsDeleteBatchResult | SqsEnsureQueueResult | SqsDeleteQueueResultUnion type of all SQS result types.
#UpdateFilter
type UpdateFilter = Record<string, any>MongoDB update filter type (simplified for compatibility with mongodb driver) Allows update operators like $set, $inc, $unset, etc.
Variables
#ConnectRpcStatus
const ConnectRpcStatus: { 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.
#outdent
const outdent: Outdent