Soundcheck.Check.Warning.UnguardedSubscribe (soundcheck v0.1.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Flags PubSub subscriptions in a LiveView's mount/3 that are not guarded by connected?(socket). mount/3 also runs for the disconnected HTTP render, in a short-lived process that subscribes, renders once, and exits; only the connected mount needs the subscription.

Before:

def mount(_params, _session, socket) do
  Phoenix.PubSub.subscribe(MyApp.PubSub, "posts")
  {:ok, socket}
end

After:

def mount(_params, _session, socket) do
  if connected?(socket), do: Phoenix.PubSub.subscribe(MyApp.PubSub, "posts")
  {:ok, socket}
end

A call counts as a subscription when its alias-expanded name (Phoenix.PubSub.subscribe, MyApp.Endpoint.subscribe) matches subscribe_functions. Calls inside if connected?(socket) (or unless !connected?(socket)) are guarded. Subscriptions in helpers that mount/3 calls are not followed.

Confidence: high. Tier: syntactic (works without compiling).

Check-Specific Parameters

Use the following parameters to configure this check:

:excluded_paths

Paths to skip (atoms, binaries as path segments, or regexes).

This parameter defaults to [~r/\/test\//, "test"].

:strict

Unused.

This parameter defaults to false.

:subscribe_functions

Regexes or exact names of subscribing functions, as Module.function.

This parameter defaults to [~r/^Phoenix\.PubSub\.subscribe$/, ~r/\.subscribe$/].

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.