Browse Source

refactor: Create song as a job

Owen Diffey 3 years ago
parent
commit
7526e08ba2
2 changed files with 36 additions and 8 deletions
  1. 4 8
      backend/logic/actions/songs.js
  2. 32 0
      backend/logic/songs.js

+ 4 - 8
backend/logic/actions/songs.js

@@ -452,24 +452,20 @@ export default {
 		async.waterfall(
 			[
 				next => {
-					const song = new SongsModule.SongModel(newSong);
-					song.save({ validateBeforeSave: true }, err => {
-						if (err) return next(err, song);
-						return next(null, song);
-					});
+					SongsModule.runJob("CREATE_SONG", { song: newSong }, this)
+						.then(song => next(null, song))
+						.catch(next);
 				}
 			],
 			async (err, song) => {
 				if (err) {
 					err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
 
-					this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(song)}". "${err}"`);
+					this.log("ERROR", "SONGS_CREATE", `Failed to create song "${JSON.stringify(newSong)}". "${err}"`);
 
 					return cb({ status: "error", message: err });
 				}
 
-				SongsModule.runJob("UPDATE_SONG", { songId: song._id });
-
 				this.log("SUCCESS", "SONGS_CREATE", `Successfully created song "${song._id}".`);
 
 				return cb({

+ 32 - 0
backend/logic/songs.js

@@ -284,6 +284,38 @@ class _SongsModule extends CoreClass {
 		});
 	}
 
+	/**
+	 * Create song
+	 *
+	 * @param {object} payload - an object containing the payload
+	 * @param {string} payload.song - the song object
+	 * @returns {Promise} - returns a promise (resolve, reject)
+	 */
+	CREATE_SONG(payload) {
+		return new Promise((resolve, reject) => {
+			async.waterfall(
+				[
+					next => {
+						const song = new SongsModule.SongModel(payload.song);
+						song.save({ validateBeforeSave: true }, err => {
+							if (err) return next(err, song);
+							return next(null, song);
+						});
+					},
+
+					(song, next) => {
+						SongsModule.runJob("UPDATE_SONG", { songId: song._id });
+						return next(null, song);
+					}
+				],
+				(err, song) => {
+					if (err && err !== true) return reject(new Error(err));
+					return resolve({ song });
+				}
+			);
+		});
+	}
+
 	/**
 	 * Gets a song from id from Mongo and updates the cache with it
 	 *