Skip to content

Create a CID from a string or Uint8Array or CID-like object #92

@achingbrain

Description

@achingbrain

This module has a number of ways of converting things into CID instances - CID.parse for strings, CID.decode for Uint8Arrays, CID.asCID for things CID-shaped.

.parse and .decode will throw, .asCID will not. We generally want to validate what we've been passed as a CID, so a common pattern seems to be forming as:

function toCID (hash) {
  if (typeof hash === 'string') {
    return CID.parse(hash)
  } else if (hash instanceof Uint8Array) {
    return CID.decode(hash)
  }

  const cid = CID.asCID(hash)
  
  if (!cid) {
    throw new Error('Invalid CID')
  }

  return cid
}

If this seems familiar it may be because this is quite similar to how the constructor from the js-cids class behaves.

It is quite useful though, any objections to making this a utility method on the CID class?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions