@@ -2,6 +2,16 @@ import { FastifyInstance, FastifyRequest } from 'fastify';
22import { z } from 'zod' ;
33import { db } from '../lib/database.js' ;
44import { generateShortCode } from '../lib/utils.js' ;
5+ import { invalidateLinkResolutionCache } from '../lib/link-resolution-cache.js' ;
6+
7+ async function getTemplateSlug ( templateId : string | null ) : Promise < string | null > {
8+ if ( ! templateId ) return null ;
9+ const result = await db . query (
10+ 'SELECT slug FROM link_templates WHERE id = $1' ,
11+ [ templateId ]
12+ ) ;
13+ return result . rows [ 0 ] ?. slug ?? null ;
14+ }
515
616const createLinkSchema = z . object ( {
717 userId : z . string ( ) . uuid ( ) . optional ( ) ,
@@ -227,6 +237,12 @@ export async function linkRoutes(fastify: FastifyInstance) {
227237
228238 const data = updateLinkSchema . parse ( request . body ) ;
229239
240+ // Capture current identifiers for cache invalidation after the update
241+ const oldLinkResult = await db . query (
242+ 'SELECT short_code, template_id FROM links WHERE id = $1' ,
243+ [ id ]
244+ ) ;
245+
230246 // Build update query dynamically
231247 const updates : string [ ] = [ ] ;
232248 const values : any [ ] = [ ] ;
@@ -271,6 +287,16 @@ export async function linkRoutes(fastify: FastifyInstance) {
271287 }
272288
273289 const link = result . rows [ 0 ] ;
290+
291+ // Invalidate cached link JSON for both old and new template associations
292+ const oldRow = oldLinkResult . rows [ 0 ] ;
293+ const oldTemplateSlug = await getTemplateSlug ( oldRow ?. template_id ) ;
294+ const newTemplateSlug = await getTemplateSlug ( link . template_id ) ;
295+ await invalidateLinkResolutionCache ( fastify . redis , link . short_code , oldTemplateSlug ) ;
296+ if ( newTemplateSlug !== oldTemplateSlug ) {
297+ await invalidateLinkResolutionCache ( fastify . redis , link . short_code , newTemplateSlug ) ;
298+ }
299+
274300 return {
275301 ...link ,
276302 utmParameters : link . utm_parameters ,
@@ -388,12 +414,12 @@ export async function linkRoutes(fastify: FastifyInstance) {
388414 let result ;
389415 if ( userId ) {
390416 result = await db . query (
391- 'DELETE FROM links WHERE id = $1 AND user_id = $2 RETURNING id' ,
417+ 'DELETE FROM links WHERE id = $1 AND user_id = $2 RETURNING id, short_code, template_id ' ,
392418 [ id , userId ]
393419 ) ;
394420 } else {
395421 result = await db . query (
396- 'DELETE FROM links WHERE id = $1 RETURNING id' ,
422+ 'DELETE FROM links WHERE id = $1 RETURNING id, short_code, template_id ' ,
397423 [ id ]
398424 ) ;
399425 }
@@ -402,6 +428,10 @@ export async function linkRoutes(fastify: FastifyInstance) {
402428 throw new Error ( 'Link not found' ) ;
403429 }
404430
431+ const deleted = result . rows [ 0 ] ;
432+ const templateSlug = await getTemplateSlug ( deleted . template_id ) ;
433+ await invalidateLinkResolutionCache ( fastify . redis , deleted . short_code , templateSlug ) ;
434+
405435 return { success : true } ;
406436 } ) ;
407437}
0 commit comments