-
Notifications
You must be signed in to change notification settings - Fork 4
Adding a custom Groovy file
Mogwai allows you to optionally define Gremlin scripts in a separate .groovy file bound to a Schema. This has the following advantages:
- better caching of your Gremlin code on the server, which should result in better performance
- avoid potential Gremlin/SQL-like injection issues, because of parameters binding
- syntax highlighting in your favorite editor.
To attach Groovy methods to your model, simply create a .groovy file with the same name as your schema file and put both files in the same folder (ie user.groovy and user.js should be in the same folder). Mogwai will automatically detect the path of your model file, check for an eventual .groovy file and load its content if found.
All functions defined in that .groovy file will be loaded and automatically attached to the model as static methods. These methods can then be called asynchronously in JavaScript directly in your model.
For example, suppose the following user.groovy file:
def findUserByName(name) {
g.V('$type', 'user').has('name', name)
}Mogwai will automatically add a findUserByName static method to your Model class, allowing the name parameter to be passed.
You'll then be able to call the following anywhere in your code, without having to define anything in the Schema:
Users.findUserByName("gulthor", function(err, user) {
// Handle response
})This feature supports passing parameters as of v0.2.1. Note that passing a callback is optional (see the Query section below and the distinction between execute() and query()).
As of v0.2.2, you can also override a Groovy function in your Schema should you wish to add more JavaScript behavior when calling this function. The overriden groovy function will be accessible from the model.scripts object:
For example, suppose the groovy def findUserByName(name) function defined above; you can override it in your Schema and stil access its content with the following code:
user.js Schema file:
// Override .groovy findUserByName method
UserSchema.statics.findUserByName = function(name, callback) {
// Do more JavaScript stuff here...
console.log("Hey, I'm overriding a Groovy method!");
// Finally, call the groovy function
this.scripts.findUserByName(name, function(err, foo) {
return callback(err, foo);
});
};Note: make sure you do not forget to pass over the parameters to the Groovy method (ie. the name parameter here).
Defining custom Groovy functions directly in the Schema's .groovy file is considered a best practice in Mogwai, and it is strongly encouraged to do so.