Search code examples
2sxc

Add option to Blog App, to show "more viewed" posts


Actually, Blog post is a very nice app for 2sxc, but it should be great to be able to register every time a user opens a blog, and then have a module to show for example 5 more viewed posts.

Basically i need to know how to update a post field (views for example) every time a user opens or see details for that post

Thanks for your help


Solution

  • This is an interesting idea - let me give you some minimal guidance to keep things running well...

    1. First of all I really recommend you do the counting in a separate item/entity. This is for performance reasons: when you update a blog-post, you are updating 20-30 fields, which just puts a lot of unnecessary pressure on the system. So create something like ViewCount with a property BlogPostId and Count
    2. Now to update the count, I suggest you do two things
      1. Get the count and cache it somewhere
      2. Update the cache-count on each view
      3. Only update the server data every or 100 hits (just for performance, as I assume you expect a lot of views)

    Here's some pseudo code to do this...

    var postId = post.EntityId;
    var cacheId = "PostCount" + postId;
    var count = Application[cacheId] ?? -1;
    if(count == -1) {
      // load the data
      var countStates = AsList(App.Data["ViewCount"]);
      var counter = countStates.FirstOrDefault(c => c.BlogPostId == postId);
      if(counter != null) {
        count = counter.Count;
      } else {
        count = 0;
      }
    }
    
    // increment
    count++;
    
    // save to cache
    Application[cacheId] = count;
    
    // every 10 counts update the count in the storage / sql
    // on high load, increase this to 100 or 1000
    if(count % 10 == 0) {
      // you'll have to figure this out yourself - see docs link below
      App.Data.Update(...);
    }
    

    for the saving, check out the docs here https://docs.2sxc.org/api/dot-net/ToSic.Eav.Apps.AppData.html#ToSic_Eav_Apps_AppData_Update_System_Int32_System_Collections_Generic_Dictionary_System_String_System_Object__System_String_