peppy

peppy

How to pattern match list of structs from mysql results for multiple conditions?

I’m trying to build a simple function to see if a user is authorized to join a conversation. Basically, it needs to query the mysql database to get a list of all users in the conversation, and then compare the userid on the socket to the results list.

This is what I have so far:

 def join("conv:" <> convid, _message, socket) do
    if authorized?(convid, socket) do
      IO.inspect("join conversation " <> convid)
      send(self(), :after_join)
      {:ok, socket}
    else
      IO.inspect("not authorized to join room")
      :error
    end
  end

 defp authorized?(convid, socket) do
    IO.inspect("run conv auth function")
    results =
    from(m in GetUsersInConv, # use lib/app_web/schemas/usersinconv.ex
      where: m.id == ^convid,
      select: %{userid: m.userid, status: m.status}
    )
    |> Repo.all()
    userIdInSocket = socket.assigns.user_id
    IO.inspect("socket userid: " <> userIdInSocket)
    IO.inspect(results)
    # Need to add matching function next...
  end

These are the results I get, a list of all userids in the conversation and their status:

"run conv auth function"
[debug] QUERY OK source="conversations" db=0.7ms idle=1289.4ms
SELECT p0.`userid`, p0.`status` FROM `conversations` AS p0 WHERE (p0.`id` = ?) [107876]
"socket userid: 1"
[
  %{status: 0, userid: 1},
  %{status: 0, userid: 299},
  %{status: 0, userid: 664},
  %{status: 0, userid: 782},
  %{status: 0, userid: 1035},
  %{status: 0, userid: 4609},
  %{status: 0, userid: 4684},
  %{status: 0, userid: 5974},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 6755},
  %{status: 0, userid: 8980},
  %{status: 0, userid: 9246},
  %{status: 0, userid: 10759},
  %{status: 0, userid: 15517},
  %{status: 0, userid: 16502},
  %{status: 0, userid: 32428},
  %{status: 0, userid: 61240},
  %{status: 0, userid: 79131},
  %{status: 0, userid: 98521},
  %{status: 3, userid: 145222}
]

If the userid of the socket is “1”, how can I build an Enum iteration function to match the following conditions:

  1. userid “1” is found within the result list of userids
  2. status != 3 AND status != 7 for that user as well.

If all those conditions are met, return “true”, otherwise “false” for the entire “authorized?” function.

I’m getting better and better at figuring out elixir, but syntax for enum and pattern matching is still a little tricky.

Thanks!

Marked As Solved

dimitarvp

dimitarvp

While I am not convinced that I understood your requirements well, this works:

defmodule UserChecks do
  def authorized?(user_id, %{userid: user_id, status: status}) when status not in [3, 7], do: true
  def authorized?(_user_id, %{userid: _other_user_id, status: _status}), do: false

  def any_authorized?(user_id, user_ids_and_statuses) when is_list(user_ids_and_statuses) do
    Enum.any?(user_ids_and_statuses, &authorized?(user_id, &1))
  end

  def test() do
    user_ids_and_statuses = [
      %{status: 0, userid: 1},
      %{status: 3, userid: 100},
      %{status: 7, userid: 200},
      %{status: 0, userid: 299},
      %{status: 0, userid: 664}
    ]

    IO.inspect(user_ids_and_statuses, label: "userids and statuses")
    IO.inspect(any_authorized?(1, user_ids_and_statuses), label: "Is userid 1 authorized?")
    IO.inspect(any_authorized?(2, user_ids_and_statuses), label: "Is userid 2 authorized?")
    IO.inspect(any_authorized?(100, user_ids_and_statuses), label: "Is userid 100 authorized?")
    IO.inspect(any_authorized?(200, user_ids_and_statuses), label: "Is userid 200 authorized?")
    IO.inspect(any_authorized?(299, user_ids_and_statuses), label: "Is userid 299 authorized?")
    IO.inspect(any_authorized?(664, user_ids_and_statuses), label: "Is userid 664 authorized?")
  end
end

authorized? basically emulates the match? you are trying to do. IMO a function with multiple pattern-matching heads reads better. Notice how user_id is specified twice in the first head; this a neat trick that matches only when there’s the same value in the first function argument and the userid field of the map.

But if you really must know how does it look with match?, here you go:

  def authorized?(searched_user_id, %{userid: _user_id, status: _status} = userid_and_status) do
    match?(
      %{userid: ^searched_user_id, status: status} when status not in [3, 7],
      userid_and_status
    )
  end

Also Liked

al2o3cr

al2o3cr

Both of these are expressible in SQL - for instance, you could rephrase the above as:

“does a row exist with user_id = 1 and status != 3 and status != 7”

Check out Repo.exists?.

Where Next?

Popular in Questions Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement