Skip to content

Instantly share code, notes, and snippets.

@jmont
Last active May 6, 2016 18:41
Show Gist options
  • Save jmont/114b14b5237556526be43581abb5fbd1 to your computer and use it in GitHub Desktop.
Save jmont/114b14b5237556526be43581abb5fbd1 to your computer and use it in GitHub Desktop.
Upserting using the spread function and Sequelize
// The spread function!
Promise.resolve([thing1, thing2, thing3]).spread((thing1, thing2, thing3) => { /* Do something! */ })
// Upserting a sample Movie model
import Models from 'db/models/index'
updateMovie (movie, params) {
return this.updateMovieObject(movie, params).spread(this.upsertTagsForMovie).spread(this.updateMovieInfo).spread((movie, params) => movie)
}
updateMovieObject (movie, params) {
const newValues = {
title: params.title,
image_url: params.image_url
}
return movie.update(newValues).then((movie) => [movie, params])
}
upsertTagsForMovie (movie, params) {
const tags = params.tags ? params.tags : []
const addTags = tags.map((t) => {
return Models.Tag.findOrCreate({ where: { tag: t } }).spread((actualTag, trash) => { return actualTag })
})
return Promise.all(addTags).then((syncedTags) => {
movie.setTags(syncedTags)
for (const i in syncedTags) {
syncedTags[i].addMovie(movie)
}
return [movie, params]
})
}
updateMovieInfo (movie, params) {
return Models.MovieInfo.findOrCreate({ where: { movieId: movie.id }}).spread((info, trash) => {
return info.update({
director: params.director,
runtime: params.runtime,
genre: params.genre,
summary: params.summary,
}).then((info) => {
return [movie, params]
})
})
}
addMovie (params) {
const newValues = {
title: params.title,
image_url: params.image_url,
}
Models.Movie.create(newValues).then((movie) => { return [movie, params] }).spread(this.upsertTagsForMovie).spread(this.updateMovieInfo).spread((movie, params) => movie)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment