@codeanpeace Thanks , I think it solved the above issue but now I get another issue related to empty response.
now here is my domain_whitelist_plug.ex
defmodule DbserviceWeb.DomainWhitelistPlug do
import Plug.Conn
def init(options) do
options
end
def call(conn, _options) do
if allowed_domains?(conn) do
conn
else
conn
|> send_resp(403, "Not Authorized")
|> halt()
end
end
defp allowed_domains?(conn) do
whitelisted_domains = System.get_env("WHITELISTED_DOMAINS")
allowed_domains =
if is_nil(whitelisted_domains),
do: ["localhost"],
else: String.split(whitelisted_domains, ",")
if Mix.env() == :test do
true
else
Enum.member?(allowed_domains, conn.host)
end
end
end
but when I run the test code provided above , it give me this error
test index lists all user (DbserviceWeb.UserControllerTest)
test/dbservice_web/controllers/user_controller_test.exs:71
** (MatchError) no match of right hand side value: []
code: [head | _tail] = json_response(conn, 200)
stacktrace:
test/dbservice_web/controllers/user_controller_test.exs:73: (test)
but when I hit the api endpoint url http://localhost:4000/api/user
I get the data,
but when I run the test here I get empty response in the response body
here is my IO.inspect(conn)
%Plug.Conn{
adapter: {Plug.Adapters.Test.Conn, :...},
assigns: %{layout: false, user: []},
body_params: %{},
cookies: %{},
halted: false,
host: "www.example.com",
method: "GET",
owner: #PID<0.454.0>,
params: %{},
path_info: ["api", "user"],
path_params: %{},
port: 80,
private: %{
DbserviceWeb.Router => {[], %{PhoenixSwagger.Plug.SwaggerUI => []}},
:before_send => [#Function<0.11807388/1 in Plug.Telemetry.call/2>],
:phoenix_action => :index,
:phoenix_controller => DbserviceWeb.UserController,
:phoenix_endpoint => DbserviceWeb.Endpoint,
:phoenix_format => "json",
:phoenix_layout => {DbserviceWeb.LayoutView, :app},
:phoenix_recycled => false,
:phoenix_request_logger => {"request_logger", "request_logger"},
:phoenix_router => DbserviceWeb.Router,
:phoenix_template => "index.json",
:phoenix_view => DbserviceWeb.UserView,
:plug_session_fetch => #Function<1.84243074/1 in Plug.Session.fetch_session/1>,
:plug_skip_csrf_protection => true
},
query_params: %{},
query_string: "",
remote_ip: {127, 0, 0, 1},
req_cookies: %{},
req_headers: [{"accept", "application/json"}],
request_path: "/api/user",
resp_body: "[]",
resp_cookies: %{},
resp_headers: [
{"content-type", "application/json; charset=utf-8"},
{"cache-control", "max-age=0, private, must-revalidate"},
{"x-request-id", "F1NFjCHCBySi7EcAAAOB"}
],
scheme: :http,
script_name: [],
secret_key_base: :...,
state: :sent,
status: 200
}
here is my usercontoller
def index(conn, params) do
param = Enum.map(params, fn {key, value} -> {String.to_existing_atom(key), value} end)
user =
Enum.reduce(param, User, fn
{key, value}, query ->
from u in query, where: field(u, ^key) == ^value
_, query ->
query
end)
|> Repo.all()
IO.inspect(user)
render(conn, "index.json", user: user)
end