Wednesday, August 31, 2011

Javascript CAML Where clause OR Builder

It is pretty rare that I run into an occasion where I get to use recursive functions and it is always great. This case is pretty limited, but is perfectly suited for JavaScript. Essentially, I needed to be able to tell if a series of files existed in a SharePoint document library because of an old process where data in the database may contain file names which were not in the SharePoint document library. The root cause of this issue is in the file loading and the database loading processes, however changing these are out of scope.

If the list of possible file names is known we can build a query and have SharePoint return the files that exist. In this case I don't need a reusable function, so I decided that I would take the chance and use an area of JavaScript that I almost never get to utilize: self-referencing anonymous functions or recursive anonymous functions. Below is my implementation, it writes the result of the function to the FireBug/IE Developer Toolbar console.

NOTE: Below there is an issue with the syntax highlighter functionality. If you copy and paste the test below, you must change the "" + field + "" to '" + field + "' and the Type="Text" to Type='Text'
Hopefully there will be a fix to the rendering functionality, but until then, there we are.
files = ["file3.pdf", "file1.pdf", "file2.pdf"];
ors = (function buildOR(field, filelist) {
    var BuildEq = function (field, value) { return "" + value + ""; }
    return (filelist.length == 1) ? BuildEq(field, filelist.shift()) : "" + BuildEq(field, filelist.shift()) + buildOR(field, filelist) + "";
})("FileLeafRef", files)

console.log(ors);
//buildOR("FileLeafRef", files);
Running the example with line 8 uncommented, causes the browser to throw an error. This occurs because the "buildOR" function is an anonymous function. The name "buildOR" is only available inside the function.

Running this example produces the following output (I have formatted it for readability). Note: The FieldRef nodes are self closing, the syntax highlighter appears does not handle these correctly, so I have changed the self closing nodes to accommodate the limitation.

    
        
            
            file3.pdf
        
        
            
                
                file1.pdf
            
            
                
                file2.pdf
            
        
    

No comments: