in firestore/solution-sharded-timestamp/shardedTimestamps.js [90:136]
function createQuery(fieldName, fieldOperator, fieldValue, limit = 5) {
// For each shard value, map it to a new query which adds an additional
// where clause specifying the shard value.
return Promise.all(shardChunks().map(shardChunk => {
return fs.collection('instruments')
.where('shard', 'in', shardChunk) // new shard condition
.where(fieldName, fieldOperator, fieldValue)
.orderBy('timestamp', 'desc')
.limit(limit)
.get();
}))
// Now that we have a promise of multiple possible query results, we need
// to merge the results from all of the queries into a single result set.
.then((snapshots) => {
// Create a new container for 'all' results
const docs = [];
snapshots.forEach((querySnapshot) => {
querySnapshot.forEach((doc) => {
// append each document to the new all container
docs.push(doc);
});
});
if (snapshots.length === 1) {
// if only a single query was returned skip manual sorting as it is
// taken care of by the backend.
return docs;
} else {
// When multiple query results are returned we need to sort the
// results after they have been concatenated.
//
// since we're wanting the `limit` newest values, sort the array
// descending and take the first `limit` values. By returning negated
// values we can easily get a descending value.
docs.sort((a, b) => {
const aT = a.data().timestamp;
const bT = b.data().timestamp;
const secondsDiff = aT.seconds - bT.seconds;
if (secondsDiff === 0) {
return -(aT.nanoseconds - bT.nanoseconds);
} else {
return -secondsDiff;
}
});
return docs.slice(0, limit);
}
});
}