Search code examples
node.jsapiexpressloopbackjs

How to change loopback API response to a particular format


I am new to loopback I want to change every response from my loopback remote method API to a particular format

eg: if success

{
    status:1,
    data:{},
    message:"Success"
}

If error

{
    status:0,
    data:{},
    message:"Something went wrong"
}

Solution

  • You should create a boot script to change all remote method responses :

    Create hook.js or any other name in /server/boot/

    module.exports = function (app) {
    var remotes = app.remotes();
    // modify all returned values
    remotes.after('**', function (ctx, next) {
        if (ctx) {
            ctx.result = {
                status: 1,
                data: ctx.result,
                message: "Success"
            };
        } else {
            var err = new Error();
            next({
                status: 0,
                data: err,
                message: "Something went wrong"
            });
        }
        next();
    });
    

    };

    Check these links for more information :

    Formatting remote method responses (Last Section)

    https://loopback.io/doc/en/lb3/Remote-methods.html

    Hooks

    https://loopback.io/doc/en/lb3/Strong-Remoting.html