Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
})
})