Skip to content

feat(notifications): add user-targeted push notifications#15

Open
francescopausellii wants to merge 11 commits intofeat/web-appfrom
feat/notifications-users
Open

feat(notifications): add user-targeted push notifications#15
francescopausellii wants to merge 11 commits intofeat/web-appfrom
feat/notifications-users

Conversation

@francescopausellii
Copy link
Contributor

No description provided.

@gemini-code-assist
Copy link

Summary of Changes

Hello @francescopausellii, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a comprehensive system for user-targeted push notifications. It establishes the necessary database structures and API endpoints to manage user push subscriptions and deliver notifications directly to authenticated users. The frontend has been updated to allow users to subscribe/unsubscribe and for authenticated users to send notifications to other subscribed users. Additionally, new authentication UI components are integrated into the homepage, and foundational fields for user moderation features have been added to the database schema.

Highlights

  • User-Targeted Push Notifications: Implemented the capability to send push notifications directly to specific authenticated users, enhancing personalized communication.
  • Database Schema Expansion: Introduced new database models for PushSubscription and Notification to store user subscription details and a history of sent notifications. Also added administrative fields to User and Session models.
  • New API Endpoints: Created dedicated API routes for managing user push subscriptions (saving and removing) and for retrieving a list of users who have active subscriptions.
  • Enhanced Notification Sending Logic: Modified the notification API to support sending messages based on either a direct browser subscription or a target user ID.
  • Authentication UI Integration: Integrated new client-side authentication components (AuthForm, UserStatus) into the main application page for a more complete user experience.
Changelog
  • .gitignore
    • Added certificates directory to the ignore list.
  • prisma/migrations/20260217132538_add_push_subscription_notification_and_admin_fields/migration.sql
    • Created new database tables for push_subscription and notification.
    • Added impersonatedBy column to the session table.
    • Added banExpires, banReason, and banned columns to the user table.
  • prisma/schema.prisma
    • Defined new PushSubscription and Notification models.
    • Updated User and Session models with new fields and relationships to support notifications and administrative features.
  • src/app/api/notifications/route.ts
    • Modified the POST endpoint to conditionally send notifications to a specific user ID or a direct subscription.
  • src/app/api/notifications/subscriptions/route.ts
    • Added new API routes for POST (saving) and DELETE (removing) user push subscriptions.
  • src/app/api/notifications/users/route.ts
    • Added a new API route to fetch a list of users who have active push subscriptions.
  • src/app/page.tsx
    • Updated the main page to include authentication forms and user status display.
    • Integrated the enhanced notification form to allow user-targeted sending.
  • src/features/auth/components/auth-form.tsx
    • Added a new React component for user login and registration.
  • src/features/auth/components/user-status.tsx
    • Added a new React component to display the current user's status and a logout button.
  • src/features/auth/index.ts
    • Exported the new AuthForm and UserStatus components.
  • src/features/auth/lib/auth.ts
    • Configured the authentication library to require a username for user creation.
  • src/features/push-notifications/components/notification-subscription-form.tsx
    • Updated the form to allow selecting a target user for notifications.
    • Implemented fetching and displaying a list of users with active subscriptions.
  • src/features/push-notifications/hook/use-notification.tsx
    • Extended the notification hook to include an handleUnsubscribe function.
    • Integrated backend calls for saving and removing subscriptions when subscribing/unsubscribing.
  • src/features/push-notifications/service/notification.client.service.ts
    • Implemented client-side functions saveSubscription and removeSubscription to interact with the new subscription API.
  • src/features/push-notifications/service/notification.server.service.ts
    • Added a sendToUser function to send notifications to all active subscriptions of a given user.
    • Implemented persistence of sent notifications in the database.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces user-targeted push notifications, including database schema changes, new API endpoints for managing subscriptions and sending notifications, and UI components for authentication and notification management. The changes are well-structured within the feature-based architecture. My review focuses on improving performance and React best practices according to the repository's style guide. I've identified a critical performance issue in the notification sending logic where notifications are sent sequentially instead of in parallel, and a medium-severity issue related to React hook dependencies that could cause unnecessary re-renders. Applying these suggestions will make the feature more robust and performant.

Comment on lines 42 to 54
for (const sub of subscriptions) {
try {
await sendNotification(
{ endpoint: sub.endpoint, keys: { auth: sub.auth, p256dh: sub.p256dh } },
title,
message,
);
} catch (error) {
if (error instanceof webpush.WebPushError && error.statusCode === 410) {
await prisma.pushSubscription.delete({ where: { id: sub.id } });
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The current implementation sends notifications to a user's multiple subscriptions sequentially using a for...of loop with await. This creates a network waterfall, where each notification must wait for the previous one to complete, potentially delaying delivery.

To improve performance, these independent network requests should be executed in parallel using Promise.all().

This change aligns with the style guide rule async-parallel (1.4), which is critical for performance.

Suggested change
for (const sub of subscriptions) {
try {
await sendNotification(
{ endpoint: sub.endpoint, keys: { auth: sub.auth, p256dh: sub.p256dh } },
title,
message,
);
} catch (error) {
if (error instanceof webpush.WebPushError && error.statusCode === 410) {
await prisma.pushSubscription.delete({ where: { id: sub.id } });
}
}
}
await Promise.all(
subscriptions.map(async (sub) => {
try {
await sendNotification(
{ endpoint: sub.endpoint, keys: { auth: sub.auth, p256dh: sub.p256dh } },
title,
message,
);
} catch (error) {
if (error instanceof webpush.WebPushError && error.statusCode === 410) {
await prisma.pushSubscription.delete({ where: { id: sub.id } });
} else {
console.error(`Failed to send notification to endpoint ${sub.endpoint}:`, error);
}
}
}),
);
References
  1. Rule 1.4 async-parallel: When async operations have no interdependencies, execute them concurrently using Promise.all(). Sending notifications to different subscriptions for the same user are independent operations and should be parallelized. (link)

setTargetUserId(session.user.id);
}
});
}, [isAuthenticated, session?.user]);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The useEffect hook's dependency array includes session?.user, which is an object. This can cause the effect to re-run on every render if the session object reference changes, even if its content is the same. This leads to unnecessary re-fetches of the user list.

To avoid this, you should use a primitive value from the object that the effect actually depends on, such as session.user.id.

This follows the style guide rule rerender-dependencies (5.3) to narrow effect dependencies.

Suggested change
}, [isAuthenticated, session?.user]);
}, [isAuthenticated, session?.user?.id]);
References
  1. Rule 5.3 rerender-dependencies: Specify primitive dependencies instead of objects to minimize effect re-runs. The effect depends on the user's ID, so session?.user?.id should be used instead of the session?.user object. (link)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant