Skip to content

Instantly share code, notes, and snippets.

@jmont
Created May 4, 2016 21:51
Show Gist options
  • Save jmont/764ea0dbb2dd20c2f3784d491b8096e4 to your computer and use it in GitHub Desktop.
Save jmont/764ea0dbb2dd20c2f3784d491b8096e4 to your computer and use it in GitHub Desktop.
Upserting models using the spread function
// 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.updateMovieWParams(movie, params).spread(this.upsertTagsForMovie).spread(this.updateMovieInfo).spread((movie, params) => movie)
}
updateMovieWParams (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