zf

zenflows testing
git clone https://s.sonu.ch/~srfsh/zf.git
Log | Files | Refs | Submodules | README | LICENSE

commit 26be4f7f22ba820cae1a9eba4649348c7a031a66
parent 972e8eac628517c2d5b2ceabde291123eeca8905
Author: srfsh <dev@srf.sh>
Date:   Tue, 19 Jul 2022 00:40:53 +0300

web: put gql_context/2 under mw namespace

Diffstat:
Asrc/zenflows/web/mw/gql_context.ex | 48++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/zenflows/web/router.ex | 22+++-------------------
2 files changed, 51 insertions(+), 19 deletions(-)

diff --git a/src/zenflows/web/mw/gql_context.ex b/src/zenflows/web/mw/gql_context.ex @@ -0,0 +1,48 @@ +defmodule Zenflows.Web.MW.GQLContext do +@moduledoc """ +Plug middleware to set Absinthe context. + +Must be placed after `Plug.Parsers`. +""" + +@behaviour Plug + +alias Plug.Conn + +@impl true +def init(opts), do: opts + +@impl true +def call(conn, _opts) do + ctx = + %{} + |> set_admin(conn) + |> set_user_and_sign_and_body(conn) + + Absinthe.Plug.put_options(conn, context: ctx) +end + +# Set `admin` key from the headers. +@spec set_admin(map(), Conn.t()) :: map() +defp set_admin(ctx, conn) do + case Conn.get_req_header(conn, "zenflows-admin") do + [key | _] -> Map.put(ctx, :gql_admin, key) + _ -> ctx + end +end + +# Set `user` and `sign` keys from the headers, and `body` key from +# `conn.assigs`, if only `admin` is not set. +@spec set_user_and_sign_and_body(map(), Conn.t()) :: map() +defp set_user_and_sign_and_body(%{gql_admin: _} = ctx, _conn), do: ctx +defp set_user_and_sign_and_body(ctx, conn) do + with [user | _] <- Conn.get_req_header(conn, "zenflows-user"), + [sign | _] <- Conn.get_req_header(conn, "zenflows-sign"), + {:ok, raw_body} <- Map.fetch(conn.assigns, :raw_body) do + ctx + |> Map.put(:gql_user, user) + |> Map.put(:gql_sign, sign) + |> Map.put(:gql_body, raw_body) + end +end +end diff --git a/src/zenflows/web/router.ex b/src/zenflows/web/router.ex @@ -3,6 +3,8 @@ defmodule Zenflows.Web.Router do use Plug.Router +alias Zenflows.Web.MW + plug :match plug Plug.RequestId plug Plug.Logger @@ -10,7 +12,7 @@ plug Plug.Parsers, parsers: [{:json, json_decoder: Jason}, Absinthe.Plug.Parser], pass: ["*/*"], body_reader: {__MODULE__, :read_body, []} -plug :gql_context +plug MW.GQLContext plug :dispatch forward "/api", @@ -31,24 +33,6 @@ match _ do """) end -# Set the absinthe context with the data fetched from various headers. -defp gql_context(conn, _opts) do - ctx = - case get_req_header(conn, "zenflows-admin") do - [key | _] -> - %{gql_admin: key} - _ -> - with [user | _] <- get_req_header(conn, "zenflows-user"), - [sign | _] <- get_req_header(conn, "zenflows-sign") do - %{gql_user: user, gql_sign: sign} - else _ -> - %{} - end - end - - Absinthe.Plug.put_options(conn, context: ctx) -end - @doc false def read_body(conn, opts) do alias Plug.Conn