From 783dcc866e4ca6784d2801a8e18fa1135a137a6b Mon Sep 17 00:00:00 2001 From: Alex Potsides Date: Fri, 17 Sep 2021 16:27:13 +0200 Subject: [PATCH] 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. --- packages/interface-datastore/src/key.js | 17 ++++++++++ packages/interface-datastore/test/key.spec.js | 34 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/packages/interface-datastore/src/key.js b/packages/interface-datastore/src/key.js index cae03f42..fdb41f7e 100644 --- a/packages/interface-datastore/src/key.js +++ b/packages/interface-datastore/src/key.js @@ -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 * diff --git a/packages/interface-datastore/test/key.spec.js b/packages/interface-datastore/test/key.spec.js index 1a30250b..8ef5018f 100644 --- a/packages/interface-datastore/test/key.spec.js +++ b/packages/interface-datastore/test/key.spec.js @@ -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 = '/' @@ -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() + }) })