Skip to content

Commit

Permalink
feat: Ensure storageEngine implements correct interface
Browse files Browse the repository at this point in the history
In order to prevent implementation errors, we want to check that
storageEngine implements the correct methods

This replies to #1483 (comment)
  • Loading branch information
Ldoppea committed Sep 9, 2024
1 parent f6552cd commit 3054dee
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/cozy-pouch-link/src/localStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const LOCALSTORAGE_ADAPTERNAME = 'cozy-client-pouch-link-adaptername'

export class PouchLocalStorage {
constructor(storageEngine) {
checkStorageEngine(storageEngine)
this.storageEngine = storageEngine
}

Expand Down Expand Up @@ -220,3 +221,23 @@ export class PouchLocalStorage {
await this.storageEngine.setItem(LOCALSTORAGE_ADAPTERNAME, adapter)
}
}

/**
* Throw if the given storage engine does not implement the expected Interface
*
* @param {*} storageEngine - Object containing storage access methods
*/
const checkStorageEngine = storageEngine => {
const requiredMethods = ['setItem', 'getItem', 'removeItem']

const missingMethods = requiredMethods.filter(
requiredMethod => !storageEngine[requiredMethod]
)

if (missingMethods.length > 0) {
const missingMethodsString = missingMethods.join(', ')
throw new Error(
`Provided storageEngine is missing the following methods: ${missingMethodsString}`
)
}
}
48 changes: 48 additions & 0 deletions packages/cozy-pouch-link/src/localStorage.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { PouchLocalStorage } from './localStorage'

describe('LocalStorage', () => {
describe('Type assertion', () => {
it('should throw if setItem method is missing', () => {
expect(() => {
new PouchLocalStorage({
getItem: jest.fn(),
removeItem: jest.fn()
})
}).toThrow(
'Provided storageEngine is missing the following methods: setItem'
)
})

it('should throw if getItem method is missing', () => {
expect(() => {
new PouchLocalStorage({
setItem: jest.fn(),
removeItem: jest.fn()
})
}).toThrow(
'Provided storageEngine is missing the following methods: getItem'
)
})

it('should throw if removeItem method is missing', () => {
expect(() => {
new PouchLocalStorage({
getItem: jest.fn(),
setItem: jest.fn()
})
}).toThrow(
'Provided storageEngine is missing the following methods: removeItem'
)
})

it('should throw if multiple methods are missing', () => {
expect(() => {
new PouchLocalStorage({
getItem: jest.fn()
})
}).toThrow(
'Provided storageEngine is missing the following methods: setItem, removeItem'
)
})
})
})

0 comments on commit 3054dee

Please sign in to comment.