-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
80 lines (69 loc) · 1.71 KB
/
index.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
'use strict'
const assert = require('assert').strict
const Firestore = require('@google-cloud/firestore')
class KeyvFirestore {
constructor (options) {
// Required by @keyv/test-suite…
this.opts = options
const {
projectId,
credentials,
collection
} = options
assert.equal(typeof collection, 'string')
this._store = new Firestore({ projectId, credentials })
this._collection = this._store.collection(collection)
}
_col () {
return this._collection.doc(this.namespace).collection(this.namespace)
}
_doc (key) {
const prefix = `${this.namespace}:`
return this._col().doc(key.slice(prefix.length))
}
get (key) {
return this._doc(key).get().then((doc) => {
if (doc.exists) {
return doc.get('value')
}
return undefined
})
}
set (key, value, ttl) {
return this._doc(key).set({ value })
}
delete (key) {
return this._doc(key).get().then((doc) => {
if (doc.exists) {
return this._doc(key).delete()
.then(() => true)
}
return false
})
}
_deleteBatch (query) {
return query.get().then((snapshot) => {
if (snapshot.size === 0) return true
const batch = this._store.batch()
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref)
})
return batch.commit().then(() => false)
})
}
clear () {
return new Promise((resolve, reject) => {
function next () {
this._deleteBatch(this._col().limit(100)).then((finished) => {
if (finished) {
resolve()
} else {
next.call(this)
}
}).catch(reject)
}
next.call(this)
})
}
}
module.exports = KeyvFirestore