linksort
linksort copied to clipboard
Add LinksCount field to User model with lazy population and incremental updates
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 intfield to theUserstruct - Added
IncrementLinksCount()method for convenient count updates
LinkStore Interface and Implementation
-
Interface (
model/link.go): AddedGetTotalLinksCountByUser(ctx context.Context, u *User) (int, error)method -
Implementation (
db/link.go): Implemented the method using MongoDB'sCountDocuments()to query actual link counts
UserController (controller/user.go)
- Added private
populateLinksCount()method that lazily loads the count from database whenLinksCount == 0 - Updated
GetUserBySessionID()andGetUserByToken()to populate LinksCount when needed - Updated LinkStore interface definition to include the new method
LinkController (controller/link.go)
- Updated
CreateLink()to callIncrementLinksCount()after successful link creation - Only increments when
user.LinksCount > 0to avoid setting inaccurate values that would prevent lazy loading
Implementation Strategy
The solution uses a lazy population pattern:
- New users: LinksCount defaults to 0 (Go's zero value)
- First access: When LinksCount is 0, the system queries the database for the actual count
- Subsequent updates: New links increment the cached count without additional database queries
- 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.