File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
packages/interface-datastore Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -109,6 +109,23 @@ export class Key {
109
109
return new Key ( nanoid ( ) . replace ( / - / g, '' ) )
110
110
}
111
111
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
+
112
129
/**
113
130
* Cleanup the current key
114
131
*
Original file line number Diff line number Diff line change 2
2
3
3
import { expect } from 'aegir/utils/chai.js'
4
4
import { Key } from '../src/key.js'
5
+ import { fromString as uint8ArrayFromString } from 'uint8arrays'
5
6
6
7
const pathSep = '/'
7
8
@@ -205,4 +206,37 @@ describe('Key', () => {
205
206
// should be a view on the original buffer
206
207
expect ( buf . buffer ) . to . equal ( arrWithSlashes . buffer )
207
208
} )
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
+ } )
208
242
} )
You can’t perform that action at this time.
0 commit comments