Skip to content

Commit 2a4fe91

Browse files
committed
feat: Ensure storageEngine implements correct interface
In order to prevent implementation errors, we want to check that storageEngine implements the correct methods This replies to #1483 (comment)
1 parent 927ffa1 commit 2a4fe91

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

packages/cozy-pouch-link/src/localStorage.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export const LOCALSTORAGE_ADAPTERNAME = 'cozy-client-pouch-link-adaptername'
99

1010
export class PouchLocalStorage {
1111
constructor(storageEngine) {
12+
checkStorageEngine(storageEngine)
1213
this.storageEngine = storageEngine
1314
}
1415

@@ -220,3 +221,23 @@ export class PouchLocalStorage {
220221
await this.storageEngine.setItem(LOCALSTORAGE_ADAPTERNAME, adapter)
221222
}
222223
}
224+
225+
/**
226+
* Throw if the given storage engine does not implement the expected Interface
227+
*
228+
* @param {*} storageEngine - Object containing storage access methods
229+
*/
230+
const checkStorageEngine = storageEngine => {
231+
const requiredMethods = ['setItem', 'getItem', 'removeItem']
232+
233+
const missingMethods = requiredMethods.filter(
234+
requiredMethod => !storageEngine[requiredMethod]
235+
)
236+
237+
if (missingMethods.length > 0) {
238+
const missingMethodsString = missingMethods.join(', ')
239+
throw new Error(
240+
`Provided storageEngine is missing the following methods: ${missingMethodsString}`
241+
)
242+
}
243+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { PouchLocalStorage } from './localStorage'
2+
3+
describe('LocalStorage', () => {
4+
describe('Type assertion', () => {
5+
it('should throw if setItem method is missing', () => {
6+
expect(() => {
7+
new PouchLocalStorage({
8+
getItem: jest.fn(),
9+
removeItem: jest.fn()
10+
})
11+
}).toThrow(
12+
'Provided storageEngine is missing the following methods: setItem'
13+
)
14+
})
15+
16+
it('should throw if getItem method is missing', () => {
17+
expect(() => {
18+
new PouchLocalStorage({
19+
setItem: jest.fn(),
20+
removeItem: jest.fn()
21+
})
22+
}).toThrow(
23+
'Provided storageEngine is missing the following methods: getItem'
24+
)
25+
})
26+
27+
it('should throw if removeItem method is missing', () => {
28+
expect(() => {
29+
new PouchLocalStorage({
30+
getItem: jest.fn(),
31+
setItem: jest.fn()
32+
})
33+
}).toThrow(
34+
'Provided storageEngine is missing the following methods: removeItem'
35+
)
36+
})
37+
38+
it('should throw if multiple methods are missing', () => {
39+
expect(() => {
40+
new PouchLocalStorage({
41+
getItem: jest.fn()
42+
})
43+
}).toThrow(
44+
'Provided storageEngine is missing the following methods: setItem, removeItem'
45+
)
46+
})
47+
})
48+
})

0 commit comments

Comments
 (0)