OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-social / bridge-envelope / lib / codec.js

67 lines · javascript ref:
import cenc from 'compact-encoding'

// Compact-encoding codec for bridge envelopes
// Fields: type(uint), platform(uint), author(string), content(string),
//         timestamp(uint), channel(string), replyTo(string),
//         mediaUrl(string), mediaType(string), editOf(string),
//         deleteOf(string), id(string)

const envelopeCodec = {
  preencode (state, envelope) {
    cenc.uint.preencode(state, envelope.type)
    cenc.uint.preencode(state, envelope.platform)
    cenc.string.preencode(state, envelope.author)
    cenc.string.preencode(state, envelope.content)
    cenc.uint.preencode(state, envelope.timestamp)
    cenc.string.preencode(state, envelope.channel)
    cenc.string.preencode(state, envelope.replyTo || '')
    cenc.string.preencode(state, envelope.mediaUrl || '')
    cenc.string.preencode(state, envelope.mediaType || '')
    cenc.string.preencode(state, envelope.editOf || '')
    cenc.string.preencode(state, envelope.deleteOf || '')
    cenc.string.preencode(state, envelope.id)
  },

  encode (state, envelope) {
    cenc.uint.encode(state, envelope.type)
    cenc.uint.encode(state, envelope.platform)
    cenc.string.encode(state, envelope.author)
    cenc.string.encode(state, envelope.content)
    cenc.uint.encode(state, envelope.timestamp)
    cenc.string.encode(state, envelope.channel)
    cenc.string.encode(state, envelope.replyTo || '')
    cenc.string.encode(state, envelope.mediaUrl || '')
    cenc.string.encode(state, envelope.mediaType || '')
    cenc.string.encode(state, envelope.editOf || '')
    cenc.string.encode(state, envelope.deleteOf || '')
    cenc.string.encode(state, envelope.id)
  },

  decode (state) {
    return {
      type: cenc.uint.decode(state),
      platform: cenc.uint.decode(state),
      author: cenc.string.decode(state),
      content: cenc.string.decode(state),
      timestamp: cenc.uint.decode(state),
      channel: cenc.string.decode(state),
      replyTo: cenc.string.decode(state),
      mediaUrl: cenc.string.decode(state),
      mediaType: cenc.string.decode(state),
      editOf: cenc.string.decode(state),
      deleteOf: cenc.string.decode(state),
      id: cenc.string.decode(state)
    }
  }
}

function encode (envelope) {
  return cenc.encode(envelopeCodec, envelope)
}

function decode (buf) {
  return cenc.decode(envelopeCodec, buf)
}

export { envelopeCodec, encode, decode }