计算Google Firestore文档的大小

时间:2018-03-25 06:30:38

标签: size google-cloud-firestore document calculation

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
    }
}

1 个答案:

答案 0 :(得分:0)

在Android中,如果您要对照最大1 MiB(1,048,576字节)检查文档大小,则可以使用一个库来帮助您:

通过这种方式,您将始终能够保持在限制之下。该库背后的算法是官方文档中关于Storage Size的算法。

相关问题