Search code examples
jsonloopbackjsstrongloop

LoopBack JSON Return Inconsistency


We're using LoopBack for our REST APIs. We've noticed an inconsistency in the return JSON from REST endpoints. We can code around, but it would be better to know how to resolve it properly in our code. The issue is that when the standard REST endpoint returns JSON there is no JSON object ID. However, when we return JSON from a query that we execute directly we must specify an object ID. Here's the JSON that's returned from the standard LoopBack REST 'get' call:

enter image description here

When we return our own JSON it appears that it must have an ID:

enter image description here

Here's how we're returning our own JSON (TypeScript):

    var sql: string = "SELECT * FROM as_trialbalancelist"

    // Execute the SQL
    dbConn.query(sql, function (error: number, rows: any, fields: any) {

        // Check for errors 
        if (error) {
            console.log('ERROR: ' + error);
            // TODO: Need better error return.
            // res.send(error);
            return;
        }

        callback(null, rows);

    });

Dataview.remoteMethod(
    'trialbalance',
    {
        returns: { arg: 'data' },
        http: { verb: 'get' }
    }

    );

When we remove the "returns: { arg: 'data' }" it causes an error. A blank 'arg' causes problems as well.


Solution

  • You should be able to use this for your returns property instead:

    returns: {type: 'object', root: true},
    

    Basically says the type will be object, and it will be the root meaning no id required. Not sure if you would need to use type: 'array' in your case since you're returning an array, I haven't had to return an array from a custom remote method yet.