jakejs / jake

JavaScript build tool, similar to Make or Rake. Built to work with Node.js.
http://jakejs.com
Apache License 2.0
1.97k stars 190 forks source link

Using model in jake file #238

Closed cometbalan closed 10 years ago

cometbalan commented 10 years ago

I have been started to use 'jake' for creating tasks in compoundjs project. I can able to run some sample task, but when i try to use Models within the jake tasks, it shows like


User model is not defined.

But this model is accessible throughout all the controllers, but not in the jake file.

My jake file is under

/jake/invite-jakefile.js

Note : I am using Mongodb as database and used database.json to configure database.

Please suggest a solution.

mde commented 10 years ago

I'm not particularly familiar with CompoundJS, but I imagine it has an application environment that has to load before you can use things like your models in Jake tasks.

Jake is used extensively in the Geddy MVC framework, and has an app-environment initialization step that makes it easy to run tasks in the context of your app (just by running geddy jake myTask), and have access to the models like you're describing. I could definitely give you more help if you were using Geddy instead of Compound.

The only other suggestion I might have would be to ask the Compound guys if they've exposed some sort of API for loading the app environment so you can use it without an HTTP server.

nholdren commented 10 years ago

I came across this same problem several times first using Kue and now using Jake. However, I don't use CompoundJS, but rather sails.js. If it helps take a look at https://github.com/ragulka/sails-starter-app where they have a custom bootstrap that allows the models to be loaded without actually starting the server instance. I was able to apply this same method for Jake albeit it is running sails.js.

mde commented 10 years ago

@nholdren, thanks for the info!

cometbalan commented 10 years ago

I found the solution....

We need to initialize the app in a jake file and use the compound instance available when the app is ready.

namespace('friend_request_state', function () {

  desc('Task to generate General invite code');
  task('add_states', function (general_ic) {

    console.log("Adding Friend Request States");

        //my jake file is under project_directory/jake/test.js
    require('../../')().compound.on('ready', function(compound){
        model_ops(compound)     
    });

  });

});

function model_ops(compound){

    var MyModel = compound.models.FriendRequestState;

    var states = [{ state : "new" }, { state : "viewed" }, { state : "approved" }, { state : "rejected" }, { state : "requested" }];

    MyModel.create(states, function(err){
        if(err) console.log(err);
        process.exit(0);
    });

}