Effective clean way to initialize Sequelize as an object

Sequelize is an ORM for Node.js that I have decided to use in a project. I, like most of my fellow programmers, generally like cleaner code and in this case I found a pretty damn good way to initialize it and keep the initializing functions separate from rest of the code. Further, I structured it so that it was very easy to use it as well.

[crayon lang=”JavaScript”]
var db = {
Notes: sequelize.define(‘Notes’, {
text: Sequelize.STRING,
title: Sequelize.STRING,
description: Sequelize.TEXT,
width: Sequelize.FLOAT,
height: Sequelize.FLOAT,
offsetLeft: Sequelize.FLOAT,
offsetTop: Sequelize.FLOAT,
zIndex: Sequelize.INTEGER
}),
Boards: sequelize.define(‘Boards’, {
title: Sequelize.STRING,
description: Sequelize.TEXT,
created: Sequelize.DATE
}),
init: function(){
//init this bitch
this.Boards.hasMany(this.Notes);
this.Boards.sync();
this.Notes.sync();
}
};

[/crayon]

To use this code you would simply do something like:
[crayon lang=”JavaScript”]

//this is async, so save will fail initially.
//ideally we would try to fire a callback instead of trying to do this synchronously.

//But it demonstrates the idea, anyhow.
db.init();
var board = db.Boards.build({
title: “title”,
description: “description”,
created: new Date()
});

board.save();

[/crayon]

This is how you use that, this is a bit complicated because it’s from an actual application:
[crayon lang=”JavaScript”]
try{
var board = db.Boards.build({
path: _boardName,
title: “title”,
description: “description”,
created: new Date()
});
board.save();

}catch(error){
console.log(error.text);
}
[/crayon]
[crayon lang=”JavaScript”]
db.Boards.find({where: {path: _boardName}}).success(function(board){
//board.build();
board.getNotes().success(
function(notes){
dbresults = new Array();

for(n=0; n < notes.length; n++){ //console.log(notes[0]); var fields = {}; for(i=0; i < notes[n].attributes.length; i++){ key = notes[n].attributes[i]; value = notes[n][key]; fields[key] = value; } dbresults.push(fields); } //res.send(dbresults); res.contentType('json'); //res.contentType('application/javascript'); callback = req.query.callback; res.send(callback + '(' + JSON.stringify(dbresults) + ');'); } ); }); [/crayon] [/raw]

Comments (1)

  1. Sami K. (reply)

    October 5, 2012 at 5:24 am

    I updated the existing entry with some more example code about how you might try using this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Published on: 6 March 2012
Posted by: Sami K.
Discussion: 1 Comment
Tags: , ,