简体   繁体   中英

Display One-to-Many result in a JSON with nodejs

Hello I have this model: Gateways -serial -name -ip

Devices -uui -vendor -name -gw_serial

Where a Gateway has 1 or many devices

I need to show a result like this in my rest/api in nodejs with SQLITE3:

{
serial: 123,
name: Huawei,
ip: 192.168.12.1,
devices:[
{
 uuid: 888,
 vendor: Intel,
 name: mouse,  
},

{
 uuid: 999,
 vendor: Intel,
 name: keyboard,  
}

],
serial: 345,
name: Apple,
ip: 192.168.12.3,
devices:[
{
 uuid: 567,
 vendor: Intel,
 name: mouse,  
},

{
 uuid: 893,
 vendor: Intel,
 name: keyboard,  
}

]
}

I presume you are using node-sqlite3 . I haven't tested it with real database, but here I did some kind of mocking and demo of the function.

Perhaps this is what you need:

const get_grouped = async (db) => {
    return new Promise((resolve, reject) => {
        const sql = `
        SELECT serial,
               gateways.name AS gw_name,
               uuid,
               vendor,
               devices.name
        FROM   gateways
               JOIN devices
                 ON gateways.serial = gw_serial
        `;
        const acc = {};
        db.each(sql, (error, gw_dev) => {
            if(error) return reject(error);
            acc[gw_dev.serial] = acc[gw_dev.serial] || {
                serial: gw_dev.serial,
                name: gw_dev.gw_name,
                ip: gw_dev.ip,
                devices: []
            };
            acc[gw_dev.serial].devices.push({
                uuid: gw_dev.uuid,
                vendor: gw_dev.vendor,
                name: gw_dev.name,
            });
        }, (error, rows) => error ? reject(error) : resolve(Object.values(acc)));
    });
};

Basically you pass the database instance to this function.

On every row the result is stored in the acc variable. If there is no gateway with that serial it is initialized. Then the device is just pushed to it's collection. Of course this assumes that the serial is unique per gateway but it should be.

When the oncomplete callback is called if there are no errors the result is presented as the values of the acc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM