瀏覽代碼

Implement storage logic

Use storage functions in implementations.
master
Allan Crisostomo 3 年之前
父節點
當前提交
75124f7921
共有 2 個檔案被更改,包括 52 行新增9 行删除
  1. +1
    -1
      src/Storage.ts
  2. +51
    -8
      src/index.ts

+ 1
- 1
src/Storage.ts 查看文件

@@ -1,7 +1,7 @@
import Storage, { Collection, OutOfSyncError } from '../../core/src/storage' import Storage, { Collection, OutOfSyncError } from '../../core/src/storage'
import Engine from './Engine' import Engine from './Engine'


export default class LocalStorage<T> implements Storage<T> {
export default class LocalStorage<T = unknown> implements Storage<T> {
private readonly engine: Engine<Collection<T>> private readonly engine: Engine<Collection<T>>


constructor( constructor(


+ 51
- 8
src/index.ts 查看文件

@@ -1,13 +1,56 @@
import { Plugin } from '../../core/src/plugin'
import { Plugin, StoragePlugin, } from '../../core/src/plugin'
import Storage from './Storage' import Storage from './Storage'


type PluginConfig = {}
type PluginConfig = {
idAttribute?: string,
}

const AVAILABLE_COLLECTIONS = ['notes', 'folders'] as const

const localStorageFactory: Plugin<PluginConfig> = ({
idAttribute = 'id',
} = {}) => class LocalStorage implements StoragePlugin {
private readonly storageMap: Record<string, Storage>

public static readonly type: 'storage'

constructor({ currentUserId, }) {
this.storageMap = AVAILABLE_COLLECTIONS.reduce(
(theStorages, collectionId) => ({
...theStorages,
[collectionId]: new Storage(currentUserId, collectionId)
}),
{}
)
}

async save(collectionId, item) {
const { [collectionId]: storage = null } = this.storageMap
if (storage === null) {
throw new Error(`Invalid collection "${collectionId}"`)
}
return storage.saveItem(item)
}

async load(collectionId, itemId) {
const { [collectionId]: storage = null } = this.storageMap
if (storage === null) {
throw new Error(`Invalid collection "${collectionId}"`)
}
const items = await storage.queryItems()
if (!itemId) {
return items
}
return items.filter(i => i[idAttribute] === itemId)
}


const LocalStoragePlugin: Plugin<PluginConfig> = config => ({
currentUserId,
}) => {
new Storage(currentUserId, 'notes')
new Storage(currentUserId, 'folders')
async remove(collectionId, item) {
const { [collectionId]: storage = null } = this.storageMap
if (storage === null) {
throw new Error(`Invalid collection "${collectionId}"`)
}
return storage.deleteItem(item)
}
} }


export default LocalStoragePlugin
export default localStorageFactory

Loading…
取消
儲存