Readable TypeScript debug() Output for Protobuf Messages

For search engine indexing and for understanding: Protobuf is frequently used with GRPC. Protobuf is how the requests and responses are serialized.

The Problem

Look at the output below. Printing protobuf messages using debug(‘%j’) produces unreadable output (the first one below).

$ DEBUG=myapp npx ts-node tojson.ts 

  myapp My object without toJSON {"wrappers_":null,"arrayIndexOffset_":-1,"array":[null,null,null,null,null,"Session name 01"],"pivot_":1.7976931348623157e+308,"convertedPrimitiveFields_":{}} +0ms

  myapp My object with toJSON {"id":"","CENSORED4":"","CENSORED3":"","version":"","name":"Session name 01","CENSORED1":"","status":0,"CENSORED2":""} +1ms

Solution

Here is all you need to make it work. SessionResponse below is a sample message (export class SessionResponse extends jspb.Message in another file, after import * as jspb from "google-protobuf";)

// --- Setup ---
import {Message} from "google-protobuf";

import {
    SessionResponse
} from "./PATH/TO/YOUR_GENERATED_PROTOBUF_FILE_pb";

import debug0 from 'debug';
const debug = debug0('myapp');

const req = new SessionResponse().setName("Session name 01");

// --- Test before ---
debug('My object without toJSON %j', req)

// --- Add this to your code --- start ---

declare module "google-protobuf" {
    interface Message {
        toJSON(): any;
    }
}
Message.prototype.toJSON = function () {
    return this.toObject();
}

// --- Add this to your code --- end ---

// --- Test after ---
debug('My object with toJSON %j', req)

Hope this helps. Let me know if you have questions.

Leave a comment