2023-03-12 23:55:12 +01:00
|
|
|
const { DataTypes, Model } = require('sequelize')
|
|
|
|
|
|
|
|
module.exports = (sequelize) => {
|
|
|
|
class PlaylistMediaItem extends Model {
|
|
|
|
getMediaItem(options) {
|
|
|
|
if (!this.mediaItemType) return Promise.resolve(null)
|
2023-03-18 22:56:57 +01:00
|
|
|
const mixinMethodName = `get${this.mediaItemType}`
|
2023-03-12 23:55:12 +01:00
|
|
|
return this[mixinMethodName](options)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
PlaylistMediaItem.init({
|
|
|
|
id: {
|
|
|
|
type: DataTypes.UUID,
|
|
|
|
defaultValue: DataTypes.UUIDV4,
|
|
|
|
primaryKey: true
|
|
|
|
},
|
2023-03-18 22:56:57 +01:00
|
|
|
MediaItemId: DataTypes.UUIDV4,
|
2023-03-12 23:55:12 +01:00
|
|
|
mediaItemType: DataTypes.STRING
|
|
|
|
}, {
|
|
|
|
sequelize,
|
2023-03-18 22:56:57 +01:00
|
|
|
timestamps: true,
|
|
|
|
updatedAt: false,
|
2023-03-12 23:55:12 +01:00
|
|
|
modelName: 'PlaylistMediaItem'
|
|
|
|
})
|
|
|
|
|
|
|
|
const { Book, PodcastEpisode, Playlist } = sequelize.models
|
|
|
|
|
|
|
|
Book.hasMany(PlaylistMediaItem, {
|
2023-03-18 22:56:57 +01:00
|
|
|
foreignKey: 'MediaItemId',
|
2023-03-12 23:55:12 +01:00
|
|
|
constraints: false,
|
|
|
|
scope: {
|
2023-03-18 22:56:57 +01:00
|
|
|
mediaItemType: 'Book'
|
2023-03-12 23:55:12 +01:00
|
|
|
}
|
|
|
|
})
|
2023-03-18 22:56:57 +01:00
|
|
|
PlaylistMediaItem.belongsTo(Book, { foreignKey: 'MediaItemId', constraints: false })
|
2023-03-12 23:55:12 +01:00
|
|
|
|
|
|
|
PodcastEpisode.hasOne(PlaylistMediaItem, {
|
2023-03-18 22:56:57 +01:00
|
|
|
foreignKey: 'MediaItemId',
|
2023-03-12 23:55:12 +01:00
|
|
|
constraints: false,
|
|
|
|
scope: {
|
2023-03-18 22:56:57 +01:00
|
|
|
mediaItemType: 'PodcastEpisode'
|
2023-03-12 23:55:12 +01:00
|
|
|
}
|
|
|
|
})
|
2023-03-18 22:56:57 +01:00
|
|
|
PlaylistMediaItem.belongsTo(PodcastEpisode, { foreignKey: 'MediaItemId', constraints: false })
|
2023-03-12 23:55:12 +01:00
|
|
|
|
|
|
|
PlaylistMediaItem.addHook('afterFind', findResult => {
|
|
|
|
if (!Array.isArray(findResult)) findResult = [findResult]
|
|
|
|
for (const instance of findResult) {
|
2023-03-18 22:56:57 +01:00
|
|
|
if (instance.mediaItemType === 'Book' && instance.Book !== undefined) {
|
2023-03-12 23:55:12 +01:00
|
|
|
instance.MediaItem = instance.Book
|
2023-03-18 22:56:57 +01:00
|
|
|
} else if (instance.mediaItemType === 'PodcastEpisode' && instance.PodcastEpisode !== undefined) {
|
2023-03-12 23:55:12 +01:00
|
|
|
instance.MediaItem = instance.PodcastEpisode
|
|
|
|
}
|
|
|
|
// To prevent mistakes:
|
|
|
|
delete instance.Book
|
|
|
|
delete instance.dataValues.Book
|
|
|
|
delete instance.PodcastEpisode
|
|
|
|
delete instance.dataValues.PodcastEpisode
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
Playlist.hasMany(PlaylistMediaItem)
|
|
|
|
PlaylistMediaItem.belongsTo(Playlist)
|
|
|
|
|
|
|
|
return PlaylistMediaItem
|
|
|
|
}
|