From 1d1e182523ff707a2551d8467bbbdeac2caec075 Mon Sep 17 00:00:00 2001 From: Sonny Date: Tue, 19 Aug 2025 23:44:48 +0200 Subject: [PATCH] refactor: compute favorite links in backend --- .../controllers/show_collections_controller.ts | 17 ++++++++++++----- app/links/services/link_service.ts | 8 ++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/app/collections/controllers/show_collections_controller.ts b/app/collections/controllers/show_collections_controller.ts index b3433d1..da82f28 100644 --- a/app/collections/controllers/show_collections_controller.ts +++ b/app/collections/controllers/show_collections_controller.ts @@ -1,17 +1,24 @@ import { CollectionService } from '#collections/services/collection_service'; +import { LinkService } from '#links/services/link_service'; import { inject } from '@adonisjs/core'; import type { HttpContext } from '@adonisjs/core/http'; @inject() export default class ShowCollectionsController { - constructor(private collectionService: CollectionService) {} + constructor( + private collectionService: CollectionService, + private linkService: LinkService + ) {} // Dashboard async render({ inertia, response }: HttpContext) { const activeCollectionId = await this.collectionService.validateCollectionId(false); - const collections = - await this.collectionService.getCollectionsForAuthenticatedUser(); + const [collections, favoriteLinks] = await Promise.all([ + this.collectionService.getCollectionsForAuthenticatedUser(), + this.linkService.getFavoriteLinksForAuthenticatedUser(), + ]); + if (collections.length === 0) { return response.redirectToNamedRoute('collection.create-form'); } @@ -26,8 +33,8 @@ export default class ShowCollectionsController { return inertia.render('dashboard', { collections: collections.map((collection) => collection.serialize()), - activeCollection: - activeCollection?.serialize() || collections[0].serialize(), + favoriteLinks: favoriteLinks.map((link) => link.serialize()), + activeCollection: activeCollection?.serialize(), }); } } diff --git a/app/links/services/link_service.ts b/app/links/services/link_service.ts index 27fffff..e623e88 100644 --- a/app/links/services/link_service.ts +++ b/app/links/services/link_service.ts @@ -50,6 +50,14 @@ export class LinkService { .update({ favorite }); } + async getFavoriteLinksForAuthenticatedUser() { + const context = this.getAuthContext(); + return await Link.query() + .where('author_id', context.auth.user!.id) + .where('favorite', true) + .orderBy('created_at'); + } + getAuthContext() { const context = HttpContext.getOrFail(); if (!context.auth.user || !context.auth.user.id) {