Skip to content

Commit 783dcc8

Browse files
authored
feat: add Key.asKey method (#41)
`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.
1 parent 1ab80a7 commit 783dcc8

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

packages/interface-datastore/src/key.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,23 @@ export class Key {
109109
return new Key(nanoid().replace(/-/g, ''))
110110
}
111111

112+
/**
113+
* @param {*} other
114+
*/
115+
static asKey (other) {
116+
if (other instanceof Uint8Array || typeof other === 'string') {
117+
// we can create a key from this
118+
return new Key(other)
119+
}
120+
121+
if (other.uint8Array) {
122+
// this is an older version or may have crossed the esm/cjs boundary
123+
return new Key(other.uint8Array())
124+
}
125+
126+
return null
127+
}
128+
112129
/**
113130
* Cleanup the current key
114131
*

packages/interface-datastore/test/key.spec.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { expect } from 'aegir/utils/chai.js'
44
import { Key } from '../src/key.js'
5+
import { fromString as uint8ArrayFromString } from 'uint8arrays'
56

67
const pathSep = '/'
78

@@ -205,4 +206,37 @@ describe('Key', () => {
205206
// should be a view on the original buffer
206207
expect(buf.buffer).to.equal(arrWithSlashes.buffer)
207208
})
209+
210+
it('should turn a string into a key', () => {
211+
const str = '/foo/bar'
212+
const key = Key.asKey(str)
213+
214+
expect(`${key}`).to.equal(str)
215+
})
216+
217+
it('should turn a key into a key', () => {
218+
const str = '/foo/bar'
219+
const key = Key.asKey(new Key(str))
220+
221+
expect(`${key}`).to.equal(str)
222+
})
223+
224+
it('should turn a uint8array into a key', () => {
225+
const str = '/foo/bar'
226+
const key = Key.asKey(uint8ArrayFromString(str))
227+
228+
expect(`${key}`).to.equal(str)
229+
})
230+
231+
it('should not turn a falsy value into a key', () => {
232+
const key = Key.asKey(false)
233+
234+
expect(key).to.be.null()
235+
})
236+
237+
it('should not turn an invalid value into a key', () => {
238+
expect(Key.asKey({})).to.be.null()
239+
expect(Key.asKey(5)).to.be.null()
240+
expect(Key.asKey(() => {})).to.be.null()
241+
})
208242
})

0 commit comments

Comments
 (0)