Search code examples
loopbackjsstrongloop

How to access loopback models without instantiating the server/app


I want to code a script for creating some Users and link them to some other resources.

Checking loopback docs they told you to instantiate the app/server in order to acomplish it. https://docs.strongloop.com/display/public/LB/Working+with+LoopBack+objects#WorkingwithLoopBackobjects-Fromacustomscript

But this method implies to get the app runing, a side effect which I'd like to avoid.

Any thoughts of how to access just the models but not the entire app?


Solution

  • What we used for running the script without getting the web server initiated is a "work-arround" suggested in the loopback examples at github.

    By adding this in your app.js...

    // start the server if `$ node server.js`
    if (require.main === module) {
      app.start();
    }
    

    ...you get the app to start only if is directly called, not if it is required.

    So with var app = require('../app'); in our script we can fully access the app.models without running anything unnecessary.