UNPKG

@cerbos/grpc

Version:

Client library for interacting with the Cerbos policy decision point service over gRPC from server-side Node.js applications

73 lines 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Transport = void 0; const grpc_js_1 = require("@grpc/grpc-js"); const core_1 = require("@cerbos/core"); const svc_1 = require("./protobuf/cerbos/svc/v1/svc"); const health_1 = require("./protobuf/grpc/health/v1/health"); const services = { admin: svc_1.CerbosAdminServiceService, cerbos: svc_1.CerbosServiceService, health: health_1.HealthService, }; class Transport { client; constructor(client) { this.client = client; } async unary(service, method, request, headers, abortHandler) { const { path, requestSerialize, responseDeserialize } = services[service][method]; // https://github.com/microsoft/TypeScript/issues/30581 return await new Promise((resolve, reject) => { abortHandler.throwIfAborted(); const call = this.client.makeUnaryRequest(path, requestSerialize, responseDeserialize, request, metadata(headers), (error, response) => { if (error) { reject(new core_1.NotOK((error.code || core_1.Status.UNKNOWN), error.details)); } else if (!response) { reject(new core_1.NotOK(core_1.Status.UNKNOWN, "No response received")); } else { resolve(response); } }); abortHandler.onAbort((error) => { reject(error); call.cancel(); }); }); } async *serverStream(service, method, request, headers, abortHandler) { const { path, requestSerialize, responseDeserialize } = services[service][method]; // https://github.com/microsoft/TypeScript/issues/30581 abortHandler.throwIfAborted(); try { const stream = this.client.makeServerStreamRequest(path, requestSerialize, responseDeserialize, request, metadata(headers)); abortHandler.onAbort(() => { stream.cancel(); }); for await (const response of stream) { yield response; } } catch (error) { abortHandler.throwIfAborted(); if ((0, core_1._isObject)(error)) { const { code, details } = error; if (typeof code === "number" && typeof details === "string") { throw new core_1.NotOK(code in core_1.Status ? code : core_1.Status.UNKNOWN, details); } } throw new core_1.NotOK(core_1.Status.UNKNOWN, error instanceof Error ? `Error reading stream: ${error.message}` : "Error reading stream", { cause: error }); } } } exports.Transport = Transport; function metadata(headers) { const metadata = new grpc_js_1.Metadata(); for (const [name, value] of headers) { metadata.set(name, value); } return metadata; } //# sourceMappingURL=transport.js.map