Skip to content
tuxychandru edited this page Nov 30, 2011 · 2 revisions

#CRUD with Grasshopper and MySQL

This a small app which allows associating programming languages to an execution method and one or more paradigms. The goal is to demonstrate how various features of grasshopper can be used in a typical web application handling CRUD.

##Models

Models are representations of objects in your application's domain. Models contain the domain data and related business logic.

function Language() {
}

Language.prototype.validate = function() {
    this.validateRequired('name', false);
    this.validateRequired('executionId', false);
    this.validateRequired('paradigmIds');
    if(!this.static() && !this.dynamic()) {
        this.addError('typing', 'Select at least one type system.', false);
    }
};

exports.Language = gh.initModel(Language, 'name', 'static',
                                'dynamic', 'executionId', 'paradigmIds');

Language is one of the models in the app which uses the Validation API. All models must to initialized using gh.initModel(). This method takes the constructor of the model and the properties of the model. It creates a method for each property on the model which is used to read and write a field whose name is the property name prefixed with a '_'. For example, name() to read and write _name. The method reads the field if no argument is passed else writes the given value.

##Repositories and Controllers

We use the Repository Pattern for data access. The controllers are similar to the one used in the REST example.

Models are updated in controllers using the update() method of the models. This method can optionally take a converter and callback. The callback is required only if a converter is specified and it is asynchronous.

##Locales and Initialization

We use the following locales configuration to internationalize our error messages.

exports['en-us'] = {
    'required': 'Value is required.',
    'Language.paradigmIds.required': 'Select at least one paradigm.'
};

Finally, the application is initialized.

var gh = require('./grasshopper');

    gh.configure({
        viewsDir: './views',
    layout: 'layout',
    locales: require('./locales')
});

[
    './controllers/home', './controllers/paradigms', './controllers/executions', './controllers/languages'
].forEach(function(controller) {
    require(controller);
});

gh.serve(8080);

Complete Source Code

Clone this wiki locally