fire-entity
Advanced tools
Comparing version 0.0.1 to 0.1.0
{ | ||
"name": "fire-entity", | ||
"version": "0.0.1", | ||
"version": "0.1.0", | ||
"description": "Allows for storing and retrieving documents in a standardized format from Firestore.", | ||
@@ -5,0 +5,0 @@ "main": "./dist/index.js", |
import * as firebase from 'firebase/app'; | ||
import 'firebase/firestore'; | ||
import { Entity, EntityInsert } from './entity'; | ||
import { convertFirestoreTimestamps } from './util'; | ||
import {Entity, EntityInsert} from './entity'; | ||
import {convertFirestoreTimestamps} from './util'; | ||
@@ -17,8 +17,16 @@ function extractEntity<T extends Entity>(snap: firebase.firestore.QueryDocumentSnapshot): T { | ||
return { ...data, id, type, path, parentPath }; | ||
return {...data, id, type, path, parentPath}; | ||
} | ||
type QueryFn = (ref: firebase.firestore.CollectionReference) => firebase.firestore.Query; | ||
export type EntityInserter = (collectionPath: string, values: {}) => Promise<void>; | ||
export type EntitySelector = (collectionPath: string) => Promise<firebase.firestore.QuerySnapshot>; | ||
export type EntitySelector = (collectionPath: string, queryFn?: QueryFn) => Promise<firebase.firestore.QuerySnapshot>; | ||
export interface QueryParam { | ||
prop: string; | ||
op: firebase.firestore.WhereFilterOp; | ||
val: any; | ||
} | ||
export abstract class EntityStore { | ||
@@ -32,6 +40,6 @@ private _prepareInsert(data: {}): {} { | ||
constructor(private inserter: EntityInserter, private selector: EntitySelector) { } | ||
constructor(private inserter: EntityInserter, private selector: EntitySelector) {} | ||
public insert<T extends EntityInsert>(insert: T): Promise<void> { | ||
const { type, parentPath, ...data } = insert; | ||
const {type, parentPath, ...data} = insert; | ||
const collectionPath = !parentPath ? type : `${parentPath}/${type}`; | ||
@@ -46,2 +54,13 @@ const preparedData = this._prepareInsert(data); | ||
} | ||
public async selectWhere<T extends Entity>(path: string, filters: QueryParam[]): Promise<T[]> { | ||
const snap = await this.selector(path, ref => { | ||
let query: any = ref; | ||
for (const f of filters) { | ||
query = ref.where(f.prop, f.op, f.val); | ||
} | ||
return query; | ||
}); | ||
return snap.docs.map(doc => extractEntity<T>(doc)); | ||
} | ||
} |
@@ -8,2 +8,3 @@ function isFireTimestamp(obj: any): boolean { | ||
} | ||
export function convertFirestoreTimestamps<T>(data: T) { | ||
@@ -10,0 +11,0 @@ for (const key in data) { |
3743
7
94