This repository was archived by the owner on Nov 18, 2025. It is now read-only.
File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -334,6 +334,20 @@ export class GrpcClient {
334334
335335 return serviceStub ;
336336 }
337+
338+ /**
339+ * Creates a 'bytelength' function for a given proto message class.
340+ *
341+ * See {@link BundleDescriptor} about the meaning of the return value.
342+ *
343+ * @param {function } message - a constructor function that is generated by
344+ * protobuf.js. Assumes 'encoder' field in the message.
345+ * @return {function(Object):number } - a function to compute the byte length
346+ * for an object.
347+ */
348+ static createByteLengthFunction ( message : typeof protobuf . Message ) {
349+ return gax . createByteLengthFunction ( message ) ;
350+ }
337351}
338352
339353/**
Original file line number Diff line number Diff line change 1818 * Google API Extensions
1919 */
2020
21+ import type { Message } from 'protobufjs' ;
22+ import { warn } from './warnings' ;
2123import { BundleOptions } from './bundlingCalls/bundleExecutor' ;
2224import { toLowerCamelCase } from './util' ;
2325
@@ -702,3 +704,20 @@ export function constructSettings(
702704
703705 return defaults ;
704706}
707+
708+ export function createByteLengthFunction ( message : typeof Message ) {
709+ return function getByteLength ( obj : { } ) {
710+ try {
711+ return message . encode ( obj ) . finish ( ) . length ;
712+ } catch ( err ) {
713+ const stringified = JSON . stringify ( obj ) ;
714+ warn (
715+ 'error_encoding_protobufjs_object' ,
716+ `Cannot encode protobuf.js object: ${ stringified } : ${ err } `
717+ ) ;
718+ // We failed to encode the object properly, let's just return an upper boundary of its length.
719+ // It's only needed for calculating the size of the batch, so it's safe if it's bigger than needed.
720+ return stringified . length ;
721+ }
722+ } ;
723+ }
Original file line number Diff line number Diff line change @@ -531,14 +531,8 @@ export class GrpcClient {
531531 * @return {function(Object):number } - a function to compute the byte length
532532 * for an object.
533533 */
534- static createByteLengthFunction ( message : {
535- encode : ( obj : { } ) => {
536- finish : ( ) => Array < { } > ;
537- } ;
538- } ) {
539- return function getByteLength ( obj : { } ) {
540- return message . encode ( obj ) . finish ( ) . length ;
541- } ;
534+ static createByteLengthFunction ( message : typeof protobuf . Message ) {
535+ return gax . createByteLengthFunction ( message ) ;
542536 }
543537}
544538
You can’t perform that action at this time.
0 commit comments