Skip to content

Conversation

@egze
Copy link
Owner

@egze egze commented Apr 18, 2025

Add support for scopes introduced in Phoenix 1.8.

To add scopes to your context, use ContextKit.CRUD module like so:

defmodule MyApp.Posts do
  use ContextKit.CRUD.Scoped,
    repo: MyApp.Repo,
    schema: MyApp.Schemas.Post,
    queries: __MODULE__,
    pubsub: MyApp.PubSub,
    scope: Application.compile_env(:my_app, :scopes)[:user]
end

Scoped Operations (Phoenix 1.8)

When using Phoenix 1.8 scopes, all CRUD operations take a scope parameter:

# List records in scope
Posts.list_posts(socket.assigns.current_scope)

# Get record in scope
Posts.get_post(socket.assigns.current_scope, 123)

# Create record in scope
Posts.create_post(socket.assigns.current_scope, %{content: "my content"})

# Update record in scope
Posts.update_post(socket.assigns.current_scope, post, %{content: "updated content"})

# Delete record in scope
Posts.delete_post(socket.assigns.current_scope, post)

PubSub Integration

When configured with pubsub and scope, automatic broadcasting occurs for create, update, and delete operations:

# Subscribe to scoped updates
Posts.subscribe_posts(socket.assigns.current_scope)

# Now the current process will receive messages like:
# {:created, %Post{}}
# {:updated, %Post{}}
# {:deleted, %Post{}}

# Broadcast custom messages
Posts.broadcast_post(socket.assigns.current_scope, {:custom_event, post})

The classic ContextKit.CRUD is also still supported, which doesn't add scopes and pubsub.

@egze egze merged commit bf7e1a5 into main May 7, 2025
1 check passed
@egze egze deleted the scopes branch May 7, 2025 19:20
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.

2 participants