WIP : dynamic custom result from wixData.query via backend

Hi all. This is a bit more advanced, but very useful. If you don’t want to get all the columns each time, you can use this. It will only return specified columns. There are two more options to add, but I have no use right now, so didn’t add it yet.

This is a dynamic function you call in e.g. a public file with an amount of parameters:

  1. strCollection => database name

  2. arrColumns => desired columns in an array format

  3. arrFilters => filters, not sure for the format just yet, I think "[{eq: [col, val]},{contains: [col, val]}]

  4. arrSort => sorting, not sure for the format just yet, I think "[{eq: [col, val]},{contains: [col, val]}]
    Then to use it. In a public java file. Naturally you put the function where you need it!!

import {getData} from 'backend/FILE';
...
getData(DATABASE_NAME, [COL_NAME, COL_NAME], "", "")
.then((oData) => {
    console.log(oData)
});
...

In a backend java file

import wixData from 'wix-data';

export function getData(strCollection, arrColumns, arrFilters, arrSort) {
    return wixData.query(strCollection)
        .find()
        .then((resultRows) => {
            let newRows = [];
            
            for (let iCurrent = 0; iCurrent < resultRows.length; iCurrent++) {				
                const curRow = resultRows.items[iCurrent];
                let newRow = {};
                
                for (let iCol = 0; iCol < arrColumns.length; iCol++) {
                    const curProperty = arrColumns[iCol];
                    const curValue = curRow[curProperty]
                    
                    newRow[curProperty] = curValue;
                }
                
                newRows.push(newRow);
            }
            
            return newRows;
        });
}

The result will be like: [{},{}]. You can transform it to use it in repeaters/tables and so on.

Okay, I still need to add in a try catch for those who made a typo in the column or collection name.

1 Like