Skip to content

Instantly share code, notes, and snippets.

@ItsAsbreuk
Last active December 29, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ItsAsbreuk/7699934 to your computer and use it in GitHub Desktop.
Save ItsAsbreuk/7699934 to your computer and use it in GitHub Desktop.
mojitopromises
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('Foo', function(Y, NAME) {
/**
* The Foo module.
*
* @module Foo
*/
/**
* Constructor for the Controller class.
*
* @class Controller
* @constructor
*/
Y.namespace('mojito.controllers')[NAME] = {
/**
* Method corresponding to the 'index' action.
*
* @param ac {Object} The ActionContext that provides access
* to the Mojito API.
*/
index: function(ac) {
var model = ac.models.get('foomodel'),
username = ac.params.getFromBody('username'),
password = ac.params.getFromBody('password');
model.getUserId(username, password).then(
function(response) {
// response.result is an array with objects with property userid
var userid = response.result[0] && response.result[0].userid;
return userid ? model.getOrders(userid) : false;
}
).then(
function(response) {
// response.result is an array with objects of orders - multiple properties including 'orderid'
var orders = response && response.result,
promisebatch, i;
if (orders) {
promisebatch = [];
for (i=0; i<orders.length; i++) {
promisebatch.push(getOrderDetails(orders[i].orderid));
}
return Y.batch.apply(Y, promisebatch);
}
}
).then(
function(response) {
ac.done({
status: 'OK',
data: response || {}
});
}
).then(
null,
Y.bind(ac.error, ac)
);
}
};
}, '0.0.1', {requires: ['mojito', 'mojito-assets-addon', 'mojito-models-addon', 'mojito-params-addon']});
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('FooModel', function(Y, NAME) {
/**
* The FooModel module.
*
* @module Foo
*/
var dbConnection = new Y.DatabaseConnection({
database: 'foodb',
user: 'foousername',
password: 'foopassword'
});
/**
* Constructor for the FooModel class.
*
* @class FooModel
* @constructor
*/
Y.namespace('mojito.models')[NAME] = {
init: function(config) {
this.config = config;
},
getUserId: function(username, password) {
return dbConnection.queryPromise('select userid from users where (username=?) && (password=?)', [username, password]);
},
getOrders: function(userid) {
return dbConnection.queryPromise('select * from orders where userid=?', userid);
},
getOrderDetails: function(orderid) {
return dbConnection.queryPromise('select * from orderdetails where orderid=?', orderid);
}
};
}, '0.0.1', {requires: ['promise']});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment