Skip to content

Instantly share code, notes, and snippets.

@sdepold
Created March 21, 2012 16:31
Show Gist options
  • Save sdepold/2149328 to your computer and use it in GitHub Desktop.
Save sdepold/2149328 to your computer and use it in GitHub Desktop.
a very basic shop system with sequelize
const Sequelize = require("sequelize")
////////////////////
// database setup //
////////////////////
var sequelize = new Sequelize('master-thesis', 'root', null, {
logging: false
})
////////////
// models //
////////////
var User = sequelize.define('User', {
username: Sequelize.STRING
}, {
instanceMethods: {
publishProduct: function(attributes, callback) {
var self = this
Product.create(attributes).success(function(product) {
product.setUser(self).success(function() {
callback(product)
})
})
},
addToCart: function(product, callback) {
var self = this
this.getCart().success(function(cart) {
if(cart) {
cart.addProduct(product).success(callback)
} else {
Cart.create().success(function(cart) {
cart.setUser(self).success(function() {
cart.addProduct(product).success(function() {
callback(cart)
})
})
})
}
})
}
}
})
var Product = sequelize.define('Product', {
title: Sequelize.STRING
})
var Cart = sequelize.define('Cart', {
currentValue: Sequelize.FLOAT
})
//////////////////
// associations //
//////////////////
User.hasMany(Product).hasOne(Cart)
Cart.belongsTo(User).hasMany(Product)
Product.belongsTo(User).hasMany(Cart)
///////////
// logic //
///////////
sequelize.sync({ force: true }).success(function() {
User.create({ username: 'sdepold' }).success(function(sdepold) {
User.create({ username: 'john doe' }).success(function(johnDoe) {
sdepold.publishProduct({ title: 'ein produkt' }, function(product) {
johnDoe.addToCart(product, function(cart) {
cart.getProducts().success(function(cartItems) {
console.log(cartItems.map(function(item){ return item.values }))
})
})
})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment