Save and load notes in Zeichen using the browser's local storage.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

57 строки
1.5 KiB

  1. import { Plugin, StoragePlugin, } from '../../core/src/plugin'
  2. import Storage from './Storage'
  3. type PluginConfig = {
  4. idAttribute?: string,
  5. }
  6. const AVAILABLE_COLLECTIONS = ['notes', 'folders'] as const
  7. const localStorageFactory: Plugin<PluginConfig> = ({
  8. idAttribute = 'id',
  9. } = {}) => class LocalStorage implements StoragePlugin {
  10. private readonly storageMap: Record<string, Storage>
  11. public static readonly type: 'storage'
  12. constructor({ currentUserId, }) {
  13. this.storageMap = AVAILABLE_COLLECTIONS.reduce(
  14. (theStorages, collectionId) => ({
  15. ...theStorages,
  16. [collectionId]: new Storage(currentUserId, collectionId)
  17. }),
  18. {}
  19. )
  20. }
  21. async save(collectionId, item) {
  22. const { [collectionId]: storage = null } = this.storageMap
  23. if (storage === null) {
  24. throw new Error(`Invalid collection "${collectionId}"`)
  25. }
  26. return storage.saveItem(item)
  27. }
  28. async load(collectionId, itemId) {
  29. const { [collectionId]: storage = null } = this.storageMap
  30. if (storage === null) {
  31. throw new Error(`Invalid collection "${collectionId}"`)
  32. }
  33. const items = await storage.queryItems()
  34. if (!itemId) {
  35. return items
  36. }
  37. return items.filter(i => i[idAttribute] === itemId)
  38. }
  39. async remove(collectionId, item) {
  40. const { [collectionId]: storage = null } = this.storageMap
  41. if (storage === null) {
  42. throw new Error(`Invalid collection "${collectionId}"`)
  43. }
  44. return storage.deleteItem(item)
  45. }
  46. }
  47. export default localStorageFactory