Skip to content

Instantly share code, notes, and snippets.

@kcarlson
Last active February 19, 2024 17:28
Show Gist options
  • Select an option

  • Save kcarlson/0e69fbce5bff8ca2670af83db346df19 to your computer and use it in GitHub Desktop.

Select an option

Save kcarlson/0e69fbce5bff8ca2670af83db346df19 to your computer and use it in GitHub Desktop.
Convert json to protobuf message in browser
const isEmptyObject = obj =>
typeof obj === "object" &&
Object.keys(obj).length === 0 &&
obj.constructor === Object;
const createProxy = msg => {
if (!msg || typeof msg !== "object") {
return msg;
}
if (Array.isArray(msg)) {
return msg.map(createProxy);
}
return new Proxy(msg, {
get: function (target, prop) {
const fieldUpper = prop.replace(/get|List/g, "");
const fieldName = `${fieldUpper[0].toLowerCase()}${fieldUpper.substring(1)}`;
const value = target[fieldName];
return () =>
value === null || isEmptyObject(value)
? null
: createProxy(value);
}
});
}
export const protoMsgFromJson = (protoObject, ProtoClass) =>
protoMsgFromObject(JSON.parse(protoObject), ProtoClass);
/**
* Serialize protobuf message fromObject
*
* @param {any} protoObject
* @param {typeof require('google-protobuf').Message} ProtoClass
* @see https://github.com/sglim/protobuf-js-from-object for inspiration
* @returns {typeof require('google-protobuf').Message} ProtoClass instance
*/
export const protoMsgFromObject = (protoObject, ProtoClass) => {
if (jspb === undefined) {
throw new Error("Please include google-protobuf.js");
}
const writer = new jspb.BinaryWriter();
ProtoClass.serializeBinaryToWriter(createProxy(protoObject), writer);
return ProtoClass.deserializeBinary(writer.getResultBuffer());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment