Using gRPC from TypeScript
To use the Enterprise OPA gRPC API from TypeScript, we're relying on the SDKs generated from the Protobuf Schema published on Buf.
Installation
Add the registry to your NPM setup (only needs to be done once):
- npm
- yarn
npm config set @buf:registry https://buf.build/gen/npm/v1/
yarn config set npmScopes.buf.npmRegistryServer https://buf.build/gen/npm/v1/
Install the generated SDK:
- npm
- yarn
npm install @buf/styra_enterprise-opa.connectrpc_es@latest \
@bufbuild/protobuf@^1.10.0 \
@connectrpc/connect-node@^1.4.0
yarn add @buf/styra_enterprise-opa.connectrpc_es@latest \
@bufbuild/protobuf@^1.10.0 \
@connectrpc/connect-node@^1.4.0
Usage Example
This code requests the equivalent of POST /v1/data/my/policy
with input via gRPC:
import { createPromiseClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { Struct } from "@bufbuild/protobuf";
// generated code served from Buf Schema Registry
import { DataService } from "@buf/styra_enterprise-opa.connectrpc_es/eopa/data/v1/data_connect";
import {
GetDataRequest,
InputDocument,
} from "@buf/styra_enterprise-opa.bufbuild_es/eopa/data/v1/data_pb.js";
const transport = createGrpcTransport({
baseUrl: "http://127.0.0.1:9090",
httpVersion: "2",
});
const client = createPromiseClient(DataService, transport);
const input = Struct.fromJsonString(`{ "hello": "world" }`);
const req = new GetDataRequest({
path: "/my/policy", // "data.my.policy"
input: new InputDocument({ document: input }),
});
const resp = await client.getData(req);
console.log(resp.result?.document?.toJson()); // => { example: true }
Now run an Enterprise OPA instance serving this Rego,
# policy.rego
package my.policy
import rego.v1
example if input.hello == "world"
with a config enabling gRPC,
# enterprise-opa.yml
plugins:
grpc:
addr: localhost:9090
via eopa run --server --config-file enterprise-opa.yml policy.rego
, and execute the TypeScript code:
node --import tsx index.ts
{ example: true }
For the full package.json
, and the example configuration of Enterprise OPA, please see the examples repository.