Convert google.protobuf.Timestamp to ISO format in Fabric 1.4 in NodeJS

Viewed 1363

I am running a Hyperledger Fabric 1.4 chaincode and try to retrieve the history of a key with getHistoryForKey stub method. I am iterating over each entry and want to convert them for standardization in all my chaincode functions.

Now, I can handle all keys in the iterator, except the timestamp which is a google.protobuf.Timestamp. Any tries of mine fail to convert it to an ISO datetime string.

Code

// Entry method to retrieve the full history of any asset
async (stub, args) => {
  const idToSearch = args.id
  const historyIterator = await stub.getHistoryForKey(idToSearch)
  let historyData = []
  await iterate(historyData, historyIterator)
  if (historyData.length === 0) throw errors.ASSET_NOT_FOUND(idToSearch)
  return historyData
}

// I use node v8 and thus cannopt use for await to iterator and must write recursive helper func
const iterate = async (historyData, historyIterator) => {
    const element = await historyIterator.next()
    if (!element) return historyIterator.close()
    const {value} = element
    if (!value) return historyIterator.close()

    historyData.push({
        value: value.value.toString('utf8'),
        isDeleted: value.is_delete,
        txId: value.tx_id,
        timestamp: value.timestamp // <-- WANT TO CONVERT TO ISO DATE TIME STRING
    })
    await iterate(historyData, historyIterator)
}

My Approaches

1. toISOString()

Regarding the documentation of the protobuf of timestamp it says "In JavaScript, one can convert a Date object to this format using the standard toISOString()". This does not work, since I get "toISOString is not a function".

2. new Date()

Further, I tried to run new Date(protobufTimestamp), which results in "Invalid Date".

3. Using the seconds

I though maybe I can utilize the seconds which are on of two keys (Object.keys(protobufTimestamp) => [seconds, nanos]) in the timestamp to create the Date. But that date object also says "Invalid Date". That could be explained since I read that Protobuf Timestamp covers the ranges from year 0 to 9999. So, maybe the conversion fails.

Question

Can someone explain me how to convert the google protobuf timestamp to an ISO timestamp in Fabric 1.4 in NodeJS?

0 Answers
Related