|
| 1 | +--- |
| 2 | +topic: fcm |
| 3 | +last_verified: 2026-06-16 |
| 4 | +sources: |
| 5 | + - internal/domain/fcm_token.go |
| 6 | + - internal/usecase/notification.go |
| 7 | + - internal/infrastructure/database/postgres/fcm_token_repository.go |
| 8 | + - internal/infrastructure/database/postgres/fcm_token_repository_test.go |
| 9 | + - internal/transport/handlers/fcm_handler.go |
| 10 | + - internal/transport/handlers/fcm_handler_test.go |
| 11 | + - internal/transport/handlers/routes.go |
| 12 | + - internal/transport/handlers/handler.go |
| 13 | + - internal/server/server.go |
| 14 | + - internal/bootstrap/bootstrap.go |
| 15 | + - pkg/firebase/app.go |
| 16 | + - pkg/firebase/admin.go |
| 17 | + - pkg/firebase/messaging.go |
| 18 | + - internal/infrastructure/database/migrations/20260615220942_add_fcm_tokens.sql |
| 19 | +--- |
| 20 | + |
| 21 | +# Firebase Cloud Messaging (FCM) |
| 22 | + |
| 23 | +FCM sends push notifications to Android, iOS, and web clients. The backend stores per-user device tokens and sends notifications via the Firebase Admin SDK using the FCM HTTP v1 API. |
| 24 | + |
| 25 | +## Domain entity |
| 26 | + |
| 27 | +`internal/domain/fcm_token.go`: |
| 28 | +```go |
| 29 | +type FCMToken struct { |
| 30 | + ID string |
| 31 | + UserID string |
| 32 | + Token string |
| 33 | + Platform string // "android" | "ios" | "web" |
| 34 | + CreatedAt time.Time |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +## Usecase interfaces |
| 39 | + |
| 40 | +Both interfaces live in `internal/usecase/notification.go`. |
| 41 | + |
| 42 | +```go |
| 43 | +// NotificationSender sends FCM push notifications via the Admin SDK. |
| 44 | +type NotificationSender interface { |
| 45 | + SendToToken(ctx context.Context, token, title, body string, data map[string]string) error |
| 46 | + SendMulticast(ctx context.Context, tokens []string, title, body string, data map[string]string) error |
| 47 | +} |
| 48 | + |
| 49 | +// FCMTokenRepository persists device registration tokens per user. |
| 50 | +type FCMTokenRepository interface { |
| 51 | + SaveToken(ctx context.Context, userID, token, platform string) error |
| 52 | + GetTokensByUserID(ctx context.Context, userID string) ([]domain.FCMToken, error) |
| 53 | + DeleteToken(ctx context.Context, token string) error |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +`NotificationSender` is the narrow port used by any use case that needs to push a notification. `FCMTokenRepository` is the persistence port used by the HTTP handlers. |
| 58 | + |
| 59 | +## pkg/firebase — shared app initialisation |
| 60 | + |
| 61 | +`pkg/firebase/app.go` creates the single Firebase Admin SDK app instance: |
| 62 | + |
| 63 | +```go |
| 64 | +func NewApp(ctx context.Context, projectID, credentialsJSON string) (*firebasesdk.App, error) |
| 65 | +``` |
| 66 | + |
| 67 | +The same `*firebasesdk.App` is passed to both `NewAuthClient` and `NewMessagingClient` so the SDK initialises only once per process. Calling `firebasesdk.NewApp` twice with default settings returns an error, hence the shared app pattern. |
| 68 | + |
| 69 | +`pkg/firebase/admin.go` — `NewAuthClient(ctx, app)` now accepts the pre-created app instead of creating its own. |
| 70 | + |
| 71 | +`pkg/firebase/messaging.go` — `NewMessagingClient(ctx, app)` wraps `*messaging.Client`: |
| 72 | + |
| 73 | +```go |
| 74 | +func NewMessagingClient(ctx context.Context, app *firebasesdk.App) (usecase.NotificationSender, error) |
| 75 | +``` |
| 76 | + |
| 77 | +`SendMulticast` uses `client.SendEachForMulticast` and returns an error if any individual message fails. |
| 78 | + |
| 79 | +## bootstrap.App |
| 80 | + |
| 81 | +`internal/bootstrap/bootstrap.go` — `App` now carries `FCMSender usecase.NotificationSender`. Both Firebase clients share the same SDK app: |
| 82 | + |
| 83 | +```go |
| 84 | +if cfg.FirebaseProjectID != "" { |
| 85 | + fbApp, _ := firebase.NewApp(ctx, cfg.FirebaseProjectID, cfg.FirebaseServiceAccountJSON) |
| 86 | + authClient, _ := firebase.NewAuthClient(ctx, fbApp) |
| 87 | + msgClient, _ := firebase.NewMessagingClient(ctx, fbApp) |
| 88 | + app.Firebase = authClient |
| 89 | + app.FCMSender = msgClient |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +When `FIREBASE_PROJECT_ID` is not set both fields are `nil` and FCM routes are not registered. |
| 94 | + |
| 95 | +## Database — fcm_tokens table |
| 96 | + |
| 97 | +Migration `20260615220942_add_fcm_tokens.sql`: |
| 98 | +```sql |
| 99 | +CREATE TABLE IF NOT EXISTS fcm_tokens ( |
| 100 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), |
| 101 | + user_id TEXT NOT NULL, |
| 102 | + token TEXT NOT NULL UNIQUE, |
| 103 | + platform TEXT NOT NULL, |
| 104 | + created_at TIMESTAMPTZ NOT NULL DEFAULT now() |
| 105 | +); |
| 106 | +CREATE INDEX IF NOT EXISTS idx_fcm_tokens_user_id ON fcm_tokens(user_id); |
| 107 | +``` |
| 108 | + |
| 109 | +`SaveToken` uses an upsert (`ON CONFLICT (token) DO UPDATE`) so a physical device re-registering or switching accounts is handled atomically without a duplicate token. |
| 110 | + |
| 111 | +## HTTP endpoints |
| 112 | + |
| 113 | +Both routes are registered inside the `/api/v1` group and inherit the `FirebaseAuth` middleware when `h.verifier != nil`. They are only registered when `h.fcmTokenRepo != nil`: |
| 114 | + |
| 115 | +```go |
| 116 | +if h.fcmTokenRepo != nil { |
| 117 | + api.POST("/fcm/register", h.RegisterFCMToken) |
| 118 | + api.DELETE("/fcm/unregister", h.UnregisterFCMToken) |
| 119 | +} |
| 120 | +``` |
| 121 | + |
| 122 | +### POST /api/v1/fcm/register |
| 123 | + |
| 124 | +Request body: |
| 125 | +```json |
| 126 | +{ "token": "<fcm-registration-token>", "platform": "android|ios|web" } |
| 127 | +``` |
| 128 | + |
| 129 | +Reads `UID` from `*usecase.FirebaseToken` in the Gin context (set by `FirebaseAuth` middleware), then calls `SaveToken`. Returns `200 {"message": "token registered"}`. |
| 130 | + |
| 131 | +### DELETE /api/v1/fcm/unregister |
| 132 | + |
| 133 | +Request body: |
| 134 | +```json |
| 135 | +{ "token": "<fcm-registration-token>" } |
| 136 | +``` |
| 137 | + |
| 138 | +Calls `DeleteToken`. Returns `200 {"message": "token unregistered"}`. Designed to be called on logout. |
| 139 | + |
| 140 | +## Wiring in server.go |
| 141 | + |
| 142 | +```go |
| 143 | +fcmTokenRepo := postgres.NewFCMTokenRepository(app.DB) |
| 144 | +h := handlers.NewHandler(..., app.FCMSender, fcmTokenRepo) |
| 145 | +``` |
| 146 | + |
| 147 | +`NewFCMTokenRepository` always returns a valid repository backed by `app.DB`; the FCM routes are gated by `h.fcmTokenRepo != nil` on the router side, but since `NewFCMTokenRepository` is always called, the routes are always registered when the server starts. The `FirebaseAuth` middleware is the actual auth gate. |
| 148 | + |
| 149 | +## Sending notifications from other use cases |
| 150 | + |
| 151 | +Inject `usecase.NotificationSender` into any use case that needs to push a notification: |
| 152 | + |
| 153 | +```go |
| 154 | +// Example: notify all user devices after a background job completes |
| 155 | +tokens, _ := fcmTokenRepo.GetTokensByUserID(ctx, userID) |
| 156 | +fcmTokens := make([]string, len(tokens)) |
| 157 | +for i, t := range tokens { fcmTokens[i] = t.Token } |
| 158 | +_ = fcmSender.SendMulticast(ctx, fcmTokens, "Job done", "Your report is ready", nil) |
| 159 | +``` |
| 160 | + |
| 161 | +## Testing |
| 162 | + |
| 163 | +**Handler unit tests** (`internal/transport/handlers/fcm_handler_test.go`): `mockFCMTokenRepo` implements `usecase.FCMTokenRepository`; no database or Firebase SDK involved. |
| 164 | + |
| 165 | +**Repository integration tests** (`internal/infrastructure/database/postgres/fcm_token_repository_test.go`): use Testcontainers (real PostgreSQL). Each test calls `setupFCMTokensTable` to create the table and registers a cleanup to drop it. Shares the `testDB` global and `TestMain` from `health_repository_test.go` — do not add another `TestMain` to this package. |
| 166 | + |
| 167 | +## Environment variables |
| 168 | + |
| 169 | +| Variable | Required | Description | |
| 170 | +|---|---|---| |
| 171 | +| `FIREBASE_PROJECT_ID` | No | Firebase project ID (e.g. `my-app-12345`). Omit to disable Firebase entirely. | |
| 172 | +| `FIREBASE_SERVICE_ACCOUNT_JSON` | No | Raw service account JSON string. Omit to use Application Default Credentials. | |
| 173 | + |
| 174 | +Both are already documented in `backend/.env.example`. |
0 commit comments