implemented hooks for user-collections & user-collection-entry models to update updatedAt and order fields
This commit is contained in:
1 parent
36866dabe6
commit
cea1b207a3
12 files changed
+168
-59
No files matched your search
@@ -103,17 +103,3 @@ EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' });
|
|||||||
// * ----
|
// * ----
|
||||||
Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
|
Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
|
||||||
Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
|
Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
|
||||||
|
|
||||||
|
|
||||||
// ! TRIGGERS
|
|
||||||
UserCollectionEntry.afterUpdate(async (instance, options) => {
|
|
||||||
await UserCollection.update(instance.user_collection_id, {
|
|
||||||
updatedAt: new Date()
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
UserCollectionEntry.afterDestroy(async (instance, options) => {
|
|
||||||
await UserCollection.update(instance.user_collection_id, {
|
|
||||||
updatedAt: new Date()
|
|
||||||
})
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// Import models
|
||||||
|
const Franchise = require('../models/Franchise');
|
||||||
|
const Entry = require('../models/Entry')
|
||||||
|
const EntryId = require('../models/EntryId')
|
||||||
|
const EntryRating = require('../models/EntryRating')
|
||||||
|
const EntrySeen = require('../models/EntrySeen');
|
||||||
|
const UserCollection = require('../models/UserCollection');
|
||||||
|
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
||||||
|
const Season = require('../models/Season');
|
||||||
|
const Episode = require('../models/Episode');
|
||||||
|
const EpisodeSeen = require('../models/EpisodeSeen');
|
||||||
|
const Genre = require('../models/Genre');
|
||||||
|
const EntryGenre = require('../models/EntryGenre');
|
||||||
|
const sequelize = require('./database');
|
||||||
|
|
||||||
|
// ! Hooks
|
||||||
|
// ? user collections
|
||||||
|
// * entry add
|
||||||
|
UserCollectionEntry.afterCreate(async (instance, options) => {
|
||||||
|
try {
|
||||||
|
const userCollections = await UserCollection.findByPk(instance.user_collection_id);
|
||||||
|
|
||||||
|
const userCollectionEntriesCount = await UserCollectionEntry.count({
|
||||||
|
where: {
|
||||||
|
user_collection_id: instance.user_collection_id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// ? updating the order
|
||||||
|
await instance.update({
|
||||||
|
order: userCollectionEntriesCount
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
// ? mimicking a change to trigger updatedAt property update
|
||||||
|
await userCollections.update({
|
||||||
|
name: sequelize.literal('name')
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`Sequelize Hook Error: UserCollectionEntry.afterCreate: `, error)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// * entry update (order)
|
||||||
|
UserCollectionEntry.afterUpdate(async (instance, options) => {
|
||||||
|
try {
|
||||||
|
const userCollections = await UserCollection.findByPk(instance.user_collection_id);
|
||||||
|
|
||||||
|
// ? mimicking a change to trigger updatedAt property update
|
||||||
|
await userCollections.update({
|
||||||
|
name: sequelize.literal('name')
|
||||||
|
})
|
||||||
|
|
||||||
|
// TODO reorder entries
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`Sequelize Hook Error: UserCollectionEntry.afterUpdate: `, error)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// * entry remove
|
||||||
|
UserCollectionEntry.afterDestroy(async (instance, options) => {
|
||||||
|
try {
|
||||||
|
const userCollection = await UserCollection.findByPk(instance.user_collection_id);
|
||||||
|
const entry = await Entry.findByPk(instance.entry_id);
|
||||||
|
|
||||||
|
if (!entry || !userCollection) return;
|
||||||
|
|
||||||
|
// ? mimicking a change to trigger updatedAt property update
|
||||||
|
let updates = {
|
||||||
|
name: sequelize.literal('name')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ? updating collection poster
|
||||||
|
const collectionsEntries = await UserCollectionEntry.findAll({
|
||||||
|
where: {
|
||||||
|
user_collection_id: instance.user_collection_id
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{ model: Entry, as: 'entry' },
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
// ? remove the poster if the collection is empty now
|
||||||
|
if (collectionsEntries.length == 0) {
|
||||||
|
updates.poster = null;
|
||||||
|
} else {
|
||||||
|
// todo add is customPoster field
|
||||||
|
if (userCollection.poster_path == entry.poster_path) {
|
||||||
|
updates.poster_path = collectionsEntries[0].entry.poster_path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ? updating order, only if the removed entry isn't placed at the end
|
||||||
|
let order = instance.order;
|
||||||
|
if (instance.order != collectionsEntries.length) {
|
||||||
|
for (let i = 0; i < collectionsEntries.length; i++) {
|
||||||
|
if (collectionsEntries[i].order > instance.order) {
|
||||||
|
collectionsEntries[i].update({ order: order })
|
||||||
|
order++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ? updating the collection updatedAt and poster maybe
|
||||||
|
await userCollection.update(updates)
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`Sequelize Hook Error: UserCollectionEntry.afterDestroy: `, error)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ? entry-seen
|
||||||
|
// * entry-seen create
|
||||||
|
EntrySeen.afterCreate(async (isntance, options) => {
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
// * entry-seen udpate
|
||||||
|
EntrySeen.afterUpdate(async (isntance, options) => {
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
// * entry-seen delete
|
||||||
|
EntrySeen.afterDestroy(async (isntance, options) => {
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
// ? episode seen
|
||||||
@@ -4,6 +4,7 @@ const UserCollectionEntry = require('../models/UserCollectionEntry');
|
|||||||
const Entry = require('../models/Entry');
|
const Entry = require('../models/Entry');
|
||||||
const EntryId = require('../models/EntryId');
|
const EntryId = require('../models/EntryId');
|
||||||
const EntryRating = require('../models/EntryRating');
|
const EntryRating = require('../models/EntryRating');
|
||||||
|
const { Sequelize } = require('sequelize');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// ! /user-collections
|
// ! /user-collections
|
||||||
@@ -40,30 +41,26 @@ router.get('/:id', async (req, res) => {
|
|||||||
const userCollection = await UserCollection.findByPk(req.params.id, {
|
const userCollection = await UserCollection.findByPk(req.params.id, {
|
||||||
include: [{
|
include: [{
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entries', // Make sure this matches your alias in the association, if any
|
as: 'entries',
|
||||||
through: {
|
|
||||||
attributes: [], // Exclude attributes from the join model, if you don't need them
|
|
||||||
},
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (userCollection) {
|
|
||||||
// Optionally, sort the entries here if needed, using JavaScript's sort()
|
|
||||||
// This is a workaround for the direct ordering limitation via Sequelize in many-to-many relationships
|
|
||||||
for (let i = 0; i < userCollection.entries.length; i++) {
|
|
||||||
userCollection.entries[i] = await Entry.findByPk(userCollection.entries[i].id,
|
|
||||||
{
|
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: 'entryId' },
|
||||||
{ model: EntryRating, as: 'entryRating' }
|
{ model: EntryRating, as: 'entryRating' }
|
||||||
]
|
],
|
||||||
})
|
through: {
|
||||||
}
|
model: UserCollectionEntry,
|
||||||
|
attributes: ['order'], // attributes (to include) from the join model
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||||
|
});
|
||||||
|
|
||||||
|
if (userCollection) {
|
||||||
res.status(200).json(userCollection);
|
res.status(200).json(userCollection);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'UserCollection not found' });
|
res.status(404).json({ message: 'UserCollection not found' });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.log(`Error getting collection info: `, error)
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -104,12 +101,10 @@ router.delete('/:id', async (req, res) => {
|
|||||||
router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userCollectionId, entryId } = req.params;
|
const { userCollectionId, entryId } = req.params;
|
||||||
const { order } = req.body;
|
|
||||||
|
|
||||||
const newUserCollectionEntry = await UserCollectionEntry.create({
|
const newUserCollectionEntry = await UserCollectionEntry.create({
|
||||||
user_collection_id: userCollectionId,
|
user_collection_id: userCollectionId,
|
||||||
entry_id: entryId,
|
entry_id: entryId
|
||||||
order: order || 0
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? set a default poster if none exists
|
// ? set a default poster if none exists
|
||||||
@@ -122,6 +117,7 @@ router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|||||||
|
|
||||||
res.status(201).json(newUserCollectionEntry);
|
res.status(201).json(newUserCollectionEntry);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.log(error)
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -157,12 +153,15 @@ router.patch('/:userCollectionId/entries/:entryId/order', async (req, res) => {
|
|||||||
router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userCollectionId, entryId } = req.params;
|
const { userCollectionId, entryId } = req.params;
|
||||||
const deleted = await UserCollectionEntry.destroy({
|
const deleted = await UserCollectionEntry.findOne({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: userCollectionId,
|
user_collection_id: userCollectionId,
|
||||||
entry_id: entryId
|
entry_id: entryId
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
console.log(`deleteing : `, deleted)
|
||||||
|
|
||||||
|
const deletedCount = deleted.destroy();
|
||||||
|
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
|
|||||||
+2
-1
@@ -30,6 +30,7 @@ app.use('/api/v1', routes);
|
|||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
const relations = require('./db/relations.js');
|
const relations = require('./db/relations.js');
|
||||||
|
const sequelizeHooks = require('./db/sequelizeHooks.js');
|
||||||
const { initializeGenres, initializeData } = require('./db/dataInitializer.js');
|
const { initializeGenres, initializeData } = require('./db/dataInitializer.js');
|
||||||
|
|
||||||
sequelize
|
sequelize
|
||||||
@@ -45,6 +46,6 @@ sequelize
|
|||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
console.log("error: ____________")
|
console.log("____________SEQUELIZE SYNC ERROR____________")
|
||||||
console.log(err)
|
console.log(err)
|
||||||
});
|
});
|
||||||
@@ -46,12 +46,11 @@ export class UserCollectionService {
|
|||||||
// Add an entry to a list
|
// Add an entry to a list
|
||||||
addEntryToCollection(
|
addEntryToCollection(
|
||||||
userCollectionId: number,
|
userCollectionId: number,
|
||||||
entryId: number,
|
entryId: number
|
||||||
order: number
|
|
||||||
): Observable<UserCollectionEntry> {
|
): Observable<UserCollectionEntry> {
|
||||||
return this.http.post<UserCollectionEntry>(
|
return this.http.post<UserCollectionEntry>(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`,
|
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`,
|
||||||
{ order: order }
|
{}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<img class="card-img" [src]="getPostPath()" alt="Movie Poster">
|
<img class="card-img" [src]="getPostPath()" alt="Movie Poster">
|
||||||
|
|
||||||
<div class="card-overlay" (click)="cardClick()">
|
<div class="card-overlay">
|
||||||
<div class="rating">
|
<div class="rating">
|
||||||
<i class='bx bx-star'></i>
|
<i class='bx bx-star'></i>
|
||||||
<span>{{formattedRate}}</span>
|
<span>{{formattedRate}}</span>
|
||||||
|
|||||||
+1
-1
@@ -98,7 +98,7 @@ export class UserCollectionGridCardComponent {
|
|||||||
// ? EVENTS
|
// ? EVENTS
|
||||||
cardClick() {
|
cardClick() {
|
||||||
if (this.entry.isInLibrary)
|
if (this.entry.isInLibrary)
|
||||||
this.router.navigate([`/entry/${this.entry.id}`]);
|
this.router.navigate([`/entries/${this.entry.id}`]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? EVENT EMITTER
|
// ? EVENT EMITTER
|
||||||
|
|||||||
+7
-11
@@ -2,8 +2,8 @@ import { Component, OnInit } from '@angular/core';
|
|||||||
import { ActivatedRoute } from '@angular/router';
|
import { ActivatedRoute } from '@angular/router';
|
||||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
||||||
import { UserCollection } from '../../../../shared/models/userCollection.model';
|
import { UserCollection } from '../../../../shared/models/userCollection.model';
|
||||||
import { Entry } from '../../../../shared/models/entry.model';
|
|
||||||
import { DatePipe } from '@angular/common';
|
import { DatePipe } from '@angular/common';
|
||||||
|
import { CollectionEntry } from '../../../../shared/models/dtos/collection-entry.dto';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-userCollection-info-page',
|
selector: 'app-userCollection-info-page',
|
||||||
@@ -28,20 +28,15 @@ export class UserCollectionInfoPageComponent implements OnInit{
|
|||||||
|
|
||||||
this.listService.getCollection(id.toString()).subscribe(
|
this.listService.getCollection(id.toString()).subscribe(
|
||||||
(data) => {
|
(data) => {
|
||||||
// Handle the successful reception of data.
|
|
||||||
this.list = data as unknown as UserCollection;
|
this.list = data as unknown as UserCollection;
|
||||||
this.list.entries = this.list.entries as Entry[];
|
this.list.entries = this.list.entries as CollectionEntry[];
|
||||||
|
|
||||||
this.createdAt = this.getCreatedDate()?.toString() || '';
|
this.createdAt = this.getCreatedDate()?.toString() || '';
|
||||||
this.updatedAt = this.getUpdatedAt()?.toString() || '';
|
this.updatedAt = this.getUpdatedAt()?.toString() || '';
|
||||||
console.log('Data received:', this.list);
|
console.log(`Collection "${this.list.name}" received:`, this.list);
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
// Handle any error that occurs during the subscription
|
|
||||||
console.error('Error occurred:', error);
|
console.error('Error occurred:', error);
|
||||||
},
|
|
||||||
() => {
|
|
||||||
// Handle completion of the Observable
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -54,6 +49,7 @@ export class UserCollectionInfoPageComponent implements OnInit{
|
|||||||
return this.datePipe.transform(this.list.createdAt, 'dd MMMM, yyyy');
|
return this.datePipe.transform(this.list.createdAt, 'dd MMMM, yyyy');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO use a relativeDate pipe
|
||||||
getUpdatedAt() {
|
getUpdatedAt() {
|
||||||
const updatedAt = this.list.updatedAt;
|
const updatedAt = this.list.updatedAt;
|
||||||
// First, check if updatedAt is a valid date string or timestamp
|
// First, check if updatedAt is a valid date string or timestamp
|
||||||
@@ -77,14 +73,14 @@ export class UserCollectionInfoPageComponent implements OnInit{
|
|||||||
const diffInHours = diffInMs / (1000 * 60 * 60);
|
const diffInHours = diffInMs / (1000 * 60 * 60);
|
||||||
if (diffInHours < 1) {
|
if (diffInHours < 1) {
|
||||||
const diffInMinutes = diffInMs / (1000 * 60);
|
const diffInMinutes = diffInMs / (1000 * 60);
|
||||||
if(diffInMinutes >= 2) isPlural = 's'
|
if (diffInMinutes >= 2) isPlural = 's';
|
||||||
return `${Math.floor(diffInMinutes)} minute${isPlural} ago`;
|
return `${Math.floor(diffInMinutes)} minute${isPlural} ago`;
|
||||||
}
|
}
|
||||||
if(diffInHours >= 2) isPlural = 's'
|
if (diffInHours >= 2) isPlural = 's';
|
||||||
return `${Math.floor(diffInHours)} hour${isPlural} ago`;
|
return `${Math.floor(diffInHours)} hour${isPlural} ago`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(diffInDays >= 2) isPlural = 's'
|
if (diffInDays >= 2) isPlural = 's';
|
||||||
return `${Math.floor(diffInDays)} day${isPlural} ago`;
|
return `${Math.floor(diffInDays)} day${isPlural} ago`;
|
||||||
} else {
|
} else {
|
||||||
// More than a week, show formatted date
|
// More than a week, show formatted date
|
||||||
|
|||||||
+1
-1
@@ -43,7 +43,7 @@ export class UserCollectionsListItemComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
redirectTo(): void {
|
redirectTo(): void {
|
||||||
this.router.navigate([`/user-collections/${this.list.id}`]);
|
this.router.navigate([`/collections/${this.list.id}`]);
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteList() {
|
deleteList() {
|
||||||
|
|||||||
+1
-5
@@ -124,11 +124,7 @@ export class UserCollectionsModalComponent implements OnInit {
|
|||||||
`Adding Entry ${this.entryId} to list: ${userCollection.name}`
|
`Adding Entry ${this.entryId} to list: ${userCollection.name}`
|
||||||
);
|
);
|
||||||
this.listService
|
this.listService
|
||||||
.addEntryToCollection(
|
.addEntryToCollection(userCollection.id, this.entryId)
|
||||||
userCollection.id,
|
|
||||||
this.entryId,
|
|
||||||
userCollection.userCollectionEntries.length + 1
|
|
||||||
)
|
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (response) => {
|
next: (response) => {
|
||||||
console.log('Successfuly added Entry To Collection:', response);
|
console.log('Successfuly added Entry To Collection:', response);
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { Entry } from '../entry.model';
|
||||||
|
|
||||||
|
export interface CollectionEntry extends Entry {
|
||||||
|
order: number;
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Entry } from './entry.model';
|
import { CollectionEntry } from './dtos/collection-entry.dto';
|
||||||
import { UserCollectionEntry } from './userCollectionEntry.model';
|
import { UserCollectionEntry } from './userCollectionEntry.model';
|
||||||
|
|
||||||
export interface UserCollection {
|
export interface UserCollection {
|
||||||
@@ -11,7 +11,7 @@ export interface UserCollection {
|
|||||||
poster_path: string;
|
poster_path: string;
|
||||||
|
|
||||||
userCollectionEntries: UserCollectionEntry[];
|
userCollectionEntries: UserCollectionEntry[];
|
||||||
entries: Entry[];
|
entries: CollectionEntry[];
|
||||||
changed: boolean;
|
changed: boolean;
|
||||||
isChecked: boolean;
|
isChecked: boolean;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user