【发布时间】:2018-09-03 12:24:23
【问题描述】:
Firestore 文档详细说明了如何手动计算文档的存储大小,但在任何文档引用、快照或元数据中似乎都没有为此提供函数。
在我尝试使用自己的计算之前,有没有人知道官方或非官方的函数?
这是我对 https://firebase.google.com/docs/firestore/storage-size 文档的解释中对此类功能的第一次(完全未经测试)剪辑
function calcFirestoreDocSize(collectionName, docId, docObject) {
let docNameSize = encodedLength(collectionName) + 1 + 16
let docIdType = typeof(docId)
if(docIdType === 'string') {
docNameSize += encodedLength(docId) + 1
} else {
docNameSize += 8
}
let docSize = docNameSize + calcObjSize(docObject)
return docSize
}
function encodedLength(str) {
var len = str.length;
for (let i = str.length - 1; i >= 0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) {
len++;
} else if (code > 0x7ff && code <= 0xffff) {
len += 2;
} if (code >= 0xDC00 && code <= 0xDFFF) {
i--;
}
}
return len;
}
function calcObjSize(obj) {
let key;
let size = 0;
let type = typeof obj;
if(!obj) {
return 1
} else if(type === 'number') {
return 8
} else if(type === 'string') {
return encodedLength(obj) + 1
} else if(type === 'boolean') {
return 1
} else if (obj instanceof Date) {
return 8
} else if(obj instanceof Array) {
for(let i = 0; i < obj.length; i++) {
size += calcObjSize(obj[i])
}
return size
} else if(type === 'object') {
for(key of Object.keys(obj)) {
size += encodedLength(key) + 1
size += calcObjSize(obj[key])
}
return size += 32
}
}
【问题讨论】:
-
你有没有找到解决方案,或者测试你自己的实现?
-
我使用您链接的文档中的 Google 示例数据(任务 ID:5730082031140864)尝试了您的实施。预期大小为 131 字节,您的实现给出了 230 字节。对于我的目的来说,这实际上已经足够接近了,我只是想确保我没有接近极限。所以谢谢你!
-
我刚刚对照当前示例检查了这一点,它几乎是完美的。它只是关闭,因为您不需要第一行中的 +1(文档名称只需要额外的 +16 与字符串不同)...谢谢!!
标签: size google-cloud-firestore document calculation