Save and load notes in Zeichen using an external API.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

59 linhas
1.5 KiB

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