UNPKG

@graphql-mesh/transport-grpc

Version:
79 lines (78 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.addMetaDataToCall = addMetaDataToCall; exports.addExecutionLogicToScalar = addExecutionLogicToScalar; const tslib_1 = require("tslib"); const lodash_get_1 = tslib_1.__importDefault(require("lodash.get")); const string_interpolation_1 = require("@graphql-mesh/string-interpolation"); const utils_1 = require("@graphql-mesh/utils"); const grpc_js_1 = require("@grpc/grpc-js"); function isBlob(input) { return input != null && input.stream instanceof Function; } function addMetaDataToCall(callFn, input, resolverData, metaData, isResponseStream = false) { const callFnArguments = []; if (!isBlob(input)) { callFnArguments.push(input); } if (metaData) { const meta = new grpc_js_1.Metadata(); for (const [key, value] of Object.entries(metaData)) { let metaValue = value; if (Array.isArray(value)) { // Extract data from context metaValue = (0, lodash_get_1.default)(resolverData.context, value); } // Ensure that the metadata is compatible with what node-grpc expects if (typeof metaValue !== 'string' && !(metaValue instanceof Buffer)) { metaValue = JSON.stringify(metaValue); } if (typeof metaValue === 'string') { metaValue = string_interpolation_1.stringInterpolator.parse(metaValue, resolverData); } meta.add(key, metaValue); } callFnArguments.push(meta); } return new Promise((resolve, reject) => { const call = callFn(...callFnArguments, (error, response) => { if (error) { reject(error); } resolve(response); }); if (isResponseStream) { let isCancelled = false; const responseStreamWithCancel = (0, utils_1.withCancel)(call, () => { if (!isCancelled) { call.call?.cancelWithStatus(0, 'Cancelled by GraphQL Mesh'); isCancelled = true; } }); resolve(responseStreamWithCancel); if (isBlob(input)) { const blobStream = input.stream(); blobStream.pipe(call); } } }); } function addExecutionLogicToScalar(nonExecutableScalar, actualScalar) { Object.defineProperties(nonExecutableScalar, { serialize: { value: actualScalar.serialize, }, parseValue: { value: actualScalar.parseValue, }, parseLiteral: { value: actualScalar.parseLiteral, }, extensions: { value: { ...actualScalar.extensions, ...nonExecutableScalar.extensions, }, }, }); }