Skip to content

通知に新しい設定種別を追加する手順 ​

ユーザーに通知設定のオンオフを選ばせたい時の実装手順です。

1. internal/ent/schema/user.go で、追加した設定項目を増やす ​

go
type DisabledNotificationSettings struct {
    FriendRequests          bool `json:"friend_requests,omitempty"`
    FriendActivity          bool `json:"friend_activity,omitempty"`
    EventParticipation      bool `json:"event_participant,omitempty"`
    Chat                    bool `json:"chat,omitempty"`
    Tipping                 bool `json:"tipping,omitempty"`
    FavoriteScenarioPublish bool `json:"favorite_scenario_publish,omitempty"`

    // こんな感じで追加
    Hogeeee                 bool `json:"hogeeee,omitempty"`
}

INFO

  • goではboolのデフォルト値はfalse → 通知設定のデフォルトはオン
  • ちなみに、デフォルトで通知設定オフにはできない

2. internal/usecase/notification_setting.go で、通知設定のデータの格納をする ​

go
{
    Key:         "hogeeee",
    Disabled:    func(u *ent.User) bool { return u.DisabledNotificationSettings.Hogeeee },
    SetDisabled: func(ns *schema.DisabledNotificationSettings, disabled bool) { ns.Hogeeee = disabled },
    Name:        i18n.GetDictContext(ctx).NotificationSetting.Hogeeee,
    Show:        func(ctx context.Context, u *ent.User) (bool, error) { return true, nil },
}

Name は backend/i18n/dict_*.yaml の notificationSetting に全ロケール分を追加し、 go generate ./i18n/generate.go で再生成する。

設定画面への表示 (notificationSettings query) と保存 (updateNotificationSetting mutation) は どちらもこの一覧を回すので、resolver 側に項目ごとの分岐を足す必要はない。 SetDisabled を書き忘れるとその項目だけ保存できなくなるため、 notification_setting_test.go が定義漏れを検出する。

WARNING

Show が false を返すユーザーには項目自体が表示されず、保存時も現在値が維持される。 「表示されないユーザーには必ずオフ」にしたい場合は、Show で隠すだけでなく 送信側でも送らないようにする。

3. 具体的な通知にそのオンオフを適用する ​

go
if _, err := usecase.SendNotification(
    ctx,
    sender,
    receiver,
    true, // showNotifyTab
    "送信するテキスト",
    s, // imageScenario
    schema.OpenFriendRequestAction(), // 通知をタップした時のアクション
    func(ns schema.DisabledNotificationSettings) bool {
        // こう書けば、通知設定オンの時しか通知が来なくなる
        return !ns.Hogeeee 
        // ちなみに、常に通知をしたい場合はtrueを書くだけでよい
    },
); err != nil {
    return nil, err
}