Skip to content

Commit

Permalink
feat: backport Key.asKey (#42)
Browse files Browse the repository at this point in the history
Backports #41 to previous release.
  • Loading branch information
achingbrain committed Sep 17, 2021
1 parent f5d59e8 commit 4932a7d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/interface-datastore/src/key.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,23 @@ class Key {
return new Key(nanoid().replace(/-/g, ''))
}

/**
* @param {*} other
*/
static asKey (other) {
if (other instanceof Uint8Array || typeof other === 'string') {
// we can create a key from this
return new Key(other)
}

if (other.uint8Array) {
// this is an older version or may have crossed the esm/cjs boundary
return new Key(other.uint8Array())
}

return null
}

/**
* Cleanup the current key
*
Expand Down
34 changes: 34 additions & 0 deletions packages/interface-datastore/test/key.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

const { expect } = require('aegir/utils/chai')
const Key = require('../src').Key
const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')

const pathSep = '/'

Expand Down Expand Up @@ -206,4 +207,37 @@ describe('Key', () => {
// should be a view on the original buffer
expect(buf.buffer).to.equal(arrWithSlashes.buffer)
})

it('should turn a string into a key', () => {
const str = '/foo/bar'
const key = Key.asKey(str)

expect(`${key}`).to.equal(str)
})

it('should turn a key into a key', () => {
const str = '/foo/bar'
const key = Key.asKey(new Key(str))

expect(`${key}`).to.equal(str)
})

it('should turn a uint8array into a key', () => {
const str = '/foo/bar'
const key = Key.asKey(uint8ArrayFromString(str))

expect(`${key}`).to.equal(str)
})

it('should not turn a falsy value into a key', () => {
const key = Key.asKey(false)

expect(key).to.be.null()
})

it('should not turn an invalid value into a key', () => {
expect(Key.asKey({})).to.be.null()
expect(Key.asKey(5)).to.be.null()
expect(Key.asKey(() => {})).to.be.null()
})
})

0 comments on commit 4932a7d

Please sign in to comment.