Created
January 12, 2020 06:39
-
-
Save markmssd/43d762000be5241c41c7ac0f3170542a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { IStorageBackend, EmptyStorageModel, StorageOptions } from '@react-native-community/async-storage' | |
import firestore, { FirebaseFirestoreTypes } from '@react-native-firebase/firestore' | |
// UNTESTED | |
// @react-native-community/async-storage | |
class FirestoreSettings<T extends EmptyStorageModel = EmptyStorageModel> implements IStorageBackend<T> { | |
firestore: FirebaseFirestoreTypes.DocumentReference | |
constructor(firestore: FirebaseFirestoreTypes.DocumentReference) { | |
this.firestore = firestore | |
} | |
async getSingle<K extends keyof T>( | |
key: K, | |
opts?: StorageOptions, | |
): Promise<T[K] | null> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.get() | |
.then(snap => snap.get(key)) | |
} | |
async setSingle<K extends keyof T>( | |
key: K, | |
value: T[K], | |
opts?: StorageOptions, | |
): Promise<void> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.update({ [key]: value }) | |
} | |
async getMany<K extends keyof T>( | |
keys: Array<K>, | |
opts?: StorageOptions, | |
): Promise<{ [k in K]: T[k] | null }> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.get() | |
.then((snap) => snap.data() || {}) | |
.then((data) => keys.reduce((acc, k) => ({ ...acc, [k]: data[k] }), [])) | |
} | |
async setMany<K extends keyof T>( | |
values: Array<Partial<{ [k in K]: T[k] }>>, | |
opts?: StorageOptions, | |
): Promise<void> { | |
if (opts) { | |
// noop | |
} | |
const updates = values.reduce((acc: object, kv: object) => ({ ...acc, ...kv }), {}) | |
return this.firestore.update(updates) | |
} | |
async removeSingle(key: keyof T, opts?: StorageOptions): Promise<void> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.update({ [key]: firestore.FieldValue.delete() }) | |
} | |
async removeMany(keys: Array<keyof T>, opts?: StorageOptions): Promise<void> { | |
if (opts) { | |
// noop | |
} | |
const updates = keys.map(k => ({ [k]: firestore.FieldValue.delete() })) | |
return this.firestore.update(updates) | |
} | |
async getKeys(opts?: StorageOptions): Promise<Array<keyof T>> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.get() | |
.then((snap) => Object.keys(snap.data() || {})) | |
} | |
async dropStorage(opts?: StorageOptions): Promise<void> { | |
if (opts) { | |
// noop | |
} | |
return this.firestore.set({}) | |
} | |
} | |
export default FirestoreSettings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment