-
Notifications
You must be signed in to change notification settings - Fork 248
/
test.solution-counters.js
84 lines (71 loc) · 2.52 KB
/
test.solution-counters.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import firebase from 'firebase/app';
import 'firebase/firestore';
var db;
// [START create_counter]
function createCounter(ref, num_shards) {
var batch = db.batch();
// Initialize the counter document
batch.set(ref, { num_shards: num_shards });
// Initialize each shard with count=0
for (let i = 0; i < num_shards; i++) {
const shardRef = ref.collection('shards').doc(i.toString());
batch.set(shardRef, { count: 0 });
}
// Commit the write batch
return batch.commit();
}
// [END create_counter]
// [START increment_counter]
function incrementCounter(ref, num_shards) {
// Select a shard of the counter at random
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = ref.collection('shards').doc(shard_id);
// Update count
return shard_ref.update("count", firebase.firestore.FieldValue.increment(1));
}
// [END increment_counter]
// [START get_count]
function getCount(ref) {
// Sum the count of each shard in the subcollection
return ref.collection('shards').get().then((snapshot) => {
let total_count = 0;
snapshot.forEach((doc) => {
total_count += doc.data().count;
});
return total_count;
});
}
// [END get_count]
describe("firestore-solution-counters", () => {
before(() => {
var config = {
apiKey: "AIzaSyArvVh6VSdXicubcvIyuB-GZs8ua0m0DTI",
authDomain: "firestorequickstarts.firebaseapp.com",
projectId: "firestorequickstarts",
};
var app = firebase.initializeApp(config, "solution-counters");
db = firebase.firestore(app);
});
describe("solution-counters", () => {
it("should create a counter", () => {
// Create a counter with 10 shards
return createCounter(db.collection('counters').doc(), 10);
});
it("should increment a counter", () => {
// Create a counter, then increment it
const ref = db.collection('counters').doc();
return createCounter(ref, 10).then(() => {
return incrementCounter(ref, 10);
});
});
it("should get the count of a counter", () => {
// Create a counter, increment it, then get the count
const ref = db.collection('counters').doc();
return createCounter(ref, 10).then(() => {
return incrementCounter(ref, 10);
}).then(() => {
return getCount(ref);
});
});
});
});