🔍 Code Extractor

function count_user_notifications

Maturity: 56

Counts the total number of notifications for a specific user in a Neo4j graph database, with an option to filter for only unread notifications.

File:
/tf/active/vicechatdev/CDocs/utils/notifications.py
Lines:
1046 - 1078
Complexity:
simple

Purpose

This function queries a Neo4j database to retrieve the count of notifications associated with a user identified by their UID. It supports filtering to count only unread notifications when needed. The function is designed for notification management systems where users need to see their notification counts, such as badge indicators in user interfaces. It includes error handling that returns 0 if the query fails or if no notifications are found.

Source Code

def count_user_notifications(user_uid: str, unread_only: bool = False) -> int:
    """
    Count notifications for a user.
    
    Args:
        user_uid: UID of user
        unread_only: Whether to count only unread notifications
        
    Returns:
        Number of notifications
    """
    try:
        # Build query
        query = """
        MATCH (u:User {UID: $user_uid})-[:HAS_NOTIFICATION]->(n:Notification)
        """
        
        if unread_only:
            query += "WHERE n.read = false "
            
        query += "RETURN count(n) as count"
        
        # Execute query
        result = db.run_query(query, {"user_uid": user_uid})
        
        if result and 'count' in result[0]:
            return result[0]['count']
            
        return 0
        
    except Exception as e:
        logger.error(f"Error counting notifications for user {user_uid}: {e}")
        return 0

Parameters

Name Type Default Kind
user_uid str - positional_or_keyword
unread_only bool False positional_or_keyword

Parameter Details

user_uid: A string representing the unique identifier (UID) of the user whose notifications should be counted. This UID must match the UID property of a User node in the Neo4j database. Expected to be a non-empty string, typically a UUID or similar unique identifier.

unread_only: A boolean flag that determines whether to count all notifications or only unread ones. When set to True, only notifications with read=false are counted. When False (default), all notifications are counted regardless of their read status. Defaults to False.

Return Value

Type: int

Returns an integer representing the count of notifications matching the query criteria. Returns 0 if no notifications are found, if the user doesn't exist, if the query fails, or if an exception occurs during execution. The return value is always a non-negative integer.

Dependencies

  • CDocs
  • logging

Required Imports

import logging
from CDocs import db

Usage Example

# Count all notifications for a user
total_notifications = count_user_notifications(user_uid="user-123-abc")
print(f"Total notifications: {total_notifications}")

# Count only unread notifications
unread_count = count_user_notifications(user_uid="user-123-abc", unread_only=True)
print(f"Unread notifications: {unread_count}")

# Example in a notification badge context
user_id = "550e8400-e29b-41d4-a716-446655440000"
unread_badge = count_user_notifications(user_id, unread_only=True)
if unread_badge > 0:
    print(f"You have {unread_badge} unread notification(s)")

Best Practices

  • Always handle the case where the function returns 0, as this could indicate either no notifications or an error condition
  • Consider logging or monitoring when this function returns 0 unexpectedly to detect potential database connectivity issues
  • The function silently catches all exceptions and returns 0, so check logs for error messages if unexpected results occur
  • Ensure the user_uid parameter is validated before calling this function to avoid unnecessary database queries
  • For high-traffic applications, consider caching the notification count to reduce database load
  • The function assumes the database schema has User nodes with UID property and Notification nodes with read property connected by HAS_NOTIFICATION relationships
  • When using unread_only=True, ensure that all Notification nodes have a 'read' boolean property set, otherwise they may not be counted correctly

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_user_notifications 86.7% similar

    Retrieves notifications for a specific user from a Neo4j graph database, with options for filtering unread notifications and pagination support.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function delete_all_notifications 72.8% similar

    Deletes all notifications or only read notifications for a specific user from a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function delete_notification 66.5% similar

    Deletes a notification node from a Neo4j graph database by its unique identifier (UID).

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function mark_notification_read 63.1% similar

    Updates a notification's read status in a Neo4j graph database and sets a timestamp when marked as read.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function count_audit_events 57.3% similar

    Counts audit events in a Neo4j graph database with flexible filtering options including resource, user, event type, category, and date range.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
← Back to Browse