linksort icon indicating copy to clipboard operation
linksort copied to clipboard

Add LinksCount field to User model with lazy population and incremental updates

Open Copilot opened this issue 7 months ago • 0 comments

This PR implements a LinksCount tracking system for users to efficiently track the total number of links each user has saved.

Changes Made

User Model (model/user.go)

  • Added LinksCount int field to the User struct
  • Added IncrementLinksCount() method for convenient count updates

LinkStore Interface and Implementation

  • Interface (model/link.go): Added GetTotalLinksCountByUser(ctx context.Context, u *User) (int, error) method
  • Implementation (db/link.go): Implemented the method using MongoDB's CountDocuments() to query actual link counts

UserController (controller/user.go)

  • Added private populateLinksCount() method that lazily loads the count from database when LinksCount == 0
  • Updated GetUserBySessionID() and GetUserByToken() to populate LinksCount when needed
  • Updated LinkStore interface definition to include the new method

LinkController (controller/link.go)

  • Updated CreateLink() to call IncrementLinksCount() after successful link creation
  • Only increments when user.LinksCount > 0 to avoid setting inaccurate values that would prevent lazy loading

Implementation Strategy

The solution uses a lazy population pattern:

  1. New users: LinksCount defaults to 0 (Go's zero value)
  2. First access: When LinksCount is 0, the system queries the database for the actual count
  3. Subsequent updates: New links increment the cached count without additional database queries
  4. Accuracy: If the count becomes stale (e.g., through direct database operations), it will be refreshed on next user fetch

Example Usage

// User creation - LinksCount starts at 0
user := CreateUser(...)  // user.LinksCount == 0

// First access - populates from database  
user = GetUserBySessionID(...)  // Queries DB: user.LinksCount == actual count

// Link creation - increments cached value
CreateLink(user, ...)  // user.LinksCount++, no additional DB query

This approach minimizes database queries while maintaining accuracy and is consistent with the existing codebase patterns.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Jul 22 '25 13:07 Copilot