shelving
Version:
Toolkit for using data in JavaScript.
137 lines (136 loc) • 5.08 kB
JavaScript
import { FieldPath, FieldValue, Firestore } from "@google-cloud/firestore";
import { AsyncProvider } from "../../db/Provider.js";
import { LazyDeferredSequence } from "../../sequence/LazyDeferredSequence.js";
import { getItem } from "../../util/item.js";
import { getObject } from "../../util/object.js";
import { getFilters, getLimit, getOrders } from "../../util/query.js";
import { mapItems } from "../../util/transform.js";
import { getUpdates } from "../../util/update.js";
// Constants.
const ID = FieldPath.documentId();
// Map `Filter.types` to `WhereFilterOp`
const OPERATORS = {
is: "==",
not: "!=",
in: "in",
out: "not-in",
contains: "array-contains",
gt: ">",
gte: ">=",
lt: "<",
lte: "<=",
};
function _getCollection(firestore, c) {
return firestore.collection(c);
}
/** Create a corresponding `QueryReference` from a Query. */
function _getQuery(firestore, c, q) {
let query = _getCollection(firestore, c);
if (q) {
for (const { key, direction } of getOrders(q))
query = query.orderBy(key === "id" ? ID : key, direction);
for (const { key, operator, value } of getFilters(q))
query = query.where(key === "id" ? ID : key, OPERATORS[operator], value);
const l = getLimit(q);
if (typeof l === "number")
query = query.limit(l);
}
return query;
}
function _getItemArray(snapshot) {
return snapshot.docs.map(_getItem);
}
function _getItem(snapshot) {
const data = snapshot.data();
return getItem(snapshot.id, data);
}
function _getOptionalItem(snapshot) {
const data = snapshot.data();
if (data)
return getItem(snapshot.id, data);
}
/** Convert `Update` instances into corresponding Firestore `FieldValue` instances. */
function _getFieldValues(updates) {
return getObject(mapItems(getUpdates(updates), _getFieldValue));
}
function _getFieldValue({ key, action, value }) {
if (action === "set")
return [key, value];
if (action === "sum")
return [key, FieldValue.increment(value)];
if (action === "with")
return [key, FieldValue.arrayUnion(...value)];
if (action === "omit")
return [key, FieldValue.arrayRemove(...value)];
return action; // Never happens.
}
/**
* Firestore server database provider.
* - Works with the Firebase Admin SDK for Node.JS
*/
export class FirestoreServerProvider extends AsyncProvider {
_firestore;
constructor(firestore = new Firestore()) {
super();
this._firestore = firestore;
}
async getItem(c, id) {
return _getOptionalItem(await _getCollection(this._firestore, c).doc(id).get());
}
getItemSequence(c, id) {
const ref = _getCollection(this._firestore, c).doc(id);
return new LazyDeferredSequence(sequence => ref.onSnapshot(snapshot => sequence.resolve(_getOptionalItem(snapshot)), //
//
reason => sequence.reject(reason)));
}
async addItem(c, data) {
return (await _getCollection(this._firestore, c).add(data)).id;
}
async setItem(c, id, data) {
await _getCollection(this._firestore, c).doc(id).set(data);
}
async updateItem(c, id, updates) {
await _getCollection(this._firestore, c).doc(id).update(_getFieldValues(updates));
}
async deleteItem(c, id) {
await _getCollection(this._firestore, c).doc(id).delete();
}
async countQuery(c, q) {
const snapshot = await _getQuery(this._firestore, c, q).count().get();
return snapshot.data().count;
}
async getQuery(c, q) {
return _getItemArray(await _getQuery(this._firestore, c, q).get());
}
getQuerySequence(c, q) {
const ref = _getQuery(this._firestore, c, q);
return new LazyDeferredSequence(sequence => ref.onSnapshot(snapshot => sequence.resolve(_getItemArray(snapshot)), //
//
reason => sequence.reject(reason)));
}
async setQuery(c, q, data) {
return await bulkWrite(this._firestore, c, q, (w, s) => void w.set(s.ref, data));
}
async updateQuery(c, q, updates) {
const fieldValues = _getFieldValues(updates);
return await bulkWrite(this._firestore, c, q, (w, s) => void w.update(s.ref, fieldValues));
}
async deleteQuery(c, q) {
return await bulkWrite(this._firestore, c, q, (w, s) => void w.delete(s.ref));
}
}
/** Perform a bulk update on a set of documents using a `BulkWriter` */
async function bulkWrite(firestore, c, q, callback) {
const writer = firestore.bulkWriter();
const query = _getQuery(firestore, c, q).limit(BATCH_SIZE).select(); // `select()` turs the query into a field mask query (with no field masks) which saves data transfer and memory.
let current = query;
while (current) {
const { docs, size } = await current.get();
for (const s of docs)
callback(writer, s);
current = size >= BATCH_SIZE && query.startAfter(docs.pop()).select();
void writer.flush();
}
await writer.close();
}
const BATCH_SIZE = 1000;