<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivy Markwell on Medium]]></title>
        <description><![CDATA[Stories by Ivy Markwell on Medium]]></description>
        <link>https://medium.com/@ivymarkwell?source=rss-85bd38496576------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*APnzs14wB-JpjZl28KoapQ@2x.jpeg</url>
            <title>Stories by Ivy Markwell on Medium</title>
            <link>https://medium.com/@ivymarkwell?source=rss-85bd38496576------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:00:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivymarkwell/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Standardizing data migrations in Elixir with Monarch]]></title>
            <link>https://medium.com/@ivymarkwell/standardizing-data-migrations-in-elixir-with-monarch-2ccb4cd98152?source=rss-85bd38496576------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ccb4cd98152</guid>
            <category><![CDATA[data-migration]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[oban]]></category>
            <dc:creator><![CDATA[Ivy Markwell]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-02-02T14:01:02.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgT5kO6Xg_qeqFn9xosJng.jpeg" /><figcaption>Real image of who’s waiting for you to finish verifying your data migration</figcaption></figure><p>If I had to guess, you’re probably using <em>at least</em> three different approaches to do data migrations in production today:</p><ul><li>You put data changes directly into an Ecto migration</li><li>You write one-off scripts, iex into production, and run them manually</li><li>You write Oban workers and enqueue them after a deploy</li></ul><p>At least, that’s been the case for me in my Elixir positions. And while this <em>works</em>, there’s never been a standard process for engineers to follow.</p><p>The other issue I’ve run into, is that these don’t scale particularly well. Ecto migrations block deploys, while one-off scripts and Oban jobs are entirely manual — easy to forget, hard to track, and tricky to rerun safely.</p><p>These are the issues that led my coworker, <a href="https://www.linkedin.com/in/yiiniiniin/">Chris Bailey</a> and I to create <a href="https://github.com/Vetspire-VSP/monarch">Monarch</a>. Monarch is an Oban powered process that automatically runs data migrations when your application starts.</p><h3>How Monarch Works</h3><p>Monarch provides a behaviour that defines the standard interface for your data migration jobs. We call any module that implements this behaviour a <em>Monarch job</em>.</p><p>Once you have your own Monarch jobs, Monarch uses a single entry point to discover and run them. That entry point is Monarch.run/2. When you call Monarch.run/2, Monarch:</p><ol><li>Scans your application for modules that implement the Monarch behaviour</li><li>Checks whether each job has already been run or is currently running</li><li>Automatically enqueues any jobs that still need to be processed using Oban</li></ol><p>No manual steps. No remembering. Your jobs run automatically 🎉</p><h3>What Is a Monarch Job?</h3><p>A Monarch job is simply a module that implements the Monarch behaviour. That behaviour is defined by two core functions:</p><ul><li><strong>query/0</strong><br> Returns a list of records that still need to be updated.<br> This function must be <em>idempotent </em>and should always return records that still need to be processed.</li><li><strong>update/1</strong><br> Takes the records returned by query/0 and performs the necessary updates.</li></ul><p>Monarch calls these function recursively. It runs query/0, passes the results to update/1 and then reruns query/0 to check if there are more records remaining. This continues until there are no more records left to be updated.</p><h3>Starting Monarch</h3><p>Since Monarch is built on top of Oban, your application must already have Oban installed and be configured with at least one queue.</p><p>Once that’s done, start Monarch by calling:</p><pre>Monarch.run(Oban, &lt;my_queue&gt;)</pre><ul><li>Oban is the Oban instance you want to use</li><li>&lt;my_queue&gt; is the default queue Monarch will use for data migrations</li></ul><p>You can call this run function from a release task or directly in application.ex—anywhere that ensures it runs automatically after a deploy.</p><h3>Writing Your First Monarch Job</h3><p>Once your using the Monarch.run/2 function your application is ready to start looking for Monarch jobs! You just need to write one.</p><p>Monarch includes a mix task to make getting started easy:</p><pre>mix monarch --monarch-path myapp/lib/myapp/workers/monarch my_monarch_module</pre><p>This generates a boilerplate module with the required callbacks:</p><pre>defmodule MyApp.Workers.Monarch.MyFirstMonarchJob do<br>  <a href="http://twitter.com/behaviour">@behaviour</a> Monarch</pre><pre>  @impl Monarch<br>  def skip, do: false</pre><pre>  @impl Monarch<br>  def scheduled_at, do: DateTime.utc_now()</pre><pre>  @impl Monarch<br>  def query do<br>    # Return a chunk of records that still need to be updated<br>    []<br>  end</pre><pre>  @impl Monarch<br>  def update(_records) do<br>    # Process the returned records<br>  end<br>end</pre><p>From now on, you only need to focus on the your data migration logic, which is all you wanted to do anyway.</p><h3>Simple Example: Backfilling Usernames</h3><p>Here’s a real-world example of using Monarch to backfill a newly added username field on an existing users table.</p><p>Assume we’ve just introduced this username column and want to make it a required<strong> </strong>field. Before we can enforce that constraint, we need to backfill existing users with to have a default value.</p><p>Our business requirements look like this:</p><ul><li>Every user must have a username</li><li>Usernames must be unique</li><li>The default username should be derived from the user’s first and last name</li><li>If multiple users share the same name, we append a number to ensure they are unique</li></ul><p>Below is what our Monarch job could look like.</p><pre>defmodule MyApp.Workers.Monarch.Backfill do<br>  <a href="http://twitter.com/behaviour">@behaviour</a> Monarch</pre><pre>  import Ecto.Query</pre><pre>  alias MyApp.Repo<br>  alias MyApp.Users.User</pre><pre>  @impl Monarch<br>  def skip, do: false</pre><pre>  @impl Monarch<br>  def scheduled_at, do: DateTime.utc_now()</pre><pre>  @impl Monarch<br>  def query do<br>    from(u in User,<br>      where: is_nil(u.username),<br>      limit: 100<br>    )<br>    |&gt; Repo.all()<br>  end</pre><pre>  @impl Monarch<br>  def update(users) when is_list(users) do<br>    Enum.each(users, fn user -&gt;<br>      base_username =<br>        [user.first_name, user.last_name]<br>        |&gt; Enum.join(&quot;&quot;)<br>        |&gt; String.downcase()</pre><pre>      username = unique_username(base_username)</pre><pre>      user<br>      |&gt; User.changeset(%{username: username})<br>      |&gt; Repo.update!()<br>    end)<br>  end</pre><pre>  defp unique_username(base_username, attempt \\ 0) do<br>    username =<br>      if attempt == 0, do: base_username, else: &quot;#{base_username}#{attempt}&quot;</pre><pre>    case Repo.get_by(User, username: username) do<br>      nil -&gt; username<br>      _ -&gt; unique_username(base_username, attempt + 1)<br>    end<br>  end<br>end</pre><p>Because query/0 only returns users without usernames, this job is safe to retry. Once all users are updated, Monarch marks the job as completed.</p><p>Please note, I don’t want to focus on the logic of this migration example itself but rather give you ideas on the kind of things you could do with Monarch.</p><h3>So why Monarch?</h3><p>We’ve been using Monarch in production for over a year now and I’ve found that it helps me stay focused on actually writing my data migration and not writing the thing that writes my migration.</p><ul><li><strong>Standardization</strong><br>Every data migration could follow the same pattern across the codebase.</li><li><strong>Automatic execution</strong><br>Migrations run automatically after deploys in every single environment and in every instance of production. I write my update one time.</li><li><strong>Secretly Oban</strong><br>Retries, monitoring, and job tracking come for free using tooling you already have.</li><li><strong>Idempotent</strong><br>Jobs are always safe to rerun, with no risk of duplicate updates.</li></ul><p>However, Monarch is currently at a 0.3.0 release and has a lot more improvements to come.</p><h3>Things to Consider</h3><p>If you’re looking for more information about Monarch, I’d highly suggest you go look at our library. It is open source.</p><p>There are a few important considerations worth calling out before adopting Monarch in your own application.</p><ul><li><strong>Race Conditions</strong><br>By default, Monarch enqueues all of its jobs into a single default Oban queue you define. If multiple Monarch jobs run concurrently and update the same table, this can cause race conditions.<br>For example, imagine two Monarch jobs running at the same time, both operating on the users table we updated from before but updating on different fields. If those jobs overlap, they may attempt to update the same records concurrently and could cause one job to overwrite the other. This can cause a Monarch job to believe it has been completed successfully even though its changes were later overwritten and undone.<br>To address this, Monarch allows individual jobs to define a custom queue via an optional callback in the behaviour. For tables that are frequently updated, I’d suggest you create a dedicated Oban queue with a global_limit: 1 and assign it to those relevant Monarch jobs.<br>Doing this ensures that jobs that could conflict are run one at a time and that any unrelated Monarch jobs can still continue running concurrently on the default queue.</li><li><strong>Jobs that never finish<br></strong>Monarch detects jobs that repeatedly return the same data without making progress and discards them. However, the job itself is still not considered completed.<br>This will cause a job to be reinserted on every deployment until it’s fixed or removed from the codebase.<br>For now, the simplest solution is to either delete the Monarch job or fix the problem so that it can be completed. Handling these “stuck” jobs is something we plan to address in the future.</li><li><strong>Rolling Back<br></strong>Currently, rolling back a Monarch job is manual. Again, I hope to add support for this soon but hopefully this is not an issue you are running into often. However, it is important to note that either the job cannot be rolled back or you would need to be prepared to roll it back manually.</li></ul><p>Thanks for reading! This was meant to be a short, fun article highlighting a library I helped build and how it could be useful for you. If you’re looking for more information about Monarch, I’d highly suggest you go look at our library. It is open source! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ccb4cd98152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing permission based authorization in Absinthe with custom GraphQL directives]]></title>
            <link>https://medium.com/@ivymarkwell/implementing-permission-based-authorization-in-absinthe-with-custom-graphql-directives-a4f96de72652?source=rss-85bd38496576------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f96de72652</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[absinthe]]></category>
            <dc:creator><![CDATA[Ivy Markwell]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 05:01:31 GMT</pubDate>
            <atom:updated>2025-06-24T18:50:43.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Fo5Njt2oVYn4EA2hzNbiiw.jpeg" /><figcaption>Who’s That User?</figcaption></figure><p>Quick disclaimer! Writing and learning about this topic was a challenge so this article will be a heavier read. However, I expect if you’ve found yourself here that you are either familiar with Absinthe or have an existing application with a similar authorization problem. With that being said, let’s get into it!</p><h3>The Problem</h3><p>Imagine the following query that’s exposed in GraphQL:</p><pre>query getUser($id: ID!) {<br>    getUser(id: $id) {<br>      id<br>      name<br>      address<br>    }<br>  }</pre><p>There are many complex actions this can be broken into. The naive question in a REST system might be: does the user making the request have permission to read the exposed user object?</p><p>In GraphQL we can get much more granular than just basic CRUD permissions. Does the user have access to read the user object? Does the user have access to read the exposed address field under the user object? What about any of the arguments being passed to our query? Does the user have access to pass the argument id in order to query a specific user?</p><p>I decided to <a href="https://hexdocs.pm/absinthe/Absinthe.Schema.Notation.html#directive/3-defining-a-directive">define my own custom Absinthe directive</a>. A directive would allow me to decorate my GraphQL schemas and grant control over user access as the schema resolves the requested fields.</p><p>If you aren’t familiar with GraphQL directives but you are using Absinthe, you likely have already worked with directives and haven’t even realized it! GraphQL offers built in directives that are used in Absinthe. For example:</p><pre>field :old_field, :string do<br>  deprecate &quot;Please use :new_field&quot;<br>end</pre><p>deprecate is a <a href="https://github.com/absinthe-graphql/absinthe/blob/v1.7.8/lib/absinthe/schema/prototype/notation.ex">built in directive that Absinthe</a> uses for you to mark that a field should no longer be used directly in the schema.</p><h3>Defining our directive</h3><p>In my case, directives would allow me to get very granular about the permissions a user needed in order to access a field. Let’s go back to our query example from before. Let’s say we wanted to define permissions around reading a user. However, it’s not that simple. Only certain users should be allowed to query a user, read a user, their name and address, and we want specific permissions to reflect that. So, the goal of this post is to define the following permissions: query_user, read_user, read_user_name, and read_user_address.</p><p>My Absinthe schema looks something like this:</p><pre>defmodule MyApp.Schema do<br>  use Absinthe.Schema<br>  <br>  object :user do<br>    field(:id, non_null(:id))<br>    field(:name, :string)<br>    field(:address, :string)<br>  end<br>  <br>  query do<br>    field :get_user, :user do<br>      arg(:id, non_null(:id))<br>    <br>      resolve(fn _, %{id: id}, _ -&gt;<br>        {:ok, UserResolver.get_user(id)}<br>      end)<br>    end<br>  end<br>end</pre><p>So I <a href="https://hexdocs.pm/absinthe/Absinthe.Schema.Notation.html#directive/3-applying-a-type-system-directive">defined a directive</a> that would allow me to pass permissions onto the GraphQL fields and objects themselves. <a href="https://hexdocs.pm/absinthe/Absinthe.Schema.Prototype.html">We do this by defining our own prototype schema and then exposing it as our </a><a href="https://hexdocs.pm/absinthe/Absinthe.Schema.Prototype.html">@prototype_schema in our Absinthe Schema file.</a></p><pre>defmodule MyApp.SchemaPrototype do<br>  @moduledoc &quot;&quot;&quot;<br>  Defines our custom schema directives.<br>  &quot;&quot;&quot;<br><br>  use Absinthe.Schema.Prototype<br><br>  @doc &quot;&quot;&quot;<br>  Authorization directive that allows us to pass a list of permissions to<br>  GraphQL fields and objects.<br>  &quot;&quot;&quot;<br>  directive :auth do<br>    arg(:permissions, list_of(:string))<br><br>    on([:field_definition, :object])<br><br>    expand(fn %{permissions: permissions}, node -&gt;<br>      %{node | __private__: Keyword.put(node.__private__, :permissions, permissions)}<br>    end)<br>  end<br>end</pre><p>This creates a custom Absinthe directive :auth that allows us to pass a list of string permissions as an argument on any GraphQL fields or objects we define. Then, we can expose our prototype_schema to our Absinthe schema file like this:</p><pre>defmodule MyApp.Schema do<br>  use Absinthe.Schema<br><br>  @prototype_schema MyApp.SchemaPrototype<br><br>  # query and mutation definitions...<br>end</pre><h3>Understanding directives</h3><p>If you’re wanting to understand more about the Absinthe directive itself, you’re going to have to read some Absinthe source code. You can follow along if you look at our :auth directive. First, we are using the <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/schema/prototype.ex">use Absinthe.Schema.Prototype</a> to access a macro Absinthe has defined for schema prototypes. When we add our directive all we are basically doing is importing the <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/schema/prototype/notation.ex">already defined directives code</a> and adding another one.</p><p>Then in the directive itself we are defining <a href="https://hexdocs.pm/elixir/1.12/Macro.html#expand/2">the expand</a> to <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/phase/document/directives.ex">alter the node that Absinthe is going to pass to us</a> when it applies our directive in the <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/pipeline.ex#L112">GraphQL pipeline</a>. Now we can focus on what we have access to alter in the node itself. If you look at the node Absinthe gives us, it has a type <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/blueprint.ex#L55">Blueprint.node_t()</a> . There you can find the following definitions for our node:</p><pre>  @type node_t ::<br>          t()<br>          | Blueprint.Directive.t()<br>          | Blueprint.Document.t()<br>          | Blueprint.Schema.t()<br>          | Blueprint.Input.t()<br>          | Blueprint.TypeReference.t()</pre><p>Depending what your directive is allowed on will determine what type you’re accessing in your expand/2 function. Since our directive is only allowed on field_definition and object we are using the <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/blueprint/schema/object_type_definition.ex">object type definition</a> and the <a href="https://github.com/absinthe-graphql/absinthe/blob/main/lib/absinthe/blueprint/schema/field_definition.ex">field definition</a>. Either way, our nodes have access to a few common fields we can alter so we can pass information down to our middleware later; __private__ being one of them. We are guaranteed this is for <a href="https://hexdocs.pm/absinthe/search.html?q=__private__">internal use only</a> and shouldn’t be altered by Absinthe itself. So we’re able to add a string of permissions on these nodes using the __private__ field that we will handle later in our middleware when our fields are getting resolved.</p><p>TLDR; We add a directive that has access to a node_t() . node_t() has access to a __private__ field that we can use to pass down information into our middleware later when GraphQL is resolving our fields.</p><p>😅Anyways! Now that our detour is over, let’s get into passing down our permissions so we can actually use them and start writing our authorization logic.</p><h3>Using the directive via middleware</h3><p>If you were paying attention earlier, what’s going to happen after Absinthe applies our directive is that the node we altered earlier is going to be passed down to our <a href="https://hexdocs.pm/absinthe/Absinthe.Middleware.html">middleware</a>. This is because as Absinthe attempts to resolve the fields the user is accessing, we are passing around a <a href="https://hexdocs.pm/absinthe/Absinthe.Resolution.html#t:t/0">Absinthe.Resolution</a> struct. If you look closely at the type for Resolution it has a definition field that is our node we altered earlier 👏.</p><p>Now that our directive is defined we can update our GraphQL fields from earlier to use our :auth directive with all the permissions we needed from before!</p><pre>defmodule MyApp.Schema do<br>  use Absinthe.Schema<br>  <br>  object :user do<br>    directive(:auth, permissions: [&quot;read_user&quot;])<br><br>    field(:id, non_null(:id))<br>    field(:name, :string, <br>      directives: [auth: [permissions: [&quot;read_user_name&quot;]]])<br>    field(:address, :string, <br>      directives: [auth: [permissions: [&quot;read_user_address&quot;]]])<br>  end<br>  <br>  query do<br>    field :get_user, :user, <br>      directives: [auth: [permissions: [&quot;query_user&quot;]]] do<br><br>      arg(:id, non_null(:id))<br><br>      resolve(fn _, %{id: id}, _ -&gt;<br>        {:ok, UserResolver.get_user(id)}<br>      end)<br>    end<br>  end<br>end</pre><p>Then we are going to create our own custom middleware MyApp.Middleware.Authorization to access our permissions and restrict user access. We can update our MyApp.Schema file again to use that middleware:</p><pre>defmodule MyApp.Schema do<br>  use Absinthe.Schema<br><br>  @prototype_schema MyApp.SchemaPrototype<br><br>  def middleware(middleware, _field, _object) do<br>    [MyApp.Middleware.Authorization | middleware]<br>  end<br><br>  # query and mutation definitions...<br>end</pre><p>Finally… our authorization logic. Let’s write our middleware that will be in charge of allowing users to gain access to the GraphQL fields.</p><pre>defmodule MyApp.Middleware.Authorization do<br>  @moduledoc &quot;&quot;&quot;<br>  Authorization middleware that verifies users have the necessary permissions to<br>  access specific GraphQL fields and objects.<br>  &quot;&quot;&quot;<br><br>  @behaviour Absinthe.Middleware<br><br>  alias Absinthe.Blueprint<br>  alias Absinthe.Type.Object<br><br>  def call(resolution, _config) do<br>    user = resolution.context.current_user<br>    user_permissions = get_in(user.permissions)<br><br>    # unauthorized_permissions = // Logic to check for missing permissions...<br><br>    if unauthorized_permissions == [] do<br>      resolution<br>    else<br>      Absinthe.Resolution.put_result(<br>        resolution,<br>        {:error,<br>          &quot;Unauthorized to perform the following action(s): #{Enum.join(unauthorized_permissions, &quot;, &quot;)}&quot;}<br>      )<br>    end<br>  end<br>end</pre><p>There’s not a lot going on here yet but you can assume I have my Absinthe project setup to pass around the correct current_user in my resolution context with an imaginary permissions field that contains a list of strings that defines the permissions that user has access to.</p><p>This middleware will check for any permissions that were passed on object or field_definition types and return an error to our resolution if we found the user doesn’t have the right permissions. This will happen as Absinthe resolves each of the fields the user is accessing. Let’s go back to the first query I showed to see how this works.</p><p>As Absinthe resolves the fields in the getUser query, the middleware is triggered up to four times. The middleware can be triggered once for the top level query itself, :get_user, and once for each field being queried, i.e. id, name and address. This matters because depending on what’s currently being resolved will determine what we have access to in our middleware at the time.</p><p>The first thing that will resolve and our middleware will check is the top level query itself, :get_user which has the query_user permission defined using our directive.</p><p>Our <a href="https://hexdocs.pm/absinthe/Absinthe.Resolution.html#module-contents">resolution.definition</a> that is getting passed into our middleware will look something like this:</p><pre>%Absinthe.Blueprint.Document.Field{<br>  name: &quot;getUser&quot;,<br>  arguments: [<br>    %Absinthe.Blueprint.Input.Argument{<br>      name: &quot;id&quot;,<br>      schema_node: %Absinthe.Type.Argument{<br>        identifier: :id,<br>        name: &quot;id&quot;,<br>        __private__: [],<br>        ...remaining_fields<br>      },<br>    }<br>  ],<br>  schema_node: %Absinthe.Type.Field{<br>    identifier: :get_user,<br>    name: &quot;get_user&quot;,<br>    __private__: [permissions: [&quot;query_user&quot;]],<br>    ...remaining_fields<br>  },<br>  ...remaining_fields<br>}</pre><p>It’s important to note that while we are only looking at a query that does not have any permissions on its arguments, that we could have added a permission to an argument for the field, like :id. This matters a lot more when we start considering mutations that could be passing arguments we don’t want to give a user access to. Imagine we had an update_user mutation and we wanted a permission allowing only certain users to update the :address. We could add a directive on the argument and it would be in our resolution definition like the above example. We will come back to this in a minute.</p><p>For now, let’s focus on getting our query_user permission and checking that the user has it!</p><pre>defp field_permissions_unauthorized(resolution, user_permissions) do<br>  resolution.definition.schema_node.__private__<br>  |&gt; Keyword.get(:permissions, [])<br>  |&gt; Enum.reject(fn permission -&gt;<br>    has_permission?(permission, user_permissions)<br>  end)<br>end<br><br>def has_permission?(_, nil), do: false<br><br>def has_permission?(permission, user_permissions) do<br>  Enum.find_value(user_permissions, false, fn user_permission -&gt;<br>    user_permission == permission<br>  end)<br>end</pre><p>Hopefully the above code is really straight forward to reason about. Using the snippet of our resolution.definition from above, in order to get the permissions off the top level query (or mutation) we access the schema_node.__private__ and pluck off any permissions we find! Then, we have a helper function has_permission?/2 that is going to be reused to determine if our current user has the permission we parsed out from our node. In this example, we would find the permission query_user defined and check to verify that our current user has that permission. If they didn’t, we would return that permission back from our function so we can use it in our error message from before.</p><p>Now that we have our first permission verified, let’s circle back to our arguments’ permissions discussion.</p><pre>defp argument_permissions_unauthorized(resolution, user_permissions) do<br>  resolution.definition.arguments<br>  |&gt; Blueprint.find(fn<br>    %Absinthe.Blueprint.Input.Field{<br>      schema_node: %Absinthe.Type.Field{__private__: [permissions: permissions]}<br>    } -&gt;<br>      Enum.any?(permissions, fn permission -&gt;<br>        not has_permission?(permission, provider_permissions)<br>      end)<br><br>    _ -&gt;<br>      false<br>  end)<br>  |&gt; case do<br>    %Absinthe.Blueprint.Input.Field{<br>      schema_node: %Absinthe.Type.Field{__private__: [permissions: permissions]}<br>    } -&gt;<br>      Enum.reject(permissions, fn permission -&gt;<br>        has_permission?(permission, provider_permissions)<br>      end)<br><br>    _ -&gt;<br>      []<br>  end<br>end</pre><p>You can see this function is a little bit more complex than when we were just accessing the permissions on the query itself. Here we are accessing the arguments passed to our query and using Absinthe’s <a href="https://hexdocs.pm/absinthe/Absinthe.Blueprint.html#find/2">Blueprint.find/2</a> to find any arguments that have permissions defined on them. We do this by pattern matching on the schema_node for our Blueprint.Input.Field and checking if the field for the argument has any permissions defined on it. Then if we find a field that has permissions defined on it, we verify if the current user does not have any of those permissions. We do this because Blueprint.find/2 will return the first field it finds that returns true. So we want to return any field that does not have the necessary permissions. After our Blueprint.find/2 returns a field that is missing permissions, we then iterate through it one more time so that we only return the permissions that were missing from our function.</p><p>This does mean that if there were multiple arguments with permissions defined the user didn’t have access to, there would only be one permission returned in our error. However, this is enough to make sure our endpoint is secure. Regardless of whether a user does not have access to pass one argument or many, since the user does not have access to something being resolved on the top level query, the rest of the query would halt. The same would apply to any mutations that had arguments. If the user doesn’t have access to an argument they are trying to mutate, the mutation will fail before an update can happen.</p><p>Also, you might be thinking that I didn’t define my directive to be used on argument_definition types and you would be correct! Currently my directive is setup so the only arguments that would be passed with permissions would be from an input_object. Any fields with permissions under an input_object would be caught the same way in my argument_permissions_unauthorized/2 function. We could iterate on this later so we can pass directives directly on the arg itself but this functionality is enough for me for now.</p><p>Moving on, the next thing that gets resolved in our query are the fields of the object that are getting accessed. The first field to get resolved is id. Let’s take a look at what our resolution.definition looks like when we are resolving id.</p><pre>%Absinthe.Blueprint.Document.Field{<br>  name: &quot;id&quot;,<br>  schema_node: %Absinthe.Type.Field{<br>    identifier: :id,<br>    name: &quot;id&quot;,<br>    __private__: [],<br>    ...remaining_fields<br>  },<br>  parent_type: %Absinthe.Type.Object{<br>    identifier: :user<br>    name: &quot;User&quot;,<br>    fields: ...userFields,<br>    __private__: [__absinthe_referenced__: true, permissions: [&quot;read_user&quot;]],<br>    ...remaining_fields<br>  }<br>}</pre><p>Even though we don’t have any directives defined on the id field itself, there are 2 different things happening here that we could care about. The first is the permission that <em>could</em> have been on id. For example, when our name and address fields get resolved next they will both have permissions here like read_user_name and read_user_address. Any permissions defined on the fields themselves will get caught and verified in our field_permissions_unauthorized/2 function so we don’t need to do anything else here!</p><p>However, the second is that our field might have a parent object with restrictive permissions on it. Here you can see we have access to the parent_type which defines any permissions on the parent object of the field. In this case id has the read_user permission defined on it’s user parent object. So let’s deal with that.</p><pre>defp object_permissions_unauthorized(resolution, provider_permissions) do<br>  resolution.definition<br>  |&gt; Blueprint.find(fn<br>    %Absinthe.Blueprint.Document.Field{<br>      parent_type: %Object{__private__: private}<br>    } -&gt;<br>      Keyword.has_key?(private, :permissions)<br><br>    _ -&gt;<br>      false<br>  end)<br>  |&gt; case do<br>    %Absinthe.Blueprint.Document.Field{<br>      parent_type: %Object{__private__: private}<br>    } -&gt;<br>      permissions = Keyword.get(private, :permissions, [])<br><br>      Enum.reject(permissions, fn permission -&gt;<br>        has_permission?(permission, provider_permissions)<br>      end)<br><br>    _ -&gt;<br>      []<br>  end<br>end</pre><p>This is almost exactly the same as when we parsed out the argument’s permissions. The only difference here is that we are now looking at the resolution.definition to find any Blueprint.Document.Field with a parent_type that has permissions. In this scenario just like before when we were finding any arguments the user did not have permission to access, this function would return the read_user permission if the user did not have that permission.</p><p>…And that’s it! When looking for permissions on queries or mutations there are only a few things we care about:</p><ul><li>If there are any arguments with permissions defined (none from our query example)</li><li>Whether the field itself has a permission defined (query_user, read_user_name, read_user_address)</li><li>If any of the fields being accessed have a parent object with permissions defined (read_user)</li></ul><p>Now let’s put this all back together in our middleware call:</p><pre>def call(resolution, _config) do<br>  user = resolution.context.current_user<br>  user_permissions = get_in(user.permissions)<br><br>  # Unauthorized permissions found from arguments that were passed as input_object GraphQL fields<br>  unauthorized_argument_permissions =<br>    argument_permissions_unauthorized(resolution, user_permissions)<br><br>  # Unathorized permissions found from defined GraphQL fields<br>  unauthorized_field_permissions =<br>    field_permissions_unauthorized(resolution, user_permissions)<br><br>  # Unathorized permissions found from defined GraphQL objects<br>  unauthorized_object_permissions =<br>    object_permissions_unauthorized(resolution, user_permissions)<br><br>  unauthorized_permissions =<br>    unauthorized_argument_permissions ++<br>      unauthorized_field_permissions ++ unauthorized_object_permissions<br><br>  if unauthorized_permissions == [] do<br>    resolution<br>  else<br>    Absinthe.Resolution.put_result(<br>      resolution,<br>      {:error,<br>       &quot;Unauthorized to perform the following action(s): #{Enum.join(unauthorized_permissions, &quot;, &quot;)}&quot;}<br>    )<br>  end<br>end</pre><p>Our middleware will now verify the user has access to all necessary permissions defined from our directives and return an error message with any of the permissions it found that the user was unauthorized for.</p><h3>Conclusion</h3><p>There are lots of ways you can enforce permissions and this way might not feel like the most efficient for your use case. You could easily handle permissions in your resolver layer where you can check any necessary permissions at one time and return the error you want. There are also loads of libraries that can help you do this.</p><p>Another problem I want to call out is that we can’t always return all the errors at once the way this is currently written. Ideally we want to show the user one error message that includes all the permissions they are lacking so they can take action. Going back to our argument_permissions_unauthorized/2 function, our error when we are accessing unauthorized arguments will only ever contain the first argument it found that was lacking a permission.</p><p>Lastly, depending on where the resolution fails will determine what action the user succeeds in taking. For example, consider a mutation like update_user that requires specific update permissions. If the user has the update_user permission, the mutation itself will succeed even if the user lacks read access to the returned user object. In this scenario, the mutation executes but the requested fields in the response won’t be resolved, and the user will receive an unauthorized error for those fields. This is because of the order in which GraphQL resolves operations. It first resolves the mutation itself and runs the resolver function. Then after the resolver function has run for the mutation, the queried fields will attempt to resolve. It’s at this layer when the queried fields are resolving that the middleware would error, even though the mutation itself succeeded. This seems reasonable but it’s just something to note if you expect the mutation to fail even if the user has update access but not read access.</p><p>However all of those things being said, this directive is very powerful. It allows us to get very granular with how we define permissions without the engineer having to do additional leg work. All our permissions can be enforced through a one line change that we add directly to the GraphQL schema itself. It’s easy to write, easy to review and can give product owners the granularity they want for security access.</p><p>I hope this gives you some deeper insight on how you can utilize Absinthe directives in your system and as always, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f96de72652" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-side rendered HTML using Phoenix LiveView]]></title>
            <link>https://medium.com/@ivymarkwell/server-side-rendered-html-using-phoenix-liveview-25d9487cb65c?source=rss-85bd38496576------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d9487cb65c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[liveview]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <dc:creator><![CDATA[Ivy Markwell]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 16:34:10 GMT</pubDate>
            <atom:updated>2020-04-20T16:50:07.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3zVa7gitgik5q_OYOm_2g.jpeg" /><figcaption>“LiveView” television</figcaption></figure><p>After attending the 2019 Lone Star Elixir conference in Austin, Texas and hearing the release of Phoenix LiveView announced, I decided I wanted to jump on the train of dabbling in LiveView. At the time, a lot of the examples being released were mini games which is what initially inspired me to recreate <a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)">Minesweeper</a>! After reading this you should understand what LiveView is, know some of the advantages and disadvantages of server side rendered HTML, and have an insight into how I used LiveView to build a clone of Minesweeper.</p><h3>What is LiveView?</h3><p>LiveView is a <a href="https://hex.pm/packages/phoenix_live_view">hex library</a> for managing application state and delivering server rendered HTML. To understand the LiveView lifecycle, we’ll first take a look at the different <a href="https://hexdocs.pm/phoenix/templates.html">templates</a> used by a LiveView application.</p><p>There are <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-live-layouts">3 layouts</a> (templates that render other templates) that are now in a Phoenix application:</p><ul><li>the root layout, root.html.eex — this is the layout shared between LiveView and regular templates; this is rendered only on the initial request for the application and then is used to render other templates</li><li>the app layout, app.html.eex — this is the default template in Phoenix that lives outside of the LiveView library (meaning that it’s irrelevant in a strictly LiveView application)</li><li>the live layout, live.html.leex — this is the LiveView template that has access to the state of the application and is updated as apart of the LiveView request life cycle</li></ul><p>LiveView starts by rendering the root layout on the initial request, and then establishes a connection with the client through <a href="https://hexdocs.pm/phoenix/channels.html">Phoenix Channels</a>. phx- <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-bindings">bindings</a> defined in the live template dictate when events are fired off by the client, and then associated event handlers in the LiveView file will make appropriate updates to the application state. Anytime the state of the application is updated, LiveView will retrigger the render function that contains your live layout, index.html.leex and rerender the page for the user. Meaning you got yourself stateful Elixir rendered HTML.</p><p>Understanding LiveView for me really came down to these 3 files:</p><ul><li>router.ex — where we assign our LiveView and define the root layout for our application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qd9hZihawqZYwLli5LaGw.png" /><figcaption>`router.ex` file</figcaption></figure><ul><li>root.html.eex — our root layout. This is the view that will be rendered on the initial request of the application, create the client connection to the server via web sockets (this happens specifically in the app.js script), and also where the embeded LiveView layout will be rendered later using the &lt;%= @inner_content&gt; tag.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qetD22xhWGdQDQ44LkrrAA.png" /><figcaption>`root.html.eex` file</figcaption></figure><ul><li>*_live.ex — the “LiveView”. This is where the state of the application is iterated on and where the LiveView layout, .leex template extension, gets rendered using the render/1 function. render/1 can return inline HTML or an index.html.leex file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7skEA13qmFFGuO0-WYIQg.png" /><figcaption>`*_live.ex` file</figcaption></figure><h3>Recreating Minesweeper and implementing event handlers</h3><p>(You can checkout and play my Minesweeper game <a href="https://github.com/ivymarkwell/minesweeper">here</a>!)</p><p>The hardest part of writing my LiveView application had nothing to do with LiveView; it was figuring out the Minesweeper logic itself (let me know if you find any bugs!). All of the logic in some way involved implementing the event handlers to track the current state of the game and display it to the user.</p><p>In the *_live.ex file diagram above, I briefly mentioned that the mount/3 function will initialize the state of the application. The state in a LiveView is <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-assigns-and-liveeex-templates">stored in the socket as assigns.</a> Meaning that we can access a particular state key by using socket.assigns.state_key (in the LiveView itself) or by accessing it in the LiveView template with the notation @state_key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mujz9tJaEc_gDYH1xlqlg.png" /><figcaption>Minesweeper!</figcaption></figure><p>Let’s go through an example! A really simple feature is that clicking the face on the board will start a new game. In order to do this we need to add an event binding in our Live layout, index.html.leex, that will listen to click events, and also create the event handler in the LiveView, minesweeper_live.ex file itself that will update the state of our application to start the new game.</p><pre>// index.html.leex, live layout file<br>&lt;span phx-click=&quot;restart-game&quot; class=&quot;status &lt;%= <a href="http://twitter.com/game_status">@game_status</a> %&gt;&quot;/&gt;</pre><pre>// minesweeper_live.ex, the LiveView file<br>def handle_event(&quot;restart-game&quot;, _key, socket) do<br>   # randomly generate initial mines with random coordinates<br>   random_initial_x = Enum.random(1..@rows)<br>   random_initial_y = Enum.random(1..@columns)<br>   <br>   new_socket = <br>      socket<br>      |&gt; new_game(random_initial_x, random_initial_y)</pre><pre>   {:noreply, new_socket}<br>end</pre><p>To keep things simple, we can determine whether we’ve started a new game by looking only at the @game_status socket value. @game_status is one of the many state keys that I implemented in my mount/3 function that were initialized when the page was rendered. If the @game_status value is “dead”, meaning the user has lost the game, then we will see the frowny face. When the user starts a new game, the value should get updated to “alive” and the face should return to a happy face.</p><p>Using <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-bindings">bindings</a> we can do this really easily. LiveView uses the phx-click binding to listen to click events and send them to the server. In my LiveView layout, I define the phx-click=&quot;restart-game&quot; binding on the &lt;span&gt; wrapping the face, so that when the user clicks the face an event is fired. Then, in my LiveView file there is an equivalent event handler, handle_event(&quot;restart-game&quot;) that will receive the event and start a new game!</p><p>Whenever we’re initializing or updating the state of our application we always return the socket with our new state attributes using the assign/2 and assign/3 function helpers. The assign function helpers take in the existing socket and a list of key/value state attributes and return the updated socket. So in the above code snippet, new_game/3 is actually just a function that returns the output of the assign/3 function with the new state attributes like this:</p><pre>defp new_game(socket, _, _) do<br>   assign(socket,<br>      game_status: &quot;alive&quot;, <br>      ...<br>   )<br>end</pre><p>And just like that, we’ve created a click event handler that will start a new game!</p><h3>Advantages and Disadvantages</h3><p>Let’s start off by saying LiveView is super fast. Not only because of the persistent client connection but LiveView also uses DOM-diffing. When the state is updated and the page is rerendered, LiveView uses DOM-diffing to update the page. This prevents the entire page from being rerendered and instead only the parts of the DOM that have been updated.</p><p>LiveView is also nice when you don’t want to have to manage both the client and the server. By no means is LiveView a replacement for Javascript frameworks that offer more complex interfaces, however there are instances where you want to enable real-time user interaction without the large overhead of a framework. This gives Elixir developers the option to create interactive applications without having to write or manage any Javascript.</p><p>Ironically, LiveView’s best use cases are usually <em>not</em> games. In fact, LiveView is a little unnecessary in these cases because we’re making server requests when we might not need to. In my Minesweeper example, I could have written this just as a simple Javascript application with no concept of a backend. LiveView would have been more useful in this instance if I had created score keeping. This would have allowed me to update scores in real time for users. As Chris McCord said, LiveView’s best uses cases can be seen in</p><blockquote>simple real-time updates, client-side style validations with immediate feedback, [and] autocomplete inputs</blockquote><p>Lastly, LiveView has no offline capacity and could be a lot of demand on your host provider. Remember, every instance of your application will be creating a unique connection from the client which after many connections can either cause your application to lag or end up just costing you money from your provider.</p><p>There are a lot of helpful <a href="https://github.com/ivymarkwell/phoenix-liveview-counter-tutorial">step by step tutorials</a> on how to get your first LiveView application up and running. Most of the work will be making your own unique application by updating the LiveView template to create the view you want and implementing the event handlers that will update your state.</p><p>LiveView is still under active development and so unfortunately some guides are already becoming outdated. The best way to keep up to date is to follow the <a href="https://github.com/phoenixframework/phoenix_live_view/blob/master/CHANGELOG.md">changelogs</a>. There’s already hype (mostly me) around the new command, <a href="https://github.com/phoenixframework/phoenix/pull/3680">mix phx.new --live</a>, which will allow users to quickly initialize a LiveView application. Hopefully as more updates come out this makes starting your own LiveView project even easier.</p><p>I hope you’re all staying safe during these hard times! Let me know if you have any feedback in the comments below! I read a lot of other great articles that helped solidify my understanding of LiveView and am really grateful Elixir has such an amazing community to learn. As always, you can follow me on <a href="https://medium.com/@ivymarkwell">Medium</a> and <a href="https://github.com/ivymarkwell">Github</a> to see what else I’m working on and thanks for reading. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d9487cb65c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a custom UserConfirmation modal with the React Router Prompt]]></title>
            <link>https://javascript.plainenglish.io/creating-a-custom-userconfirmation-modal-with-the-react-router-prompt-dc1faa5a65a0?source=rss-85bd38496576------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc1faa5a65a0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ivy Markwell]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 14:42:20 GMT</pubDate>
            <atom:updated>2020-07-27T02:19:49.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing a custom UserConfirmation modal with the React Router Prompt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYSWM1q3d5jGuZxGDK6iwQ.jpeg" /><figcaption>A person up in arms about wanting custom modals in their Prompt component</figcaption></figure><p>This is a short walkthrough on how to use React-Router’s v5 Prompt component to replace the built in user confirmation window object with your own custom UserConfirmation modal.</p><p>There is another really <a href="https://medium.com/@michaelchan_13570/using-react-router-v4-prompt-with-custom-modal-component-ca839f5faf39">good article</a> about blocking the navigation to prevent the default modal so that we can render our own custom component instead. They briefly mention an alternative method that involves utilizing BrowserRouter and the getUserConfirmation prop, which is exactly the solution this post covers!</p><h3>Briefly Behind the Scenes</h3><p>Without going into too much detail, essentially you can trace the <a href="https://github.com/ReactTraining/react-router/blob/v5.0.0/packages/react-router/modules/Prompt.js">Prompt</a> component all the way through <a href="https://github.com/ReactTraining/react-router/blob/v5.0.0/packages/react-router/modules/RouterContext.js">RouterContex</a>t, <a href="https://github.com/ReactTraining/react-router/blob/v5.0.0/packages/react-router/modules/Router.js">Router</a> and <a href="https://github.com/ReactTraining/react-router/blob/v5.0.0/packages/react-router-dom/modules/BrowserRouter.js">BrowserRouter</a>.</p><p>BrowserRouter is where the magic begins. Specifically where the history prop is created on <a href="https://github.com/ReactTraining/react-router/blob/v5.0.0/packages/react-router-dom/modules/BrowserRouter.js">line 11</a>. react-router uses <a href="https://github.com/ReactTraining/history/blob/v4.10.0/modules/createBrowserHistory.js">createBrowserHistory</a> to create our rendered history prop as an extension of the window.history that’s available in any browser. If you look in createBrowserHistory, you’ll also see the final layer of our confirmation window which comes from the initialization of getUserConfirmation from getConfirmation defined in <a href="https://github.com/ReactTraining/history/blob/v4.10.0/modules/DOMUtils.js">DomUtils</a>. This is where the default modal gets defined as a window object.</p><pre>export function getConfirmation(message, callback) {                            <br>   callback(window.confirm(message));<br>}</pre><h3>Creating our Custom UserConfirmation modal</h3><p>Since we are opting out of the window object and replacing it with our own custom component, we not only need to render a nicer modal but we also need to include all of the functionality for canceling and confirming the callback.</p><p>Remember that getUserConfirmation is initialized in BrowserRouter and is what determines what our confirmation modal displays. So wherever you’re initializing your application with BrowserRouter is where we’re going to pass our custom component into the getUserConfirmation prop.</p><pre>&lt;BrowserRouter <br>   getUserConfirmation={(message, callback) =&gt;  <br>      UserConfirmation(message, callback)}&gt; // our custom component<br>    &lt;YourAwesomeApp /&gt;<br>&lt;/BrowserRouter&gt;</pre><p>And you’re ready to go! You’re now overwriting the default window component and rendering your own custom UserConfirmation (even if it might not exist yet).</p><p>So let’s make it happen!</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import { Dialog } from &quot;evergreen-ui&quot;</pre><pre>const UserConfirmation = (message, callback) =&gt; {<br>   const container = document.createElement(&quot;div&quot;);<br>   container.setAttribute(&quot;custom-confirmation-navigation&quot;, &quot;&quot;);<br>   document.body.appendChild(container);</pre><pre>const closeModal = (callbackState) =&gt; {<br>      ReactDOM.unmountComponentAtNode(container);<br>      document.body.removeChild(container);<br>      callback(callbackState);<br>   };</pre><pre>   ReactDOM.render(<br>      &lt;Dialog<br>         cancelLabel=&quot;Cancel&quot;<br>         confirmLabel=&quot;Confirm&quot; <br>         isShown={true}<br>         onCacel={() =&gt; closeModal(false)}<br>         onConfirm={() =&gt; closeModal(true)}         <br>         title=&quot;Warning&quot;<br>      &gt;<br>       {message}<br>      &lt;/Dialog&gt;,<br>   container<br>  );<br>};</pre><pre>export default UserConfirmation;</pre><p>There are a few key things that we needed to happen in our custom component besides the UI. Since BrowserRouter and our custom component is rendered a layer above where our normal application is rendered, we start by initializing a container that we use to directly render the modal. Then we actually define what the container is rendering.</p><p>This is where we create the functionality of closing the modal through either a cancel or confirm action. In our closeModal function we unmount our manually rendered component and either push the user to the next location or stay at the location whether the Prompt was triggered. Fortunately, the callback function that is passed from Prompt makes sending the user to the next location or staying on the page really simple for us. All we need to pass callback is a boolean that tells us whether the user wants to proceed with going to their next location or doesn’t. So, when the user clicks “Cancel” we can call callback(false) and likewise when they click “OK” we call callback(true).</p><p>And that’s it! You’re done.</p><h3>But I want more than a message and a callback</h3><p>This is the part where most people would choose another solution because they want additional customization of the modal that go outside the two props that are given to us.</p><p>Sadly, that is a legitimate concern. We can attempt to alleviate this a little by a manipulating our message prop. Our Prompt component will only accept a string into message. So what we can do here is pass in a stringified JSON object with key-value pairs of things we’d like to have additional control over and then parse them out later.</p><pre>&lt;Prompt<br>   when={when}<br>   message={<br>      JSON.stringify(<br>         `{<br>           &quot;confirmText&quot;: &quot;Continue&quot;, <br>           &quot;messageText&quot;: &quot;It looks like you might have some unsaved  <br>                       changes! Are you sure you want to continue?&quot;,<br>           &quot;cancelText&quot;: &quot;Do not Continue&quot;<br>          }`   <br>      )<br>   }<br>/&gt;</pre><p>Then in our UserConfirmation modal instead of using message directly to display text we need to create a textObj that we use to reference our customized text keys.</p><pre>const textObj = JSON.parse(message);</pre><pre>&lt;Dialog<br>   cancelLabel={textObj.cancelText}<br>   confirmLabel={textObj.confirmText}   <br>   isShown={true}<br>   onCacel={() =&gt; closeModal(false)}<br>   onConfirm={() =&gt; closeModal(true)}<br>   title=&quot;Warning&quot;<br>&gt;<br>   {textObj.messageText}<br>&lt;/Dialog&gt;</pre><p>Now we’re at least going beyond a one dimensional modal that only allows us to customize the prompt message displayed to the user. Similarly, you could use the message prop to conditionally determine what to render. If we hadn’t passed for example a cancelText, then in our Evergreen <a href="https://evergreen.segment.com/components/dialog">Dialog</a> we could choose to set hasCancel to false so we’re only rendering a confirm button and not a close icon.</p><p>If you have any questions or feedback please leave a comment below! You can follow me on <a href="https://medium.com/@ivymarkwell">Medium</a> and <a href="https://github.com/ivymarkwell">Github</a> to see more fun stuff I’m working on. Special thanks to <a href="https://medium.com/u/f27d2add6165">Joerg Baier</a> for helping me work through and understand this solution and many of my other coworkers at <a href="https://rabbet.com/">Rabbet</a> for giving me helpful feedback on this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc1faa5a65a0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/creating-a-custom-userconfirmation-modal-with-the-react-router-prompt-dc1faa5a65a0">Creating a custom UserConfirmation modal with the React Router Prompt</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and deploying your first Hugo site to Github pages]]></title>
            <link>https://medium.com/@ivymarkwell/creating-and-deploying-your-first-hugo-site-to-github-pages-1e1f496cf88d?source=rss-85bd38496576------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1f496cf88d</guid>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[static-site-generator]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Ivy Markwell]]></dc:creator>
            <pubDate>Mon, 30 Apr 2018 03:00:29 GMT</pubDate>
            <atom:updated>2022-08-21T05:18:26.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDKgDXTBKX3z7x6ij5Z7xQ.jpeg" /><figcaption>A local duck I photographed recently</figcaption></figure><p>This is a comprehensive guide for creating your first static site using Hugo and hosting it on GitHub pages.</p><h3><strong>Creating your site</strong></h3><p>First, make sure you have <a href="https://gohugo.io/getting-started/installing/">Hugo</a> installed on your machine.</p><p>Now you can run these commands to make your first site.</p><pre>hugo new site hugo_site<br>cd hugo_site</pre><p>And there you go! You’ve created your first Hugo site. I mean, there’s nothing in it, but still! Let’s take a look.</p><pre>hugo server -D</pre><p>Your web server by default should be hosted at <a href="http://localhost:1313/">http://localhost:1313/.</a></p><p>There should be nothing here. We have to add themes, content, and lots of other fun stuff.</p><p>If you navigate to <a href="https://themes.gohugo.io/">Hugo,</a> you can see a complete list of themes that you can use to style your site. In my own personal Hugo site I, use <a href="https://themes.gohugo.io/minimal/">Minimal</a>, so let’s start there. First we need to initialize our Github repo, add the theme as a submodule in themes/minimal and copy the default config file for that theme.</p><pre>git init<br>git submodule add https://github.com/calintat/minimal.git themes/minimal<br>cp themes/minimal/exampleSite/config.toml .</pre><p>Now when you host your server, you should notice that you have the exact <a href="https://themes.gohugo.io/theme/minimal/">demo page</a> shown on the theme’s page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsJe92qbKtKv_BmrjvV_8Q.png" /><figcaption>Hugo’s Demo Page</figcaption></figure><p>Once that is set up, you should be able to customize it! If you navigate back to our Minimal theme’s documentation page you should find a small guide on using the parameters to customize the aesthetics of your site.</p><p>Once you’re done making your site <em>beautiful, </em>you can navigate back to Hugo’s <a href="https://gohugo.io/getting-started/quick-start/">Getting Started page</a> and generate actual content for your site. Generating content on your Hugo site is super important because Hugo won’t generate your subpages unless there is content to display (or if your content is in draft: true).</p><h3><strong>Deploying</strong></h3><p>This is where things get tricky.</p><p>Github pages doesn’t natively support Hugo like it does Jekyll (another SSG) so we’re going to have to create two Github repositories; one to hold your Hugo site and files, and one to hold the HTML files we have to generate for your actual Github page to read and render. Once you’ve created your remote repos on Github &lt;username&gt;.github.io and hugo_site we need to connect them to the site we just made.</p><p>First, let’s sync our repo and our code base and add &lt;github_username.github.io&gt; as a submodule to our existing repo just like our theme.</p><pre>git remote add origin <a href="/service/mailto:git@github.com">git@github.com</a>:&lt;github_username&gt;/hugo_site.git<br>git add .<br>git commit -m &quot;Initial commit for our Hugo site.&quot;<br>git submodule add git@github.com:&lt;github_username&gt;/&lt;github_username&gt;.github.io.git<br>git add .<br>git commit -m &quot;Initial commit for our generated HTML.&quot;<br>git push -u origin master</pre><p>Remember, this only pushes to hugo_site . We still need to generate our html pages for our &lt;github_username&gt; repo. Hugo already has a built in command, Hugo, that generates your files to a Public folder. We need to change our config.toml file to output our HTML files to our submodule &lt;github_username&gt;.github.io.</p><p>Open your config.toml:</p><pre>baseURL = &quot;<a href="https://nicoevergara.github.io/">https://&lt;github_username&gt;.github.io/</a>&quot;<br>languageCode = &quot;en-us&quot;<br>title = &quot;Minimal&quot;<br>theme = &quot;minimal&quot;<br>disqusShortname = &quot;username&quot; # delete this to disable disqus comments<br>googleAnalytics = &quot;&quot;<br>publishDir = &quot;&lt;github_username&gt;.github.io&quot;</pre><p>The default config.toml for the Minimal theme should look a little like this. However, here we added in publishDir. This tells Hugo where to create our HTML files from the content in our Hugo site.</p><p>Let’s generate them by running the following command:</p><pre>hugo</pre><p>And that should be it. Hugo already comes built with a simple command to generate the HTML from any of the customizable content in your site. If you look in your &lt;github_username&gt;.github.io folder now you should see HTML and CSS files, stuff that Github pages understands!</p><p>Before we finally deploy, we need to make sure our remotes our set up correctly one last time.</p><pre>cd &lt;github_username&gt;.github.io<br>git remote -v<br>&gt; origin <a href="/service/mailto:git@github.com">git@github.com</a>:&lt;github_username&gt;/&lt;github_username&gt;.github.io.git (fetch)<br>&gt; origin <a href="/service/mailto:git@github.com">git@github.com</a>:&lt;github_username&gt;/&lt;github_username&gt;.github.io.git (push)</pre><p>Now let’s host it!</p><pre>git add .<br>git commit -m &quot;Oh my goodness, I&#39;m hosting my first Hugo website!&quot;<br>git push origin master</pre><p>Go to your Github page &lt;github_username&gt;.github.io. You should see your very own custom Hugo site!</p><p>If you have any trouble please leave a comment below! You can follow me on <a href="https://medium.com/@ivymarkwell">Medium</a> and <a href="https://github.com/ivymarkwell">Github</a> to see more fun stuff I’m working on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1f496cf88d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>