|
| 1 | +// eslint-disable-next-line no-unused-vars |
| 2 | +import { firestore } from 'firebase'; |
| 3 | + |
| 4 | +import firebase from 'firebase.js'; |
| 5 | + |
| 6 | +const getFirestoreRef = (path) => firebase.firestore().collection(path); |
| 7 | + |
| 8 | +export const fetchDocument = async (collection, id) => { |
| 9 | + const document = await getFirestoreRef(collection).doc(id).get(); |
| 10 | + if (!document.exists) { |
| 11 | + return null; |
| 12 | + } |
| 13 | + |
| 14 | + return { id: document.id, ...document.data() }; |
| 15 | +}; |
| 16 | + |
| 17 | +export const fetchCollection = async (collection, options = {}) => { |
| 18 | + const data = []; |
| 19 | + let baseQuery = getFirestoreRef(collection); |
| 20 | + |
| 21 | + if (options.queries) { |
| 22 | + const { queries } = options; |
| 23 | + queries.forEach(({ attribute, operator, value }) => { |
| 24 | + baseQuery = baseQuery.where(attribute, operator, value); |
| 25 | + }); |
| 26 | + } |
| 27 | + |
| 28 | + if (options.sort) { |
| 29 | + const { attribute, order } = options.sort; |
| 30 | + baseQuery = baseQuery.orderBy(attribute, order); |
| 31 | + } |
| 32 | + (await baseQuery.get()).forEach((doc) => |
| 33 | + data.push({ id: doc.id, ...doc.data() }) |
| 34 | + ); |
| 35 | + |
| 36 | + return data; |
| 37 | +}; |
| 38 | + |
| 39 | +export const deleteDocument = (collection, id) => { |
| 40 | + return getFirestoreRef(collection).doc(id).delete(); |
| 41 | +}; |
| 42 | + |
| 43 | +export const createDocument = (collection, id, values) => { |
| 44 | + return getFirestoreRef(collection).doc(id).set(values); |
| 45 | +}; |
| 46 | + |
| 47 | +export const modifyDocument = (collection, id, values) => { |
| 48 | + return getFirestoreRef(collection).doc(id).update(values); |
| 49 | +}; |
0 commit comments