UNPKG

krpc-js

Version:

KRPC client for NodeJs/Bun

103 lines (100 loc) 3.06 kB
// src/index.ts import { TextEncoder, TextDecoder } from "util"; // src/client.ts import { validateSync } from "class-validator"; import { Client, ChannelCredentials, Metadata } from "@grpc/grpc-js"; import { createSecureContext } from "tls"; import { InputProto, OutputProto, RpcError, mergeHeader, toResult, preproc } from "krpc-base"; function deserialize_OutputProto(buf) { return OutputProto.deserializeBinary(new Uint8Array(buf)); } function serialize_InputProto(arg) { return Buffer.from(arg.serializeBinary()); } var NodeClient = class { pathPrefix_; headers_; exceptionHandler_; timeoutMill_; client_; // {(message?: any, ...optionalParams: any[]) : void}; constructor(client, appPath, headers, exceptionHandler, timeoutMill) { this.client_ = client; this.pathPrefix_ = appPath; this.headers_ = headers; this.exceptionHandler_ = exceptionHandler; this.timeoutMill_ = timeoutMill; } // updateToken(accessToken: string): void { // setToken(this.headers_, accessToken); // } async(method, param, cfg) { const input = new InputProto(); const eh = cfg?.exceptionHandler || this.exceptionHandler_; if (param !== void 0 && param !== null) { const errors = validateSync(param, { validationError: { target: false } }); if (errors.length > 0) { return Promise.reject(new RpcError(RpcError.CLIENT_INVALID_ARGUMENT, JSON.stringify(errors))).catch(eh); } input.setUtf8(JSON.stringify(param)); } const options = {}; if (this.timeoutMill_) { const deadline = /* @__PURE__ */ new Date(); deadline.setMilliseconds(deadline.getMilliseconds() + this.timeoutMill_); options.deadline = deadline; } let hd = this.headers_; if (cfg?.headers) { hd = mergeHeader(cfg.headers, this.headers_); } return new Promise((resolve, reject) => { this.client_.makeUnaryRequest( this.pathPrefix_ + method, serialize_InputProto, deserialize_OutputProto, input, Metadata.fromHttp2Headers(hd), options, (err, response) => { if (err) { return reject(err); } resolve(toResult(response)); } ); }).catch(eh); } }; var clientMap = {}; var RpcClient = class { static create(c, options) { let client = clientMap[c.host]; if (!client) { const url = new URL(c.host); client = new Client( url.host, url.protocol == "https:" ? ChannelCredentials.createFromSecureContext(createSecureContext()) : ChannelCredentials.createInsecure(), options ); clientMap[c.host] = client; } const [_, appPath, headers] = preproc(c); return new NodeClient(client, appPath, headers, c.exceptionHandler, c.timeoutMill); } }; // src/index.ts globalThis["TextEncoder"] = globalThis["TextEncoder"] || TextEncoder; globalThis["TextDecoder"] = globalThis["TextDecoder"] || TextDecoder; var src_default = RpcClient; export { RpcClient, src_default as default };