{"name":"nice-grpc","version":"1.2.2","keywords":["grpc","promise","async-iterable","abort-controller","abort-signal","typescript"],"author":{"name":"Daniel Lytkin","email":"aikoven@deeplay.io"},"license":"MIT","_id":"nice-grpc@1.2.2","maintainers":[{"name":"aikoven","email":"dan.lytkin@gmail.com"}],"homepage":"https://github.com/deeplay-io/nice-grpc#readme","bugs":{"url":"https://github.com/deeplay-io/nice-grpc/issues"},"dist":{"shasum":"5e31ebfdbd26285857077961ffea2e61ee5d9ad8","tarball":"http://registry-npm.ywwl.com/nice-grpc/download/nice-grpc-1.2.2.tgz","fileCount":103,"integrity":"sha512-XvVFAOVZyK9FnMEfP/dxqVsPjyfcQx86zxgsh5sNUWNnQGiTMxjig09pC4CLU6ShNS31q8+gMJ85NqbcRr7oWg==","signatures":[{"sig":"MEQCIBi/7UcqteX3pbwsgOCcjfahyteYQs449amtbLtF8NWlAiBHs7gp20vwfWCJwSdkcc124Jc+n1PkuLcCEF4YeMxOhA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":190002,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJi503/ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqE0BAAiJm3Bk6NTADp+jjMtSvp1bqmDBzxzzooA/NnZEJ9yee49hs/\r\nvW+nw/lbAUAWdj3NT2earLWloTgH8ZNOte9KkGW+B9GGsgcq4pcasGhDGy9T\r\nsNqUwyg9FefzkyrBHk9eg932ghuuFJnZ0dyec3oSfcB/HTefGLrY++RlUXKq\r\nTDDrxJvxiqcelSVnAltztdTFgQs4UIq59DxtUYxuYFDamDzWTqvOY6sBzZUr\r\nYP5Ul2DAWZ0IH1SUIwozGy7PcgBj7k32CDWK3bvA0bX08ADoBC3mxg+0K6Ki\r\niiZPbKEngJUQEra8LOW2koIMVvULlWaZiwRLxfVGzYZiFg0cJ32veaXC6Vm9\r\nPFnq7l8NOr2+KU2zBHe2H29Pxr8TWqYZ2lndAGsu3UHQJUFhB5TlzMbpb31Y\r\n8bLcRObFvA5MtvIAMFbsmTaKH+unsGrVfKfdq0rlChVegrw6pvuVAmYpaQoo\r\nYBaC33sucEmLmTUK9tNOtRgJYzmmInz4ava1slTFXDIk/HcbjUV0sh6IkXBU\r\nOAduGX/FhVtrb6pYExqVr32uu9RmKOuAfpTaPRz1gkMmuiY/PPug3TvawBuZ\r\nHKU1JKOzKgemFsqQV77208LStVArj+g7b48r9piFyPYjIYXC4l8h8vBY0CjF\r\nxoBveU4Z6bRsxjHHiWGSEsldko3Yrxwi1iw=\r\n=dF9O\r\n-----END PGP SIGNATURE-----\r\n","size":33363,"noattachment":false,"key":"/nice-grpc/-/nice-grpc-1.2.2.tgz"},"main":"lib/index.js","gitHead":"1eae2167ee0eeb1e7ab0f56278716b59269ffe46","scripts":{"test":"jest","build":"tsc -P tsconfig.build.json","clean":"rimraf lib","prepare":"npm run prepare:proto","prepare:proto":"npm run prepare:proto:grpc-js && npm run prepare:proto:ts-proto","prepublishOnly":"npm run clean && npm run build && npm test","prepare:proto:grpc-js":"mkdirp ./fixtures/grpc-js && grpc_tools_node_protoc --plugin=protoc-gen-grpc=./node_modules/.bin/grpc_tools_node_protoc_plugin --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts --js_out=import_style=commonjs,binary:./fixtures/grpc-js --ts_out=grpc_js:./fixtures/grpc-js --grpc_out=grpc_js:./fixtures/grpc-js -I fixtures fixtures/*.proto","prepare:proto:ts-proto":"mkdirp ./fixtures/ts-proto && grpc_tools_node_protoc --ts_proto_out=./fixtures/ts-proto --ts_proto_opt=outputServices=nice-grpc,outputServices=generic-definitions,useExactTypes=false,esModuleInterop=true -I fixtures fixtures/*.proto"},"typings":"lib/index.d.ts","_npmUser":{"name":"aikoven","email":"dan.lytkin@gmail.com"},"repository":{"url":"git+https://github.com/deeplay-io/nice-grpc.git","type":"git"},"_npmVersion":"lerna/4.0.0/node@v16.14.2+x64 (darwin)","description":"A Node.js gRPC library that is nice to you","directories":{},"_nodeVersion":"16.14.2","dependencies":{"@grpc/grpc-js":"^1.6.1","nice-grpc-common":"^1.1.0","abort-controller-x":"^0.2.4","node-abort-controller":"^1.2.1"},"_hasShrinkwrap":false,"devDependencies":{"mkdirp":"^1.0.4","rimraf":"^2.6.3","get-port":"^5.1.1","ts-proto":"^1.112.0","grpc-tools":"^1.10.0","defer-promise":"^2.0.1","@types/get-port":"^4.2.0","google-protobuf":"^3.14.0","@tsconfig/node12":"^1.0.8","@types/defer-promise":"^1.0.0","@types/google-protobuf":"^3.7.4","grpc_tools_node_protoc_ts":"^5.0.1"},"_npmOperationalInternal":{"tmp":"tmp/nice-grpc_1.2.2_1659325951510_0.44035648691043305","host":"s3://npm-registry-packages"},"readme":"# nice-grpc [![npm version][npm-image]][npm-url] <!-- omit in toc -->\n\nA Node.js gRPC library that is nice to you. Built on top of\n[`grpc-js`](https://www.npmjs.com/package/@grpc/grpc-js).\n\n- [Features](#features)\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Compiling Protobuf files](#compiling-protobuf-files)\n    - [Using `ts-proto`](#using-ts-proto)\n    - [Using `google-protobuf`](#using-google-protobuf)\n  - [Server](#server)\n    - [Call context](#call-context)\n    - [Errors](#errors)\n    - [Metadata](#metadata)\n    - [Cancelling calls](#cancelling-calls)\n    - [Server streaming](#server-streaming)\n      - [Example: IxJS](#example-ixjs)\n      - [Example: Observables](#example-observables)\n    - [Client streaming](#client-streaming)\n    - [Middleware](#middleware)\n      - [Example: Logging](#example-logging)\n      - [Example: Error handling](#example-error-handling)\n      - [Example: Authentication](#example-authentication)\n  - [Client](#client)\n    - [Call options](#call-options)\n    - [Channels](#channels)\n    - [Metadata](#metadata-1)\n    - [Errors](#errors-1)\n    - [Cancelling calls](#cancelling-calls-1)\n    - [Server streaming](#server-streaming-1)\n    - [Client streaming](#client-streaming-1)\n    - [Middleware](#middleware-1)\n      - [Example: Logging](#example-logging-1)\n\n## Features\n\n- Written in TypeScript for TypeScript.\n- Modern API that uses Promises and Async Iterables for streaming.\n- Easy cancellation propagation with\n  [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).\n- Client and server middleware support via concise API that uses Async\n  Generators.\n\n## Prerequisites\n\nSupports NodeJS 14+. Global `AbortController` is required which is\n[available in NodeJS](https://nodejs.org/api/globals.html#class-abortcontroller)\nsince 15.0.0, NodeJS 14.17+ requires the\n[--experimental-abortcontroller](https://nodejs.org/docs/latest-v14.x/api/cli.html#cli_experimental_abortcontroller)\nflag. A [polyfill](https://www.npmjs.com/package/abort-controller) is available\nfor older NodeJS versions.\n\n## Installation\n\n```\nnpm install nice-grpc\n```\n\n## Usage\n\n### Compiling Protobuf files\n\nThe recommended way is to use\n[`ts-proto`](https://github.com/stephenh/ts-proto).\n\n#### Using `ts-proto`\n\nInstall necessary tools:\n\n```\nnpm install protobufjs long\nnpm install --save-dev grpc-tools ts-proto\n```\n\n> Use `ts-proto` version not older than `1.112.0`.\n\nGiven a Protobuf file `./proto/example.proto`, generate TypeScript code into\ndirectory `./compiled_proto`:\n\n```\n./node_modules/.bin/grpc_tools_node_protoc \\\n  --plugin=protoc-gen-ts_proto=./node_modules/.bin/protoc-gen-ts_proto \\\n  --ts_proto_out=./compiled_proto \\\n  --ts_proto_opt=outputServices=nice-grpc,outputServices=generic-definitions,useExactTypes=false \\\n  --proto_path=./proto \\\n  ./proto/example.proto\n```\n\n> You can omit the `--plugin` flag if you invoke this command via\n> [npm script](https://docs.npmjs.com/cli/v7/using-npm/scripts).\n\nWhen running on Windows command line, you may need to wrap the `ts_proto_opt`\nvalue with double quotes:\n\n```\n--ts_proto_opt=\"outputServices=nice-grpc,outputServices=generic-definitions,useExactTypes=false\"\n```\n\n#### Using `google-protobuf`\n\nInstall necessary tools:\n\n```\nnpm install google-protobuf\nnpm install --save-dev grpc-tools grpc_tools_node_protoc_ts @types/google-protobuf\n```\n\nGiven a Protobuf file `./proto/example.proto`, generate JS code and TypeScript\ndefinitions into directory `./compiled_proto`:\n\n```\n./node_modules/.bin/grpc_tools_node_protoc \\\n  --plugin=protoc-gen-grpc=./node_modules/.bin/grpc_tools_node_protoc_plugin \\\n  --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \\\n  --js_out=import_style=commonjs,binary:./compiled_proto \\\n  --ts_out=grpc_js:./compiled_proto \\\n  --grpc_out=grpc_js:./compiled_proto \\\n  --proto_path=./proto \\\n  ./proto/example.proto\n```\n\n### Server\n\nConsider the following Protobuf definition:\n\n```proto\nsyntax = \"proto3\";\n\npackage nice_grpc.example;\n\nservice ExampleService {\n  rpc ExampleUnaryMethod(ExampleRequest) returns (ExampleResponse) {};\n}\n\nmessage ExampleRequest {\n  // ...\n}\nmessage ExampleResponse {\n  // ...\n}\n```\n\nAfter compiling Protobuf file, we can write service implementation:\n\nWhen compiling Protobufs using `ts-proto`:\n\n```ts\nimport {\n  ExampleServiceImplementation,\n  ExampleRequest,\n  ExampleResponse,\n  DeepPartial,\n} from './compiled_proto/example';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    // ... method logic\n\n    return response;\n  },\n};\n```\n\nAlternatively, you can use classes:\n\n```ts\nclass ExampleServiceImpl implements ExampleServiceImplementation {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    // ... method logic\n\n    return response;\n  }\n}\n```\n\nWith `ts-proto`, response is automatically wrapped with `fromPartial`.\n\nWhen compiling Protobufs using `google-protobuf`:\n\n```ts\nimport {ServiceImplementation} from 'nice-grpc';\nimport {ExampleRequest, ExampleResponse} from './compiled_proto/example_pb';\nimport {IExampleService} from './compiled_proto/example_grpc_pb';\n\nconst exampleServiceImpl: ServiceImplementation<IExampleService> = {\n  async exampleUnaryMethod(request: ExampleRequest): Promise<ExampleResponse> {\n    // ... method logic\n\n    return response;\n  },\n};\n```\n\nFurther examples use `ts-proto`.\n\nNow we can create and start a server that exposes our service:\n\n```ts\nimport {createServer} from 'nice-grpc';\nimport {ExampleServiceDefinition} from './compiled_proto/example';\n\nconst server = createServer();\n\nserver.add(ExampleServiceDefinition, exampleServiceImpl);\n\nawait server.listen('0.0.0.0:8080');\n```\n\nOnce we need to stop, gracefully shut down the server:\n\n```ts\nawait server.shutdown();\n```\n\n#### Call context\n\nEach service implementation method receives `CallContext` as a second argument,\nthat has type:\n\n```ts\ntype CallContext = {\n  /**\n   * Request metadata from client.\n   */\n  metadata: Metadata;\n  /**\n   * Client address.\n   */\n  peer: string;\n  /**\n   * Response header. Sent with the first response, or when `sendHeader` is\n   * called.\n   */\n  header: Metadata;\n  /**\n   * Manually send response header.\n   */\n  sendHeader(): void;\n  /**\n   * Response trailer. Sent when server method returns or throws.\n   */\n  trailer: Metadata;\n  /**\n   * Signal that is aborted once the call gets cancelled.\n   */\n  signal: AbortSignal;\n};\n```\n\nCall context may be augmented by [Middleware](#middleware).\n\n#### Errors\n\nTo report an error to a client, use `ServerError`.\n\n> Any thrown errors other than `ServerError` will result in client receiving\n> error with status code `UNKNOWN`. Use server middleware for custom handling of\n> uncaught errors.\n\nSee [gRPC docs](https://grpc.github.io/grpc/core/md_doc_statuscodes.html) for\nthe correct usage of status codes.\n\n```ts\nimport {ServerError, Status} from 'nice-grpc';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    // ... method logic\n\n    throw new ServerError(Status.NOT_FOUND, 'Requested data does not exist');\n  },\n};\n```\n\n#### Metadata\n\nA server receives client metadata along with request, and can send response\nmetadata in header and trailer.\n\n```ts\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n    context: CallContext,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    // read client metadata\n    const someValue = context.metadata.get('some-key');\n\n    // add metadata to header\n    context.header.set('some-key', 'some-value');\n\n    // ... method logic\n\n    // add metadata to trailer\n    context.trailer.set('some-key', 'some-value');\n\n    return response;\n  },\n};\n```\n\n#### Cancelling calls\n\nA server receives\n[`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)\nthat gets aborted once the call is cancelled by the client. You can use it to\ncancel any inner requests.\n\n```ts\nimport fetch from 'node-fetch';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n    context: CallContext,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    const response = await fetch('http://example.com', {\n      signal: context.signal,\n    });\n\n    // ...\n  },\n};\n```\n\n#### Server streaming\n\nConsider the following Protobuf definition:\n\n```proto\nservice ExampleService {\n  rpc ExampleStreamingMethod(ExampleRequest)\n    returns (stream ExampleResponse) {};\n}\n```\n\nService implementation defines this method as an Async Generator:\n\n```ts\nimport {delay} from 'abort-controller-x';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async *exampleStreamingMethod(\n    request: ExampleRequest,\n    context: CallContext,\n  ): AsyncIterable<DeepPartial<ExampleResponse>> {\n    for (let i = 0; i < 10; i++) {\n      await delay(context.signal, 1000);\n\n      yield response;\n    }\n  },\n};\n```\n\n##### Example: IxJS\n\n```ts\nimport {range} from 'ix/asynciterable';\nimport {withAbort, map} from 'ix/asynciterable/operators';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async *exampleStreamingMethod(\n    request: ExampleRequest,\n    context: CallContext,\n  ): AsyncIterable<DeepPartial<ExampleResponse>> {\n    yield* range(0, 10).pipe(\n      withAbort(context.signal),\n      map(() => response),\n    );\n  },\n};\n```\n\n##### Example: Observables\n\n```ts\nimport {Observable} from 'rxjs';\nimport {from} from 'ix/asynciterable';\nimport {withAbort} from 'ix/asynciterable/operators';\n\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async *exampleStreamingMethod(\n    request: ExampleRequest,\n    context: CallContext,\n  ): AsyncIterable<DeepPartial<ExampleResponse>> {\n    const observable: Observable<DeepPartial<ExampleResponse>>;\n\n    yield* from(observable).pipe(withAbort(context.signal));\n  },\n};\n```\n\n#### Client streaming\n\nGiven a client streaming method:\n\n```proto\nservice ExampleService {\n  rpc ExampleClientStreamingMethod(stream ExampleRequest)\n    returns (ExampleResponse) {};\n}\n```\n\nService implementation method receives request as an Async Iterable:\n\n```ts\nconst exampleServiceImpl: ExampleServiceImplementation = {\n  async exampleClientStreamingMethod(\n    request: AsyncIterable<ExampleRequest>,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    for await (const item of request) {\n      // ...\n    }\n\n    return response;\n  },\n};\n```\n\n#### Middleware\n\nServer middleware intercepts incoming calls allowing to:\n\n- Execute any logic before and after implementation methods\n- Look into request, request metadata and response\n- Interrupt a call before it reaches implementation by throwing a `ServerError`\n- Catch implementation errors and return friendly `ServerError`s to a client\n- Augment call context\n- Modify response header and trailer metadata\n\nServer middleware is defined as an Async Generator. The most basic no-op\nmiddleware looks like this:\n\n```ts\nimport {ServerMiddlewareCall, CallContext} from 'nice-grpc';\n\nasync function* middleware<Request, Response>(\n  call: ServerMiddlewareCall<Request, Response>,\n  context: CallContext,\n) {\n  return yield* call.next(call.request, context);\n}\n```\n\nFor unary and client streaming methods, the `call.next` generator yields no\nitems and returns a single response; for server streaming and bidirectional\nstreaming methods, it yields each response and returns void. By doing\n`return yield*` we cover both cases. To handle these cases separately, we can\nwrite a middleware as follows:\n\n```ts\nasync function* middleware<Request, Response>(\n  call: ServerMiddlewareCall<Request, Response>,\n  context: CallContext,\n) {\n  if (!call.responseStream) {\n    const response = yield* call.next(call.request, context);\n\n    return response;\n  } else {\n    for await (const response of call.next(call.request, context)) {\n      yield response;\n    }\n\n    return;\n  }\n}\n```\n\nTo attach a middleware to a server, use a `server.use` method. Note that\n`server.use` returns a new server instance.\n\n```ts\nconst server = createServer().use(middleware1).use(middleware2);\n```\n\nA middleware that is attached first, will be invoked first.\n\nYou can also attach middleware per-service:\n\n```ts\nconst server = createServer().use(middlewareA);\n\nserver.with(middlewareB).add(Service1, service1Impl);\nserver.with(middlewareC).add(Service2, service2Impl);\n```\n\nIn the above example, `Service1` gets `middlewareA` and `middlewareB`, and\n`Service2` gets `middlewareA` and `middlewareC`.\n\n##### Example: Logging\n\nLog all calls:\n\n```ts\nimport {Status} from 'nice-grpc';\nimport {isAbortError} from 'abort-controller-x';\n\nasync function* loggingMiddleware<Request, Response>(\n  call: ServerMiddlewareCall<Request, Response>,\n  context: CallContext,\n) {\n  const {path} = call.method;\n\n  console.log('Server call', path, 'start');\n\n  try {\n    const result = yield* call.next(call.request, context);\n\n    console.log('Server call', path, 'end: OK');\n\n    return result;\n  } catch (error) {\n    if (error instanceof ServerError) {\n      console.log(\n        'Server call',\n        path,\n        `end: ${Status[error.code]}: ${error.details}`,\n      );\n    } else if (isAbortError(error)) {\n      console.log('Server call', path, 'cancel');\n    } else {\n      console.log('Server call', path, `error: ${error?.stack}`);\n    }\n\n    throw error;\n  }\n}\n```\n\n##### Example: Error handling\n\nCatch unknown errors and wrap them into `ServerError`s with friendly messages:\n\n```ts\nimport {Status} from 'nice-grpc';\nimport {isAbortError} from 'abort-controller-x';\n\nasync function* errorHandlingMiddleware<Request, Response>(\n  call: ServerMiddlewareCall<Request, Response>,\n  context: CallContext,\n) {\n  try {\n    return yield* call.next(call.request, context);\n  } catch (error: unknown) {\n    if (error instanceof ServerError || isAbortError(error)) {\n      throw error;\n    }\n\n    let details = 'Unknown server error occurred';\n\n    if (process.env.NODE_ENV === 'development') {\n      details += `: ${error.stack}`;\n    }\n\n    throw new ServerError(Status.UNKNOWN, details);\n  }\n}\n```\n\n##### Example: Authentication\n\nValidate JSON Web Token (JWT) from request metadata and put its claims to\n`CallContext`:\n\n```ts\nimport {Status} from 'nice-grpc';\nimport createRemoteJWKSet from 'jose/jwks/remote';\nimport jwtVerify, {JWTPayload} from 'jose/jwt/verify';\nimport {JOSEError} from 'jose/util/errors';\n\nconst jwks = createRemoteJWKSet(\n  new URL('https://example.com/.well-known/jwks.json'),\n);\n\ntype AuthCallContextExt = {\n  auth: JWTPayload;\n};\n\nasync function* authMiddleware<Request, Response>(\n  call: ServerMiddlewareCall<Request, Response, AuthCallContextExt>,\n  context: CallContext,\n) {\n  const authorization = context.metadata.get('Authorization');\n\n  if (authorization == null) {\n    throw new ServerError(\n      Status.UNAUTHENTICATED,\n      'Missing Authorization metadata',\n    );\n  }\n\n  const parts = authorization.toString().split(' ');\n\n  if (parts.length !== 2 || parts[0] !== 'Bearer') {\n    throw new ServerError(\n      Status.UNAUTHENTICATED,\n      'Invalid Authorization metadata format. Expected \"Bearer <token>\"',\n    );\n  }\n\n  const token = parts[1];\n\n  const {payload} = await jwtVerify(token, jwks).catch(error => {\n    if (error instanceof JOSEError) {\n      throw new ServerError(Status.UNAUTHENTICATED, error.message);\n    } else {\n      throw error;\n    }\n  });\n\n  return yield* call.next(call.request, {\n    ...context,\n    auth: payload,\n  });\n}\n```\n\nService implementation can then access JWT claims via call context:\n\n```ts\nconst exampleServiceImpl: ExampleServiceImplementation<AuthCallContextExt> = {\n  async exampleUnaryMethod(\n    request: ExampleRequest,\n    context: CallContext & AuthCallContextExt,\n  ): Promise<DeepPartial<ExampleResponse>> {\n    const userId = context.auth.sub;\n\n    // ...\n  },\n};\n```\n\n### Client\n\nConsider the following Protobuf definition:\n\n```proto\nsyntax = \"proto3\";\n\npackage nice_grpc.example;\n\nservice ExampleService {\n  rpc ExampleUnaryMethod(ExampleRequest) returns (ExampleResponse) {};\n}\n\nmessage ExampleRequest {\n  // ...\n}\nmessage ExampleResponse {\n  // ...\n}\n```\n\nAfter compiling Protobuf file, we can create the client:\n\nWhen compiling Protobufs using `ts-proto`:\n\n```ts\nimport {createChannel, createClient} from 'nice-grpc';\nimport {ExampleServiceDefinition} from './compiled_proto/example';\nimport type {ExampleServiceClient} from './compiled_proto/example';\n\nconst channel = createChannel('localhost:8080');\n\nconst client: ExampleServiceClient = createClient(\n  ExampleServiceDefinition,\n  channel,\n);\n```\n\nWhen compiling Protobufs using `google-protobuf`:\n\n```ts\nimport {createChannel, createClient, Client} from 'nice-grpc';\nimport {\n  ExampleService,\n  IExampleService,\n} from './compiled_proto/example_grpc_pb';\n\nconst channel = createChannel('localhost:8080');\n\nconst client: Client<IExampleService> = createClient(ExampleService, channel);\n```\n\nFurther examples use `ts-proto`.\n\nCall the method:\n\n```ts\nconst response = await client.exampleUnaryMethod(request);\n```\n\nWith `ts-proto`, request is automatically wrapped with `fromPartial`.\n\nOnce we've done with the client, close the channel:\n\n```ts\nchannel.close();\n```\n\n#### Call options\n\nEach client method accepts `CallOptions` as an optional second argument, that\nhas type:\n\n```ts\ntype CallOptions = {\n  /**\n   * Request metadata.\n   */\n  metadata?: Metadata;\n  /**\n   * Signal that cancels the call once aborted.\n   */\n  signal?: AbortSignal;\n  /**\n   * Called when header is received.\n   */\n  onHeader?(header: Metadata): void;\n  /**\n   * Called when trailer is received.\n   */\n  onTrailer?(trailer: Metadata): void;\n};\n```\n\nCall options may be augmented by [Middleware](#middleware-1).\n\nWhen creating a client, you may specify default call options per method, or for\nall methods. This doesn't make much sense for built-in options, but may do for\nmiddleware, for example,\n[nice-grpc-client-middleware-deadline](/packages/nice-grpc-client-middleware-deadline):\n\n```ts\nconst client = createClient(ExampleServiceDefinition, channel, {\n  '*': {\n    // applies for all methods\n    deadline: 30_000,\n  },\n  exampleUnaryMethod: {\n    // applies for single method\n    deadline: 10_000,\n  },\n});\n```\n\nTo add default metadata, instead use a middleware that merges it with the\nmetadata passed to the call:\n\n```ts\nconst token = '...';\n\nconst client = createClientFactory().use((call, options) =>\n  call.next(call.request, {\n    ...options,\n    metadata: Metadata(options.metadata).set(\n      'Authorization',\n      `Bearer ${token}`,\n    ),\n  }),\n);\n```\n\n#### Channels\n\nBy default, a channel uses insecure connection. The following are equivalent:\n\n```ts\nimport {createChannel, ChannelCredentials} from 'nice-grpc';\n\ncreateChannel('example.com:8080');\ncreateChannel('http://example.com:8080');\ncreateChannel('example.com:8080', ChannelCredentials.createInsecure());\n```\n\nTo connect over TLS, use one of the following:\n\n```ts\ncreateChannel('https://example.com:8080');\ncreateChannel('example.com:8080', ChannelCredentials.createSsl());\n```\n\nIf the port is omitted, it defaults to `80` for insecure connections, and `443`\nfor secure connections.\n\nTo wait for a channel to be ready before making calls, use\n`waitForChannelReady`. It is not required to call this function before making\ncalls — they will connect automatically. This can be useful if you want to\nverify that the server is reachable at startup.\n\n```ts\nimport {createChannel, waitForChannelReady} from 'nice-grpc';\n\nconst channel = createChannel('localhost:8080');\n\nawait waitForChannelReady(channel, new Date(Date.now() + 5000));\n```\n\n##### Connection attempt timeout\n\nA connection attempt that gets no response is aborted after 20 seconds, matching\n`MIN_CONNECT_TIMEOUT` from the\n[gRPC connection backoff spec](https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md),\nafter which the channel retries it with backoff. This works around\n[grpc/grpc-node#2785](https://github.com/grpc/grpc-node/issues/2785): without\nsuch a timeout, a network path that accepts TCP connections but never responds\nleaves the channel stuck in `CONNECTING` forever, and calls made without a\ndeadline hang indefinitely.\n\nThe timeout can be changed via the `grpc.min_reconnect_backoff_ms` channel\noption, or disabled by setting it to `0`:\n\n```ts\ncreateChannel('example.com:8080', undefined, {\n  'grpc.min_reconnect_backoff_ms': 10_000,\n});\n```\n\nDespite its name, this is the channel argument that other gRPC implementations\nuse for `MIN_CONNECT_TIMEOUT`: C-core parses\n[`GRPC_ARG_MIN_RECONNECT_BACKOFF_MS`](https://github.com/grpc/grpc/blob/master/include/grpc/impl/channel_arg_names.h)\ninto the deadline it gives a connection attempt, and grpc-go has the equivalent\n`minConnectTimeout`. grpc-js itself does not read this option.\n\n#### Metadata\n\nClient can send request metadata and receive response header and trailer:\n\n```ts\nimport {Metadata} from 'nice-grpc';\n\nconst response = await client.exampleUnaryMethod(request, {\n  metadata: Metadata({key: 'value'}),\n  onHeader(header: Metadata) {\n    // ...\n  },\n  onTrailer(trailer: Metadata) {\n    // ...\n  },\n});\n```\n\n#### Errors\n\nClient calls may throw gRPC errors represented as `ClientError`, that contain\nstatus code and description.\n\n```ts\nimport {ClientError, Status} from 'nice-grpc';\nimport {ExampleResponse} from './compiled_proto/example';\n\nlet response: ExampleResponse | null;\n\ntry {\n  response = await client.exampleUnaryMethod(request);\n} catch (error: unknown) {\n  if (error instanceof ClientError && error.code === Status.NOT_FOUND) {\n    response = null;\n  } else {\n    throw error;\n  }\n}\n```\n\n#### Cancelling calls\n\nA client call can be cancelled using\n[`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).\n\n```ts\nimport {isAbortError} from 'abort-controller-x';\n\nconst abortController = new AbortController();\n\nclient\n  .exampleUnaryMethod(request, {\n    signal: abortController.signal,\n  })\n  .catch(error => {\n    if (isAbortError(error)) {\n      // aborted\n    } else {\n      throw error;\n    }\n  });\n\nabortController.abort();\n```\n\n#### Server streaming\n\nConsider the following Protobuf definition:\n\n```proto\nservice ExampleService {\n  rpc ExampleStreamingMethod(ExampleRequest)\n    returns (stream ExampleResponse) {};\n}\n```\n\nClient method returns an Async Iterable:\n\n```ts\nfor await (const response of client.exampleStreamingMethod(request)) {\n  // ...\n}\n```\n\n#### Client streaming\n\nGiven a client streaming method:\n\n```proto\nservice ExampleService {\n  rpc ExampleClientStreamingMethod(stream ExampleRequest)\n    returns (ExampleResponse) {};\n}\n```\n\nClient method expects an Async Iterable as its first argument:\n\n```ts\nimport {ExampleRequest, DeepPartial} from './compiled_proto/example';\n\nasync function* createRequest(): AsyncIterable<DeepPartial<ExampleRequest>> {\n  for (let i = 0; i < 10; i++) {\n    yield request;\n  }\n}\n\nconst response = await client.exampleClientStreamingMethod(createRequest());\n```\n\n#### Middleware\n\nClient middleware intercepts outgoing calls allowing to:\n\n- Execute any logic before and after reaching server\n- Modify request metadata\n- Look into request, response and response metadata\n- Send call multiple times for retries or hedging\n- Augment call options type to have own configuration\n\nClient middleware is defined as an Async Generator and is very similar to\n[Server middleware](#middleware). Key differences:\n\n- Middleware invocation order is reversed: middleware that is attached first,\n  will be invoked last.\n- There's no such thing as `CallContext` for client middleware; instead,\n  `CallOptions` are passed through the chain and can be accessed or altered by a\n  middleware.\n\nThe most basic no-op middleware looks like this:\n\n```ts\nimport {ClientMiddlewareCall, CallOptions} from 'nice-grpc';\n\nasync function* middleware<Request, Response>(\n  call: ClientMiddlewareCall<Request, Response>,\n  options: CallOptions,\n) {\n  return yield* call.next(call.request, options);\n}\n```\n\nFor unary and client streaming methods, the `call.next` generator yields no\nitems and returns a single response; for server streaming and bidirectional\nstreaming methods, it yields each response and returns void. By doing\n`return yield*` we cover both cases. To handle these cases separately, we can\nwrite a middleware as follows:\n\n```ts\nasync function* middleware<Request, Response>(\n  call: ClientMiddlewareCall<Request, Response>,\n  options: CallOptions,\n) {\n  if (!call.responseStream) {\n    const response = yield* call.next(call.request, options);\n\n    return response;\n  } else {\n    for await (const response of call.next(call.request, options)) {\n      yield response;\n    }\n\n    return;\n  }\n}\n```\n\nTo create a client with middleware, use a client factory:\n\n```ts\nimport {createClientFactory} from 'nice-grpc';\n\nconst client = createClientFactory()\n  .use(middleware1)\n  .use(middleware2)\n  .create(ExampleService, channel);\n```\n\nA middleware that is attached first, will be invoked last.\n\nYou can reuse a single factory to create multiple clients:\n\n```ts\nconst clientFactory = createClientFactory().use(middleware);\n\nconst client1 = clientFactory.create(Service1, channel1);\nconst client2 = clientFactory.create(Service2, channel2);\n```\n\nYou can also attach middleware per-client:\n\n```ts\nconst factory = createClientFactory().use(middlewareA);\n\nconst client1 = clientFactory.use(middlewareB).create(Service1, channel1);\nconst client2 = clientFactory.use(middlewareC).create(Service2, channel2);\n```\n\nIn the above example, `Service1` client gets `middlewareA` and `middlewareB`,\nand `Service2` client gets `middlewareA` and `middlewareC`.\n\nType augmentation to `Client` CallOptions is done automatically by adding a\nmiddleware, but can also be done by passing a generic. This code example shows\nhow to correctly annotate client type given that middleware has type\n`ClientMiddleware<{callOption?: number}>`.\n\n```ts\nlet client: ExampleServiceClient<{callOption?: number}>;\nclient = createClientFactory().use(middleware).create(ExampleService, channel);\n```\n\n##### Example: Logging\n\nLog all calls:\n\n```ts\nimport {\n  ClientMiddlewareCall,\n  CallOptions,\n  ClientError,\n  Status,\n} from 'nice-grpc';\nimport {isAbortError} from 'abort-controller-x';\n\nasync function* loggingMiddleware<Request, Response>(\n  call: ClientMiddlewareCall<Request, Response>,\n  options: CallOptions,\n) {\n  const {path} = call.method;\n\n  console.log('Client call', path, 'start');\n\n  try {\n    const result = yield* call.next(call.request, options);\n\n    console.log('Client call', path, 'end: OK');\n\n    return result;\n  } catch (error) {\n    if (error instanceof ClientError) {\n      console.log(\n        'Client call',\n        path,\n        `end: ${Status[error.code]}: ${error.details}`,\n      );\n    } else if (isAbortError(error)) {\n      console.log('Client call', path, 'cancel');\n    } else {\n      console.log('Client call', path, `error: ${error?.stack}`);\n    }\n\n    throw error;\n  }\n}\n```\n\n[npm-image]: https://badge.fury.io/js/nice-grpc.svg\n[npm-url]: https://badge.fury.io/js/nice-grpc\n","publish_time":1659325951666,"_cnpm_publish_time":1659325951666,"dist-tags":{"latest":"2.1.18"}}