扩展firebase.database.Reference

时间:2016-06-14 22:49:10

标签: firebase

在旧FB中我添加了一个辅助函数来获取/设置值,如下所示:

DECLARE @PersonId INT= 401;

WITH CTE AS
(
SELECT 
    t.*,
    c.CategoryId AS CategoryId_c,
    c.ParentCategoryId as ParentCategoryId_c,
    c.Name AS Name_c,
    c1.CategoryId AS CategoryId_c2,
    c1.ParentCategoryId AS ParentCategoryId_c2,
    c1.Name AS Name_c2,
    c2.CategoryId as CategoryId_c3,
    c2.ParentCategoryId AS ParentCategoryId_c3,
    c2.Name AS Name_c3
FROM 
PersonTimeSlotAssignment p
INNER JOIN TimeSlot t ON t.TimeSlotId=p.TimeSlotId
INNER JOIN Category c ON t.CategoryId=c.CategoryId
LEFT JOIN Category c1 ON c1.CategoryId=c.ParentCategoryId
LEFT JOIN Category c2 ON c2.CategoryId=c1.ParentCategoryId
WHERE p.PersonId=@PersonId
)

SELECT * FROM (
    SELECT TimeSlotId,Name_c  FROM CTE 
    UNION
    SELECT TimeSlotId,Name_c2 FROM CTE 
    UNION
    SELECT TimeSlotId,Name_c3 FROM CTE 
)a WHERE Name_c IS NOT NULL

然后我可以做例如返回ref.child(...)。val();

此功能不在V3中运行。

如何在V3中以这种方式扩展firebase?

THX!

1 个答案:

答案 0 :(得分:0)

这是解决方案 - 我觉得这个扩展非常方便

    // val() -> get(), resolve with value at ref, fails with error.code
    // val(value) -> set(value), resolve with value, fails with error.code
    // val(vals) -> update(vals), resolve with vals, fails with error.code

    firebase.database.Reference.prototype.val = function(vals) {
        let path=this.toString().substring(firebase.database().ref().toString().length-1);
        let valsAsString = (typeof vals==='string' ? vals : JSON.stringify(vals));

        if (!vals) {
            return this.once('value').then(
                snapshot => {
                    if (typeof snapshot.val() === 'undefined' || snapshot.val() === null) {
                        console.log('val('+path+') failed (null) ! '+error.message+' ('+error.code+')');
                        throw 'INVALID_VALUE';
                    }
                    return snapshot.val();  }, 
                error => {
                    console.log('val('+path+') failed ! '+error.message+' ('+error.code+')');
                    throw error.code;
                });
        }   

        let singleVal=(vals.constructor != Object); // is singleVal then vals is a single value

        if (singleVal ) return this.set(vals).then(  // set single value
            () => {
                return vals;
            }, error => {
                console.log('val('+path+','+valsAsString+') failed ! '+error.message+' ('+error.code+')');
                throw error.code;
            }
        );

        return this.update(vals).then( // update multiple values
            () => {
                return vals;
            }, error => {
                console.log('val('+path+','+valsAsString+') failed ! '+error.message+' ('+error.code+')');
                throw error.code;
            }
        );  
    };
}