@@ -295,38 +295,56 @@ const deleteComment = async (req, res) => {
295295 }
296296} ;
297297
298- // track view
298+ // function1: increment view count
299+ const incrementViewCount = async ( dbName , datasetId ) => {
300+ const dataset = await getOrCreateDataset ( dbName , datasetId ) ;
301+ dataset . views_count = ( dataset . views_count || 0 ) + 1 ;
302+ await dataset . save ( ) ;
303+ return dataset ;
304+ } ;
305+
306+ // function2: add or update a viewed history
307+ const trackUserHistory = async ( userId , datasetId ) => {
308+ const existingView = await ViewHistory . findOne ( {
309+ where : {
310+ user_id : userId ,
311+ dataset_id : datasetId ,
312+ } ,
313+ } ) ;
314+
315+ if ( existingView ) {
316+ existingView . viewed_at = new Date ( ) ;
317+ await existingView . save ( ) ;
318+ return { isNew : false } ;
319+ } else {
320+ // create new record
321+ await ViewHistory . create ( {
322+ user_id : userId ,
323+ dataset_id : datasetId ,
324+ } ) ;
325+ return { isNew : true } ;
326+ }
327+ } ;
328+
329+ // combined function1+2
299330const trackView = async ( req , res ) => {
300331 try {
301332 const user = req . user ;
302333 const { dbName, datasetId } = req . params ;
303- const dataset = await getOrCreateDataset ( dbName , datasetId ) ;
304- // Increment view count
305- dataset . views_count = ( dataset . views_count || 0 ) + 1 ;
306- await dataset . save ( ) ;
334+ const dataset = await incrementViewCount ( dbName , datasetId ) ;
307335
308- // check if user has viewed this dataset before
309- const existingView = await ViewHistory . findOne ( {
310- where : {
311- user_id : user . id ,
312- dataset_id : dataset . id ,
313- } ,
314- } ) ;
315-
316- if ( existingView ) {
317- existingView . viewed_at = new Date ( ) ;
318- await existingView . save ( ) ;
319- } else {
320- await ViewHistory . create ( {
321- user_id : user . id ,
322- dataset_id : dataset . id ,
323- } ) ;
336+ // track personal history
337+ let historyResult = null ;
338+ if ( user ) {
339+ historyResult = await trackUserHistory ( user . id , dataset . id ) ;
324340 }
325341
326342 res . status ( 200 ) . json ( {
327343 message : "View tracked successfully" ,
328344 viewCount : dataset . views_count ,
329- isNewView : ! existingView ,
345+ personalHistoryTracked : ! ! historyResult ,
346+ isNewView : historyResult ?. isNew ,
347+ isAuthenticated : ! ! user ,
330348 } ) ;
331349 } catch ( error ) {
332350 console . error ( "Track view error:" , error ) ;
0 commit comments