audiobookshelf/server/models/AudioBookmark.js

70 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-03-12 20:51:45 +01:00
const { DataTypes, Model } = require('sequelize')
/*
* Polymorphic association: https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations/
* Book has many AudioBookmark. PodcastEpisode has many AudioBookmark.
*/
module.exports = (sequelize) => {
class AudioBookmark 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 20:51:45 +01:00
return this[mixinMethodName](options)
}
}
AudioBookmark.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
2023-03-18 22:56:57 +01:00
MediaItemId: DataTypes.UUIDV4,
2023-03-12 20:51:45 +01:00
mediaItemType: DataTypes.STRING,
title: DataTypes.STRING,
time: DataTypes.INTEGER
}, {
sequelize,
modelName: 'AudioBookmark'
})
const { User, Book, PodcastEpisode } = sequelize.models
Book.hasMany(AudioBookmark, {
2023-03-18 22:56:57 +01:00
foreignKey: 'MediaItemId',
2023-03-12 20:51:45 +01:00
constraints: false,
scope: {
2023-03-18 22:56:57 +01:00
mediaItemType: 'Book'
2023-03-12 20:51:45 +01:00
}
})
2023-03-18 22:56:57 +01:00
AudioBookmark.belongsTo(Book, { foreignKey: 'MediaItemId', constraints: false })
2023-03-12 20:51:45 +01:00
PodcastEpisode.hasMany(AudioBookmark, {
2023-03-18 22:56:57 +01:00
foreignKey: 'MediaItemId',
2023-03-12 20:51:45 +01:00
constraints: false,
scope: {
2023-03-18 22:56:57 +01:00
mediaItemType: 'PodcastEpisode'
2023-03-12 20:51:45 +01:00
}
})
2023-03-18 22:56:57 +01:00
AudioBookmark.belongsTo(PodcastEpisode, { foreignKey: 'MediaItemId', constraints: false })
2023-03-12 20:51:45 +01:00
AudioBookmark.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) {
instance.MediaItem = instance.Book
2023-03-18 22:56:57 +01:00
} else if (instance.mediaItemType === 'PodcastEpisode' && instance.PodcastEpisode !== undefined) {
instance.MediaItem = instance.PodcastEpisode
2023-03-12 20:51:45 +01:00
}
// To prevent mistakes:
delete instance.Book
delete instance.dataValues.Book
delete instance.PodcastEpisode
delete instance.dataValues.PodcastEpisode
2023-03-12 20:51:45 +01:00
}
})
User.hasMany(AudioBookmark)
AudioBookmark.belongsTo(User)
return AudioBookmark
}