Skip to content

Instantly share code, notes, and snippets.

const initialState = {
all: [],
currentUserRooms: [],
};
export default function (state = initialState, action) {
switch (action.type) {
case 'FETCH_ROOMS_SUCCESS':
return {
...state,
import api from '../api';
export function fetchRooms() {
return dispatch => api.fetch('/rooms')
.then((response) => {
dispatch({ type: 'FETCH_ROOMS_SUCCESS', response });
});
}
export function fetchUserRooms(userId) {
import { fetchUserRooms } from './rooms';
// ...
function setCurrentUser(dispatch, response) {
localStorage.setItem('token', JSON.stringify(response.meta.token));
dispatch({ type: 'AUTHENTICATION_SUCCESS', response });
dispatch(fetchUserRooms(response.data.id)); // new line
}
# top of file...
plug Guardian.Plug.EnsureAuthenticated, [handler: Sling.SessionController] when action in [:rooms]
# bottom of file...
def rooms(conn, _params) do
current_user = Guardian.Plug.current_resource(conn)
rooms = Repo.all(assoc(current_user, :rooms))
render(conn, Sling.RoomView, "index.json", %{rooms: rooms})
defmodule Sling.RoomController do
use Sling.Web, :controller
alias Sling.Room
plug Guardian.Plug.EnsureAuthenticated, handler: Sling.SessionController
def index(conn, _params) do
rooms = Repo.all(Room)
render(conn, "index.json", rooms: rooms)
get "/users/:id/rooms", UserController, :rooms
resources "/rooms", RoomController, only: [:index, :create]
post "/rooms/:id/join", RoomController, :join
defmodule Sling.Room do
use Sling.Web, :model
schema "rooms" do
field :name, :string
field :topic, :string
many_to_many :users, Sling.User, join_through: "user_rooms"
timestamps()
end
defmodule Sling.UserRoom do
use Sling.Web, :model
schema "user_rooms" do
belongs_to :user, Sling.User
belongs_to :room, Sling.Room
timestamps()
end
defmodule Sling.Repo.Migrations.CreateUserRoom do
use Ecto.Migration
def change do
create table(:user_rooms) do
add :user_id, references(:users, on_delete: :nothing), null: false
add :room_id, references(:rooms, on_delete: :nothing), null: false
timestamps()
end
defmodule Sling.Repo.Migrations.CreateRoom do
use Ecto.Migration
def change do
create table(:rooms) do
add :name, :string, null: false
add :topic, :string, default: ""
timestamps()
end