Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Key.asKey method #41

Merged
merged 1 commit into from
Sep 17, 2021
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()
})
})