Skip to content

Commit

Permalink
feat: add Key.asKey method (#41)
Browse files Browse the repository at this point in the history
`instanceOf` is unreliable across EJS/CSM but also across different bundles loaded in the browser.

Add a `Key.asKey` method we can use as a more reliable `instanceOf` check.
  • Loading branch information
achingbrain committed Sep 17, 2021
1 parent 1ab80a7 commit 783dcc8
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 @@ -109,6 +109,23 @@ export 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 @@ -2,6 +2,7 @@

import { expect } from 'aegir/utils/chai.js'
import { Key } from '../src/key.js'
import { fromString as uint8ArrayFromString } from 'uint8arrays'

const pathSep = '/'

Expand Down Expand Up @@ -205,4 +206,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 783dcc8

Please sign in to comment.