<?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 Michael Munavu on Medium]]></title>
        <description><![CDATA[Stories by Michael Munavu on Medium]]></description>
        <link>https://medium.com/@michaelmunavu83?source=rss-c6ddf71c5b16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z5CiAUhfDBwLClW0Z8omFg.jpeg</url>
            <title>Stories by Michael Munavu on Medium</title>
            <link>https://medium.com/@michaelmunavu83?source=rss-c6ddf71c5b16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:26:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelmunavu83/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[A Beginners’ Intro to Graph Ql with Absinthe in Elixir]]></title>
            <link>https://medium.com/@michaelmunavu83/a-beginners-intro-to-graph-ql-with-absinthe-in-elixir-9951a6e91397?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/9951a6e91397</guid>
            <category><![CDATA[absinthe]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 06:02:34 GMT</pubDate>
            <atom:updated>2025-03-12T06:05:30.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginner’s Intro to Graph Ql with Absinthe in Elixir</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGby8NUENv7ig--VDEsm2g.png" /></figure><p>If you are reading this article , it probably means you wanted to understand Graphql and Absinthe better and ChatGPT or Claude gave you so much spaghetti code that you felt so lost in.</p><p>The title of this article is “A Beginner’s Intro..” and this is because I am the beginner in using Absinthe and not you, haha.</p><p>My short experience with Graphql is mindblowing to be honest , I have worked with Rest APIs for the longest time ever when building with elixir , as well as when I did write some code with Ruby.</p><p>Rest APIs are amazing , until you come across Graph ql.</p><p>Think of like this , say you want to list all posts in your database and you have an elixir backend , web frontend react and a flutter mobile app .</p><p>These you would say are 2 different frontends , mobile and web that need different types of data.</p><p>For Rest APIs you would need to create 2 different endpoints, one with just posts and the other with posts and comments preloaded.</p><p>With graphql , this can be done with one query and the mobile and react dev can choose what they want to access .</p><p>One can do</p><pre>{<br>  allPostsWithComments{<br>    id<br>    description<br>    <br>  }<br>  <br>}</pre><p>And the other</p><pre>{<br>  allPostsWithComments{<br>    id<br>    comments{<br>      id<br>      content<br>    }<br>    <br>  }<br>  <br>}</pre><p>Graph ql fixes underfetching and overfetching , you only get what you need , but all from one query/function.</p><p>Enough of the theory , let us get coding.</p><p>We will use <a href="https://hexdocs.pm/absinthe/overview.html">Absinthe</a>.</p><p>Absinthe is the GraphQL toolkit for Elixir, an implementation of the <a href="https://spec.graphql.org/">GraphQL specification</a> built to suit the language’s capabilities and idiomatic style.</p><p><strong>Create a new phoenix project</strong></p><pre>mix phx.new graphql</pre><p>Adding the absinthe dependancies to mix file</p><pre># mix.exs<br>{:absinthe, &quot;~&gt; 1.7&quot;},<br>{:absinthe_plug, &quot;~&gt; 1.5&quot;}</pre><p>Add the following code to your router.ex file to</p><pre> scope &quot;/&quot; do<br>    pipe_through :api<br><br>    forward &quot;/graphiql&quot;, Absinthe.Plug.GraphiQL,<br>      schema: Graphql.Schema,<br>      interface: :simple,<br>      context: %{pubsub: GraphqlWeb.Endpoint}<br>  end<br><br>  scope &quot;/api&quot; do<br>    pipe_through :graphql<br><br>    forward &quot;/&quot;, Absinthe.Plug, schema: Graphql.Schema<br>  end</pre><p>This Phoenix router configuration sets up two scopes for handling GraphQL requests using Absinthe. The root scope (&quot;/&quot;) passes requests through the :api pipeline and includes a <strong>GraphiQL</strong> interface at &quot;/graphiql&quot;, allowing developers to test GraphQL queries via a web-based tool. The GraphiQL plug uses Graphql.Schema as the schema, enables a simple interface, and includes a PubSub context for real-time updates. The &quot;/api&quot; scope, which goes through the :graphql pipeline, forwards all requests to Absinthe.Plug, making it the main endpoint for handling GraphQL queries and mutations defined in Graphql.Schema.</p><p>The main things to understand with elixir is a resolver and a schema.</p><p>The task of a resolver is to define functions for interacting and fetching data from the database and a schema for defining different objects that map to different tables in our database , we also define different functions in the schema that we will call in our graphql interface locally.</p><p>Whenever I am learning a new concept , my approach is to always to CRUD first , Create Read Update Delete.</p><p>So let us learn how to do CRUD with Absinthe.</p><p>First thing to do is to create context for our first table.</p><pre>mix phx.gen.context Posts Post posts title description</pre><p>To migrate the changes run</p><pre>mix ecto.migrate</pre><p><strong>Creating A Schema File</strong></p><pre># schema.ex<br>defmodule Graphql.Schema do<br>  use Absinthe.Schema<br>  alias Graphql.Resolver<br><br>  object :post do<br>    field :id, :id<br>    field :title, :string<br>    field :description, :string<br>  end<br><br>  query do<br>    @desc &quot;Get all posts&quot;<br><br>    field :all_posts, list_of(:post) do<br>      resolve(&amp;Resolver.all_posts/3)<br>    end<br>  end<br>end</pre><p>In the schema file , we will define the following block modules object and query at first.</p><p>The first object we have is a post , that has the attributes id , title and description.</p><p>In the query block , it is important to add a @desc , which is a description of that function.</p><p>In that field :all_posts , we are pointing to a function in the resolver file and calling a function taking 3 args called all_posts , let us create the resolver file.</p><p><strong>Create resolver.ex</strong></p><pre>defmodule Graphql.Resolver do<br>  alias Graphql.Posts<br><br>  def all_posts(_root, _args, _info) do<br>    {:ok, Posts.all_posts()}<br>  end<br>end</pre><p>Our resolver functions will take 3 paramters , the only one to care about is the middle one , which holds different arguments we will use in the future.</p><p>After ading this function run</p><pre>mix phx.server</pre><p>If you open</p><pre>localhost:4000/graphiql</pre><p>You will see such an interface</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlRB4pvb9nhn-AX8UOp65w.png" /></figure><p>On the left , you can click on query , then allPosts and you will see the different attributes you have access to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*MfEUA1lq_r41f24bwMCCvA.png" /></figure><p>How to get all posts , we add the following to the playground on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSSvu-Pj9Y2nM57-e_mXcQ.png" /></figure><pre>{<br>  allPosts{<br>    id<br>    title<br>    description<br>  }<br>}</pre><p>In layman’s here , we are calling the allPosts function and we want to fetch the id , title and description , here is the amazing thing with Absinthe and Graph Ql , let us say I only wanted the title , all I would do is now have</p><pre>{<br>  allPosts{<br>    description<br>  }<br>}</pre><p>And we now have .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3pl92hWo0fGXRE1YPsYoQ.png" /></figure><p>Amazing Right !.</p><p><strong>Let us now look at having query arguments</strong></p><ul><li><strong>A function to get a specific post !</strong></li></ul><p>The flow will always be resolver -&gt; schema .</p><p>So the first thing we do is create a function in our resolver , the basic idea is what we would normally do in ecto , get a post with its id , remember the arguments we mentioned , we will now use them here.</p><pre> def get_post(_root, %{id: id}, _info) do<br>    case Posts.get_post(id) do<br>      nil -&gt;<br>        {:error, &quot;Post not found&quot;}<br><br>      post -&gt;<br>        {:ok, post}<br>    end<br>  end</pre><p>In our argument , we will pass the id , now in the schema we will have.</p><pre>query do<br>    @desc &quot;Get a certain blog&quot;<br><br>    field :post, :post do<br>      arg(:id, non_null(:id))<br>      resolve(&amp;Resolver.get_post/3)<br>    end<br>  end</pre><p>The graphql function will now take the id as a parameter and we will call it as such in the playrgound</p><pre>{<br> post(id: 1){<br>     id <br>     title <br>     description<br>}<br>}</pre><p>And we get this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrqHJnnqCP4IwBUSZZRxeg.png" /></figure><p>We have dealt with the R in CRUD , now we move to create . With Create , Update and Delete Actions , these will be put in a block called mutations as they are mutating the data.</p><p><strong>CREATE A POST .</strong></p><p>We first create a function in our resolver that takes title and description as args and creates a post , same as we would do in ecto.</p><pre>def create_post(_root, %{title: title, description: description}, _info) do<br>    case Posts.create_post(%{title: title, description: description}) do<br>      {:ok, post} -&gt;<br>        {:ok, post}<br><br>      {:error, changeset} -&gt;<br>        {:error, changeset}<br>    end<br>  end</pre><p>And in our schema file we have</p><pre> mutation do<br>    @desc &quot;Create a post&quot;<br><br>    field :create_post, :post do<br>      arg(:title, non_null(:string))<br>      arg(:description, non_null(:string))<br>      resolve(&amp;Resolver.create_post/3)<br>  end</pre><p>Here we have function create_post which maps to createPost on graph ql which takes the title and description as arguments and creates a post.</p><p>How we call this on the graphql interface would be .</p><pre>mutation{<br>  createPost(title: &quot;My Post&quot; description: &quot;I am creating new post&quot;){<br>    id<br>    description<br>  }<br>}</pre><p>We call mutation , then the function we created with title and description as parameters and finally what we want to see from the updated record , in this case the id and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PW834OHas-XTkyEyYhoMCQ.png" /></figure><h4><strong>UPDATING A POST .</strong></h4><p>In our resolver we would now have</p><pre>def update_post(_root, %{id: id} = args, _info) do<br>    post = Posts.get_post(id)<br><br>    case Posts.update_post(post, args) do<br>      {:ok, post} -&gt;<br>        {:ok, post}<br><br>      {:error, changeset} -&gt;<br>        {:error, changeset}<br>    end<br>  end</pre><p>And in our schema under mutations block we have</p><pre>mutation do<br>@desc &quot;Update a post&quot;<br>    field :update_post, :post do<br>      arg(:id, non_null(:id))<br>      arg(:title, :string)<br>      arg(:description, :string)<br>      resolve(&amp;Resolver.update_post/3)<br>    end<br>end</pre><p>The update will take the id then a title and or description and will be called as such on the graph ql interface.</p><pre>mutation{<br>  updatePost(id: 5 , title: &quot;My Updated Post&quot;){<br>    id<br>    title<br>    description<br>    <br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbpOYyfIxpxxs9inLHWUVw.png" /></figure><p><strong>DELETING A POST .</strong></p><p>In our resolver we would have</p><pre>  def delete_post(_root, %{id: id}, _info) do<br>    case Posts.get_post(id) do<br>      nil -&gt;<br>        {:error, &quot;Post not found&quot;}<br><br>      post -&gt;<br>        case Posts.delete_post(post) do<br>          {:ok, post} -&gt; {:ok, post}<br>          _ -&gt; {:error, &quot;Could not delete post&quot;}<br>        end<br>    end<br>  end</pre><p>In our schema .</p><pre>mutation do<br> @desc &quot;Delete a post&quot;<br>    field :delete_post, :post do<br>      arg(:id, non_null(:id))<br>      resolve(&amp;Resolver.delete_post/3)<br>    end<br>end</pre><p>And we would call it as such on our interface.</p><pre>mutation{<br>  deletePost(id: 5){<br>    id<br>    title<br>    description<br>    <br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXVuQMh7vtv8EygFqQQmpQ.png" /></figure><p>As I said, this is a beginners’ Introduction , you can learn more here <a href="https://blog.appsignal.com/2023/05/16/an-introduction-to-absinthe-for-elixir.html">https://blog.appsignal.com/2023/05/16/an-introduction-to-absinthe-for-elixir.html</a> and You can see the code for the project I did here <a href="https://github.com/MICHAELMUNAVU83/graphql">https://github.com/MICHAELMUNAVU83/graphql</a> .</p><p>Thanks for reading through this , I hope you learnt a thing or 2 . You can find me on <a href="http://www.michaelmunavu.com/">www.michaelmunavu.com</a> and connect with me . Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9951a6e91397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CREATING CUSTOM ERROR PAGES IN PHOENIX.]]></title>
            <link>https://medium.com/@michaelmunavu83/creating-custom-error-pages-in-phoenix-25bda80196e3?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/25bda80196e3</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-liveview]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 05:43:42 GMT</pubDate>
            <atom:updated>2024-11-11T05:43:42.897Z</atom:updated>
            <content:encoded><![CDATA[<p>You are lying to yourself if you think you write perfect software or that your users are so smart that they will use the software you built as you intended them to , hard truth , you do not write perfect software and your users are not so smart , that means sometimes you will push bugs , probably on a friday that will break production , or push a broken link that goes to “/dashbob” instead of “/dashboard” .</p><p>If you have not set up custom error pages and someone goes to a bad route or something breaks , they will probably see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DH-c1VnrjcnqZVxMY8xp0A.png" /></figure><p>Or an Blank White Page With “Internal Server Error” , providing no way for the user to go back to a good page or provide any context into what might be going wrong , what is better , is such a page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yr_Zpk43o82jcQdnX4t4ZQ.png" /></figure><p>See , beautiful , tells the user what is happening and provides a way for them to go back to a good working page.</p><p>Let us now dive into the code , if you are on Phoenix and you go to a bad route , you will see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcBqD8-ZyVwMG_VqTU2X8Q.png" /></figure><p>For sure , we would not want our users to see this when using our systems , all the routes , that is shooting yourself in the foot, so let us fix this first.</p><p>Go to “config/dev.exs” and look for the line</p><pre>  debug_errors: true</pre><p>And replace it with</p><pre>  debug_errors: false</pre><p>This means , we now do not want any debug help in case of errors , so now the page you see will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DH-c1VnrjcnqZVxMY8xp0A.png" /></figure><p>Finally , we need to know style this page .</p><p>In “config/config.exs” for the Endpoint config , you see</p><pre> render_errors: [view: TenxWeb.ErrorView, accepts: ~w(html json), layout: false],</pre><p>So let us go to the “TenWebErrorView” file , where you see</p><pre>defmodule TenxWeb.ErrorView do<br>  use TenxWeb, :view<br><br>  def template_not_found(template, _assigns) do<br>    Phoenix.Controller.status_message_from_template(template)<br>  end<br>end</pre><p>All we need to do is match different error code pages to different files that we will create , let us start with a 404 Error page , customize the file to now have</p><pre>defmodule TenxWeb.ErrorView do<br>  use TenxWeb, :view<br><br>  # If you want to customize a particular status code<br>  # for a certain format, you may uncomment below.<br><br>  def render(&quot;404.html&quot;, _assigns) do<br>    render(&quot;404_page.html&quot;, %{})<br>  end<br><br>  # By default, Phoenix returns the status message from<br>  # the template name. For example, &quot;404.html&quot; becomes<br>  # &quot;Not Found&quot;.<br>  def template_not_found(template, _assigns) do<br>    Phoenix.Controller.status_message_from_template(template)<br>  end<br>end</pre><p>We have added</p><pre>def render(&quot;404.html&quot;, _assigns) do<br>    render(&quot;404_page.html&quot;, %{})<br>end</pre><p>The final piece of the puzzle is to create the “404_page” file and style it .</p><p>Create a folder called “error” in your “templates” folder , inside the “error” folder create a file “404_page.html.heex” .</p><p>Inside this page , you can customize your error page in HTML to be something as such</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjGfW_8iRGJ9tq0tzUgATA.png" /></figure><p>We can now have this for different error codes, for an internal server error, we would add</p><pre>def render(&quot;500.html&quot;, _assigns) do<br>    render(&quot;500_page.html&quot;, %{})<br>end</pre><p>Then add a coressponding “500_page” to be shown instead of “Internal Server Error”.</p><p>Thanks for hanging around with me as we learn how to add custom error pages in phoenix.</p><p>BTW , I am now. creating content around web development and elixir , you can check me out on Linkedin <a href="https://www.linkedin.com/in/michael-munavu/">https://www.linkedin.com/in/michael-munavu/</a> , Instagram <a href="https://www.instagram.com/michael_munavu">https://www.instagram.com/michael_munavu</a> and Tiktok <a href="https://www.tiktok.com/@michaelmunavu">https://www.tiktok.com/@michaelmunavu</a> and on my personal website www.michaelmunavu.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25bda80196e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AUTHENTICATE ELIXIR APIS WITH GUARDIAN AND BCRYPT]]></title>
            <link>https://medium.com/@michaelmunavu83/authenticate-elixir-apis-with-guardian-and-bcrypt-cd47f776f92d?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd47f776f92d</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 17:54:06 GMT</pubDate>
            <atom:updated>2024-01-08T17:54:06.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNl-iLDquTQBBofjZmEMwQ.png" /></figure><p>Authentication in Elixir and Phoenix is as easy as mix phx.gen.auth , which generates for you starter code with sign up , sign in , reset password and change email .</p><p>The helper mix phx.gen.auth is very good when building monolithic apps with elixir and phoenix , but when dealing with microservices , where elixir builds the api backend and you have a frontend in either react or vue or one of the million frontend frameworks , then we have to use jwts.</p><p>So what are JWTS, short for JSON web tokens , it is an ope standard protocol that defines a self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.</p><p>Let us break down authentication , what happens when someone logs in or signs up to a system .</p><p>Whenever this happens ,a unique token is created and stored in either the local storage or in the cookies , if this token is valid , the system says , I trust this person , show him this page .</p><p>Handling JWTS for api authentication will be the same , when we sign up or log in , we will be given a token , we can use this token to access certain routes .</p><p>How we do this is by passing this token in the Authorization Header of our http request .</p><p>We will see more of how this is done.</p><p>Let us get started by creating a new project .</p><pre>mix phx.new elixir_api_jwt</pre><p>move to your folder and configure your database in config/dev.exs</p><p>Set up your database with</p><pre> mix ecto.create</pre><p>What we first do is create boilerplate code for our Accounts model , our accounts table will have email and hash_password.</p><p>We will have this as json.</p><pre>mix phx.gen.json Accounts Account accounts email hash_password:text</pre><p>This creates view ,model and controller files for you.</p><p>We will configure the routes down below .</p><p>Before we migrate , we would want to have unique emails and passwords with a minimum of a certain length .</p><p>Let us open our migration files , these will be in priv/repo/migrations</p><p>Open the accounts migration file , you should have this</p><pre>defmodule ElixirApiJwt.Repo.Migrations.CreateAccounts do<br>  use Ecto.Migration<br><br>  def change do<br>    create table(:accounts) do<br>      add :email, :string<br>      add :hash_password, :text<br><br>      timestamps()<br>    end<br>  end<br>end</pre><p>Add this line at the end of the create block.</p><pre>create unique_index(:accounts, [:email])</pre><p>So now we have this</p><pre>defmodule ElixirApiJwt.Repo.Migrations.CreateAccounts do<br>  use Ecto.Migration<br><br>  def change do<br>    create table(:accounts) do<br>      add :email, :string<br>      add :hash_password, :text<br><br>      timestamps()<br>    end<br><br>    create unique_index(:accounts, [:email])<br>  end<br><br>  <br>end</pre><p>Let us also go to our schema files and add these validations</p><p>in lib/elixir_api_jwt/accounts/account.ex.</p><p>Let us change the changeset function to</p><pre> def changeset(account, attrs) do<br>    account<br>    |&gt; cast(attrs, [:email, :hash_password])<br>    |&gt; validate_required([:email, :hash_password])<br>    |&gt; unique_constraint(:email)<br>    |&gt; validate_format(:email, ~r/@/)<br>    |&gt; validate_length(:hash_password, min: 6)<br>  end</pre><h3>USING GUARDIAN AND BCYRPT</h3><blockquote>HASHING PASSWORDS</blockquote><p>Let us get into hashing passwords , hashing is necessary as it hides the real password , that way only the user can know his or her own password .</p><p>Before a user is created ,we first need to make sure their password is hashed .</p><p>We will be using bcrypt_elixir for this.</p><p>Add it to your mix.exs file in the list of dependencies</p><pre>{:bcrypt_elixir, &quot;~&gt; 3.0&quot;}</pre><p>And run</p><pre>mix deps.get</pre><p>We will now add a few functions to our accounts schema to ensure once a user is created , their password has to be hashed .</p><p>Let us look at how it currently works , we will be looking at the create_user function generated for us in lib/elixir_api/jwt</p><p>Let us jump into our Iex shell and test it out</p><pre>iex -S mix<br>alias ElixirApiJwt.Accounts<br>Accounts.create_account(%{email: &quot;test@gmail.com&quot; , hash_password: &quot;123456&quot;})<br>[debug] QUERY OK source=&quot;accounts&quot; db=60.1ms decode=4.8ms queue=5.1ms idle=400.6ms<br>INSERT INTO &quot;accounts&quot; (&quot;email&quot;,&quot;hash_password&quot;,&quot;inserted_at&quot;,&quot;updated_at&quot;) VALUES ($1,$2,$3,$4) RETURNING &quot;id&quot; [&quot;test@gmail.com&quot;, &quot;123456&quot;, ~N[2024-01-08 16:04:19], ~N[2024-01-08 16:04:19]]<br>↳ anonymous fn/4 in :elixir.eval_external_handler/1, at: src/elixir.erl:376<br>{:ok,<br> %ElixirApiJwt.Accounts.Account{<br>   __meta__: #Ecto.Schema.Metadata&lt;:loaded, &quot;accounts&quot;&gt;,<br>   id: 1,<br>   email: &quot;test@gmail.com&quot;,<br>   hash_password: &quot;123456&quot;,<br>   inserted_at: ~N[2024-01-08 16:04:19],<br>   updated_at: ~N[2024-01-08 16:04:19]<br> }}<br></pre><p>As you can see , it gets into our database with the actual password , that is not good , let us work on hashing it .</p><p>In our context file , lib/elixir_api_jwt/accounts/accounts.ex.</p><p>Add these 2 private functions</p><pre> defp put_password_hash(<br>         %Ecto.Changeset{valid?: true, changes: %{hash_password: hash_password}} = changeset<br>       ) do<br>    change(changeset, hash_password: Bcrypt.hash_pwd_salt(hash_password))<br>  end<br><br>  defp put_password_hash(changeset), do: changeset</pre><p>Now we will add this function to the changeset function as such</p><pre>def changeset(account, attrs) do<br>    account<br>    |&gt; cast(attrs, [:email, :hash_password])<br>    |&gt; validate_required([:email, :hash_password])<br>    |&gt; unique_constraint(:email)<br>    |&gt; put_password_hash()<br>end</pre><p>Now the whole file looks as</p><pre>defmodule ElixirApiJwt.Accounts.Account do<br>  use Ecto.Schema<br>  import Ecto.Changeset<br><br>  schema &quot;accounts&quot; do<br>    field :email, :string<br>    field :hash_password, :string<br><br>    timestamps()<br>  end<br><br>  @doc false<br>  def changeset(account, attrs) do<br>    account<br>    |&gt; cast(attrs, [:email, :hash_password])<br>    |&gt; validate_required([:email, :hash_password])<br>    |&gt; unique_constraint(:email)<br>    |&gt; validate_format(:email, ~r/@/)<br>    |&gt; validate_length(:hash_password, min: 6)<br>    |&gt; put_password_hash()<br>  end<br><br>  defp put_password_hash(<br>         %Ecto.Changeset{valid?: true, changes: %{hash_password: hash_password}} = changeset<br>       ) do<br>    change(changeset, hash_password: Bcrypt.hash_pwd_salt(hash_password))<br>  end<br><br>  defp put_password_hash(changeset), do: changeset<br>end</pre><p>This function now hashes the password for us before getting into the database .</p><p>Let us now jump into Iex and try it again</p><pre>recompile<br>Accounts.create_account(%{email: &quot;test2@gmail.com&quot; , hash_password: &quot;123456&quot;})<br>[debug] QUERY OK source=&quot;accounts&quot; db=43.6ms queue=3.1ms idle=278.7ms<br>INSERT INTO &quot;accounts&quot; (&quot;email&quot;,&quot;hash_password&quot;,&quot;inserted_at&quot;,&quot;updated_at&quot;) VALUES ($1,$2,$3,$4) RETURNING &quot;id&quot; [&quot;test2@gmail.com&quot;, &quot;$2b$12$RJaGpf8Ka5wFA1kJbbogWuvcociL0lJXqsz1DVhGNZqsE1H7W85cO&quot;, ~N[2024-01-08 16:10:26], ~N[2024-01-08 16:10:26]]<br>↳ anonymous fn/4 in :elixir.eval_external_handler/1, at: src/elixir.erl:376<br>{:ok,<br> %ElixirApiJwt.Accounts.Account{<br>   __meta__: #Ecto.Schema.Metadata&lt;:loaded, &quot;accounts&quot;&gt;,<br>   id: 2,<br>   email: &quot;test2@gmail.com&quot;,<br>   hash_password: &quot;$2b$12$RJaGpf8Ka5wFA1kJbbogWuvcociL0lJXqsz1DVhGNZqsE1H7W85cO&quot;,<br>   inserted_at: ~N[2024-01-08 16:10:26],<br>   updated_at: ~N[2024-01-08 16:10:26]<br> }}<br></pre><p>Now as you can see , we have</p><pre>hash_password: &quot;$2b$12$RJaGpf8Ka5wFA1kJbbogWuvcociL0lJXqsz1DVhGNZqsE1H7W85cO&quot;,</pre><p>We have now handled handling.</p><p>Let us move into authentication with guardian.</p><blockquote>AUTHENTICATION WITH GUARDIAN</blockquote><p>Guardian is a token-based authentication library for use with Elixir applications.</p><p>We add this to our mix file</p><pre><br>{:guardian, &quot;~&gt; 2.0&quot;},</pre><p>And run</p><pre>mix deps.get</pre><p>You can follow the documentation for setting up guardian here</p><p><a href="https://github.com/ueberauth/guardian">https://github.com/ueberauth/guardian</a> .</p><p>In order to leverage Guardian we’ll need first create an “implementation module” which includes Guardian’s functionality and the code for encoding and decoding our token’s values. To do this, create a module that uses Guardian and implements the subject_for_token/2 and resource_from_claims/1 function.</p><p>in your lib/elixir_api_jwt folder create a file called guardian.ex and have</p><pre>defmodule ElixirApiJwt.Guardian do<br>  use Guardian, otp_app: :elixir_api_jwt<br><br>  def subject_for_token(%{id: id}, _claims) do<br>    # You can use any value for the subject of your token but<br>    # it should be useful in retrieving the resource later, see<br>    # how it being used on `resource_from_claims/1` function.<br>    # A unique `id` is a good subject, a non-unique email address<br>    # is a poor subject.<br>    sub = to_string(id)<br>    {:ok, sub}<br>  end<br><br>  def subject_for_token(_, _) do<br>    {:error, :reason_for_error}<br>  end<br><br>  def resource_from_claims(%{&quot;sub&quot; =&gt; id}) do<br>    # Here we&#39;ll look up our resource from the claims, the subject can be<br>    # found in the `&quot;sub&quot;` key. In above `subject_for_token/2` we returned<br>    # the resource id so here we&#39;ll rely on that to look it up.<br>    case ElixirApiJwt.Accounts.get_account!(id) do<br>      nil -&gt; {:error, :reason_for_error}<br>      resource -&gt; {:ok, resource}<br>    end<br>  end<br><br>  def resource_from_claims(_claims) do<br>    {:error, :reason_for_error}<br>  end<br>end</pre><p>Next we need to add our configuration to config/config.exs:</p><pre>config :my_app, MyApp.Guardian,<br>       issuer: &quot;my_app&quot;,<br>       secret_key: &quot;Secret key. You can use `mix guardian.gen.secret` to get one&quot;</pre><p>so for us , we have</p><pre>config :elixir_api_jwt, ElixirApiJwt.Guardian,<br>  issuer: &quot;elixir_api_jwt&quot;,<br>  secret_key: &quot;Secret key. You can use `mix guardian.gen.secret` to get one&quot;</pre><p>To generate the secret key run</p><pre>mix guardian.gen.secret</pre><p>and replace the string you will be given to the config file.</p><p>Let us deal with signing in , when we sign in , what should happen,we should add a user , get a token with the user details back , for this , we will use the encode_and_sign helper by Guardian.</p><p>Go to the account controller and edit the create function to</p><pre>def create(conn, %{&quot;account&quot; =&gt; account_params}) do<br>    with {:ok, %Account{} = account} &lt;- Accounts.create_account(account_params),<br>         {:ok, token, _full_claims} &lt;- Guardian.encode_and_sign(account) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; render(&quot;account_token.json&quot;, account: account, token: token)<br>    end<br>end</pre><p>We have added a custom “account_token.json” , that will return to use the account details and the token .</p><p>Let us go into the views/account_view.ex and add this function</p><pre>def render(&quot;account_token.json&quot;, %{account: account, token: token}) do<br>    %{<br>      id: account.id,<br>      email: account.email,<br>      token: token<br>    }<br>end</pre><p>Lastly, we go to our router files and add a route to create and signup a user .</p><p>In router.ex have this</p><pre>scope &quot;/api&quot;, ElixirApiJwtWeb do<br>    pipe_through :api<br>    post &quot;/accounts/register&quot;, AccountController, :create<br>end</pre><p>Now let us try signing up , we fire up our server with</p><pre>iex -S mix phx.server</pre><p>Using Postman, we can send a POST request to</p><pre>http://localhost:4000/api/accounts/register</pre><p>With the body</p><pre>{<br>   &quot;account&quot;: {<br>  <br>        &quot;email&quot;: &quot;test3@gmail.com&quot;,<br>        &quot;hash_password&quot;: &quot;123456&quot;<br>  }<br>}</pre><p>We get</p><pre>{<br>    &quot;id&quot;: 3,<br>    &quot;token&quot;: &quot;eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJlbGl4aXJfYXBpX2p3dCIsImV4cCI6MTcwNzE1MDI5NiwiaWF0IjoxNzA0NzMxMDk2LCJpc3MiOiJlbGl4aXJfYXBpX2p3dCIsImp0aSI6IjUyMWU2MDlhLTBmNDAtNGVhZi1iZTdjLWE5MzBhNTJkZWUxMCIsIm5iZiI6MTcwNDczMTA5NSwic3ViIjoiMyIsInR5cCI6ImFjY2VzcyJ9.6wgyr9n0BuBN3Bu3-zQ8NihYG_NigmmunE82GQZo_ThP4HmuteJfmtx0VUjLhOm0bxc4g20NzWy_Zaa7-QwGQQ&quot;,<br>    &quot;email&quot;: &quot;test3@gmail.com&quot;<br>}</pre><p>In the response, we get the token, email, and user id.</p><p>Congratulations, you have configured signing up using JWT.</p><p>We will now use this token to access authenticated routes and ensure a user is authenticated.</p><blockquote>SIGNING IN</blockquote><p>Let us now add functions to help in signing in, first, we need to have a way to get a user by their email, in the accounts context file , accounts.ex add this</p><pre>def get_account_by_email(email) do<br>    Repo.get_by(Account, email: email)<br> end</pre><p>In our guardian.ex file add</p><pre>def authenticate(email, password) do<br>    case ElixirApiJwt.Accounts.get_account_by_email(email) do<br>      nil -&gt;<br>        {:error, :unauthorized}<br><br>      resource -&gt;<br>        case validate_password(password, resource.hash_password) do<br>          true -&gt; create_token(resource)<br>          false -&gt; {:error, :reason_for_error}<br>        end<br>    end<br>  end<br><br>  def validate_password(password, hash_password) do<br>    Bcrypt.verify_pass(password, hash_password)<br>  end<br><br>  defp create_token(account) do<br>    {:ok, token, _full_claims} =<br>      encode_and_sign(account)<br><br>    {:ok, account, token}<br> end</pre><p>We will be authenticating a user using email and their password .</p><p>We get the account first via email and use Bycpt to verify whether the password we passed “123456”, is similar to the one hashed in our database .</p><p>We will use these functions now for signing in , let us go to our account controller and add</p><pre>  def sign_in(conn, %{&quot;account&quot; =&gt; %{&quot;email&quot; =&gt; email, &quot;hash_password&quot; =&gt; hash_password}}) do<br>    case ElixirApiJwt.Guardian.authenticate(email, hash_password) do<br>      {:ok, account, token} -&gt;<br>        conn<br>        |&gt; put_status(:ok)<br>        |&gt; render(&quot;account_token.json&quot;, account: account, token: token)<br><br>      {:error, _reason} -&gt;<br>        conn<br>        |&gt; put_status(:unauthorized)<br>        |&gt; render(&quot;error.json&quot;, error: &quot;invalid credentials&quot;)<br>    end<br>  end</pre><p>We check if the user exists and if the password is the same, then we render the user’s id, email and token.</p><p>We. have defined “error.json”, let us add that in the views/account_view.ex</p><pre> def render(&quot;error.json&quot;, %{error: error}) do<br>    %{<br>      error: error<br>    }<br> end</pre><p>Let us add a route in router.ex , in the “/api” scope, we add</p><pre>   post &quot;/accounts/sign_in&quot;, AccountController, :sign_in</pre><p>So we have</p><pre><br>  # Other scopes may use custom stacks.<br>  scope &quot;/api&quot;, ElixirApiJwtWeb do<br>    pipe_through :api<br>    post &quot;/accounts/register&quot;, AccountController, :create<br>    post &quot;/accounts/sign_in&quot;, AccountController, :sign_in<br>  end</pre><p>Let us test this out with postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLoN__F3QYp64DT1-srGKg.png" /></figure><p>we are sending a post request to</p><pre>http://localhost:4000/api/accounts/sign_in</pre><p>with the body</p><pre>{<br>   &quot;account&quot;: {<br>       <br>        &quot;email&quot;: &quot;test3@gmail.com&quot;,<br>        &quot;hash_password&quot;: &quot;123456&quot;<br><br>}<br>}</pre><p>And we get this body back</p><pre>{<br>    &quot;id&quot;: 3,<br>    &quot;token&quot;: &quot;eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJlbGl4aXJfYXBpX2p3dCIsImV4cCI6MTcwNzE1MjM5OSwiaWF0IjoxNzA0NzMzMTk5LCJpc3MiOiJlbGl4aXJfYXBpX2p3dCIsImp0aSI6ImJjYmFhYzc4LTNlNzEtNGQ3NS1hMzBjLWYzZmFhYWIxYjI1OCIsIm5iZiI6MTcwNDczMzE5OCwic3ViIjoiMyIsInR5cCI6ImFjY2VzcyJ9.Tgd6hXKN-c-NEx5Tt69m_iOOKqxBCtgX1Ju_baDzBQRuilQ9UKyl-FtDLXMztFP5Y07p2Ol2JrFIvov5XymlXg&quot;,<br>    &quot;email&quot;: &quot;test3@gmail.com&quot;<br>}</pre><p>If we pass in an invalid password or email, we get</p><pre>{<br>    &quot;error&quot;: &quot;invalid credentials&quot;<br>}</pre><blockquote>RESET PASSWORD .</blockquote><p>When resetting the password, we want to ensure the user passed in the current_password and the new hash_password .</p><p>Let us add a reset_password function in the account controller.</p><pre>def reset_password(conn, %{&quot;account&quot; =&gt; account_params}) do<br>    case Accounts.get_account_by_email(account_params[&quot;email&quot;]) do<br>      nil -&gt;<br>        conn<br>        |&gt; put_status(:unauthorized)<br>        |&gt; render(&quot;error.json&quot;, error: &quot;Email not found&quot;)<br><br>      account -&gt;<br>        case ElixirApiJwt.Guardian.validate_password(account_params[&quot;current_password&quot;], account.hash_password) do<br>          true -&gt;<br>            with {:ok, %Account{} = account} &lt;- Accounts.update_account(account, account_params),<br>                 {:ok, token, _full_claims} &lt;- ElixirApiJwt.Guardian.encode_and_sign(account) do<br>              render(conn, &quot;account_token.json&quot;, account: account, token: token)<br>            end<br><br>          false -&gt;<br>            conn<br>            |&gt; put_status(:unauthorized)<br>            |&gt; render(&quot;error.json&quot;, error: &quot;invalid credentials&quot;)<br>        end<br>    end<br>  end</pre><p>And in our router file, add</p><pre> patch &quot;/accounts/reset_password&quot;, AccountController, :reset_password</pre><p>Let us test this out in postman</p><p>We send a patch request to</p><pre>http://localhost:4000/api/accounts/reset_password</pre><p>With the body</p><pre>{<br>   &quot;account&quot;: {<br>        <br>    <br>        &quot;email&quot;: &quot;test4@gmail.com&quot;,<br>        &quot;current_password&quot;: &quot;123456&quot;,<br>        &quot;hash_password&quot;: &quot;new password&quot;<br>  <br>}<br>}</pre><p>And getting back</p><pre>{<br>    &quot;id&quot;: 4,<br>    &quot;token&quot;: &quot;eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJlbGl4aXJfYXBpX2p3dCIsImV4cCI6MTcwNzE1MzMyMCwiaWF0IjoxNzA0NzM0MTIwLCJpc3MiOiJlbGl4aXJfYXBpX2p3dCIsImp0aSI6ImNiZDQ4ZWExLTliNmEtNDkyNi05N2NmLTljMzFlMDMzZGMxOSIsIm5iZiI6MTcwNDczNDExOSwic3ViIjoiNCIsInR5cCI6ImFjY2VzcyJ9.5gcbwoyu8vWJBvUo2TqV2tT5XL7dSmlQB1jqguOyqhdPedGWTZaj_5prWEk3S0Fqr-Lkiewjs_Tc3qKzAx1QKw&quot;,<br>    &quot;email&quot;: &quot;test4@gmail.com&quot;<br>}</pre><p>if we pass an invalid email, we get</p><pre>{<br>    &quot;error&quot;: &quot;Email not found&quot;<br>}</pre><p>And if we pass in the wrong current_password , we get</p><pre>{<br>    &quot;error&quot;: &quot;invalid credentials&quot;<br>}</pre><p>Now we are good for resetting passwords.</p><h3>PROTECTING CERTAIN ROUTES</h3><p>If we want to ensure that a user is logged in to ensure we have the right people seeing the right things, we have to make sure they are protected.</p><p>This can be found in the guardian documentation, the first thing we do is create an error handler.</p><p>Let us first create a file called guardian_error_handler.ex in lib/elixir_api_jwt</p><p>and add</p><pre>defmodule ElixirApiJwt.GuardianErrorHandler do<br>  import Plug.Conn<br><br>  def auth_error(conn, {type, _reason}, _opts) do<br>    body = Jason.encode!(%{message: to_string(type)})<br><br>    conn<br>    |&gt; put_resp_content_type(&quot;application/json&quot;)<br>    |&gt; send_resp(401, body)<br>  end<br>end</pre><p>Let us then create a pipeline, guardian_pipeline.ex</p><p>, and add</p><pre>defmodule ElixirApiJwt.GuardianPipeline do<br>  use Guardian.Plug.Pipeline,<br>    otp_app: :elixir_api_jwt,<br>     module: ElixirApiJwt.Guardian,<br>    error_handler: ElixirApiJwt.GuardianErrorHandler<br><br>  plug Guardian.Plug.VerifyHeader<br>  plug Guardian.Plug.VerifySession<br>  plug Guardian.Plug.EnsureAuthenticated<br>  plug Guardian.Plug.LoadResource<br>end</pre><p>Finally, let us add configurations to the router.ex file .</p><p>Add</p><pre>  pipeline :auth do<br>    plug ElixirApiJwt.GuardianPipeline<br>  end</pre><p>Then a scope, we want to ensure only authenticated people can see all users</p><pre> scope &quot;/api&quot;, ElixirApiJwtWeb do<br>    pipe_through [:api, :auth]<br>    get &quot;/accounts&quot;, AccountController, :index<br>  end</pre><p>Let us now try accessing the “/accounts”</p><p>send a GET request to</p><pre>http://localhost:4000/api/accounts</pre><p>We get,</p><pre>{<br>    &quot;message&quot;: &quot;unauthenticated&quot;<br>}</pre><blockquote>HOW TO ACCESS PROTECTED ROUTES .</blockquote><p>We access protected routes by passing the Authorization in the header.</p><p>We are passing it as “Bearer #{token}”, we get this token after signing up or signing in, you can add that here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXOR82aFHf9yUNL7N6RJdg.png" /></figure><p>Now when we add a token here, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukKoq4ctX7b1Gav-C8TZQw.png" /></figure><p>We are now good, we can access certain routes after authorization.</p><p>I hope you have got a good understanding of elixir api authentication with jwts .</p><p>You can view the source code here</p><p><a href="https://github.com/MICHAELMUNAVU83/elixir_api_jwt">GitHub - MICHAELMUNAVU83/elixir_api_jwt</a></p><p>Thank you so much for taking the time to learn with me, you can reach out to me at <a href="https://michaelmunavu.com/">https://michaelmunavu.com</a> in case of any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd47f776f92d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TESTING PHOENIX LIVE VIEW]]></title>
            <link>https://medium.com/@michaelmunavu83/testing-phoenix-live-view-7851ccca6e37?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/7851ccca6e37</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 05:44:41 GMT</pubDate>
            <atom:updated>2024-02-25T13:34:55.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8uFu1ez6sYkI7EJAzXt6Q.png" /></figure><p>I have had to write tests for Phoenix Live View for the past 3/4 weeks and I found it very hard to get the jist of what was happening.</p><p>I will admit, I had always been skeptical about testing until very recently.</p><p>Joshua Plicque said at Elixir Conf Africa while giving a talk” I test once and I know my thing always works, you never test so you are always testing”.</p><p>Think about this, when you have a button in your live view that increments a number by one, what you normally do, is write the code, fire up your server, and test it out on the browser till it works as expected, so in a way, you are always testing.</p><p>With testing, you write a test case against a certain event and you test once, if the test passes you are good.</p><h3><strong>HOW DO LIVE VIEW TESTS WORK?</strong></h3><p>How I understood tests in Liveview is such, think of it as a robot, but in this case, not a very intelligent robot as we see these days. Think of it as a very stupid robot that has to be told exactly what do to, do not assume your robot knows anything, you have to be specific when telling your robot which button to press, which page to go to, which input field to change and which form to submit.</p><p>We are testing how HTML within our page changes in relation to certain events.</p><p>In testing live view, we are asking this robot to go to this specific route, on this route it should expect to see certain HTML content.</p><p>We will mostly be looking at testing HTML when working with live view tests.</p><p>Think of if we are to test google.com, the home page, we would tell the robot to go to the link, in that link, you will see “Google” and a search form.</p><p>When you see the form, if you start typing “el”, I expect to see a suggestion box with “elixir” and probably other words starting with “el”.</p><h3>WHICH FUNCTIONALITIES WILL WE MOSTLY TEST?</h3><p>In Phoenix Live View, we will mostly test button clicks, form changes, and form submissions.</p><p>We can test for more functionalities but I believe in Live View, when you break it down you are testing phx_click, phx_change, and phx_click.</p><h3>STRUCTURE OF A TEST FILE</h3><p>A test file is added to the test folder and has to end in _test.exs, so the full name would be fullname_test.exs</p><p>The file structure would be</p><pre>defmodule AppNameWeb.FileName do<br>  use AppNameWeb.ConnCase<br>  <br>  import Phoenix.LiveViewTest<br>  describe &quot;Group what you are testing&quot; do<br>    setup %{conn: conn} do<br>      # here is where you have data needed in thetests and is then passed down<br><br>      [<br>        conn: conn<br>      ]<br>    end<br><br>    test &quot;testing a specific thing&quot;, %{conn: conn} do<br>      assert something = something<br>    end<br>  end<br>end</pre><h3>TERMINOLOGIES USED IN TESTING</h3><p>In the course of our testing, I will be using the following</p><h4>assert</h4><p>With assert, I am saying I expect to see something in the HTML</p><h4>refute</h4><p>With refute, I am saying that I do not expect to see certain content in the HTML, this would be useful in testing a delete functionality, if I have a list of blogs and I delete the blog titled “Blog one”, then I can refute that I will not see “Blog one” in my HTML content.</p><h4>render_click</h4><p>We will use this to simulate click events .</p><h4>render_submit</h4><p>We will use this to simulate submit events.</p><h4>render_change</h4><p>We will use this to simulate change events, mostly in forms .</p><h4>form/2</h4><p>A form will take 2 parameters, the id identifying it and the params being passed through it, an example is as such.</p><pre>  |&gt; form(&quot;#testing-search-form&quot;, query: %{search: &quot;q&quot;})</pre><p>We will also have a deeper look at this.</p><h4>element/2</h4><p>An element will take 2 parameters, the ID identifying it and the content inside it.</p><h4>has_element?</h4><p>This is used together with element/2 such that we can have</p><pre>assert <br>index_live<br>|&gt; element(&quot;#add-button&quot; , &quot;+&quot;)<br>|&gt; has_element()</pre><p>This will be true if there is an element with the content of “+” and an id of “add-button”</p><p>If we want to go to a certain route to view its HTML, we write</p><pre>  {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.home_index_path(conn, :index)<br>        )</pre><h3>THINGS TO HELP YOU TEST FASTER AND BETTER</h3><p>Remember when I said we should think of testing as a very stupid robot?</p><p>In this case, there are some things we can do in our code to help out our stupid robot.</p><ol><li>Uniquely identifying forms and buttons with IDs</li><li>Testing HTML Content and not HTML Structure.</li></ol><p>Looking at the first point, we will be telling our robot, “hey, go to this button and click it”, we need to uniquely identify this button that the robot will click, so unique IDs are very very very important.</p><p>On the second point, during a pair programming session with <a href="https://medium.com/u/c93118b21336">sigu</a>, he mentioned we should test HTML and not HTML structure as sometimes someone might change the p tag holding a title to a h2 instead, if we told our robot to look for a p tag with the title, it would fail. However, if we told our robot that within the HTML, there will be a title, regardless of the structure, then it will pass.</p><p>Most times, the HTML structure will change but not the HTML Content.</p><h3>GETTING STARTED</h3><p>Let us create a repo and get our hands dirty .</p><pre>mix phx.new testing_liveview<br>cd testing_liveview</pre><p>Set up your database credentials in config/dev.exs then run</p><pre>mix ecto.setup</pre><p>You can fire up your server with</p><pre>mix phx.server</pre><p>We will set up a live page before testing it, let us have a simple counter first.</p><p>Create a folder in lib/testing_livevview_web called home_live</p><p>Inside home_live have 2 files index.ex and index.html</p><p>In index.ex have</p><pre>defmodule TestingLiveviewWeb.HomeLive.Index do<br>  use TestingLiveviewWeb, :live_view<br><br>  def mount(_params, _session, socket) do<br>    {:ok, assign(socket, :counter, 0)}<br>  end<br><br>  def handle_event(&quot;increment&quot;, _params, socket) do<br>    {:noreply, assign(socket, :counter, socket.assigns.counter + 1)}<br>  end<br>  def handle_event(&quot;decrement&quot;, _params, socket) do<br>    {:noreply, assign(socket, :counter, socket.assigns.counter - 1)}<br>  end<br>end</pre><h4><strong><em>And the index.html.heex</em></strong></h4><pre>&lt;div&gt;<br>  &lt;p&gt;<br>    Counter<br>  &lt;/p&gt;<br><br>  &lt;%= @counter %&gt;<br><br>  &lt;button id=&quot;increment-button&quot;  phx-click=&quot;increment&quot;&gt;+&lt;/button&gt;<br>  &lt;button id=&quot;decrement-button&quot; phx-click=&quot;decrement&quot;&gt;-&lt;/button&gt;<br>&lt;/div&gt;</pre><p>In the router.ex inside the “/” scope add</p><pre>live &quot;/home&quot;, HomeLive.Index, :index</pre><p>So now you have</p><pre>scope &quot;/&quot;, TestingLiveviewWeb do<br>    pipe_through :browser</pre><pre>    get &quot;/&quot;, PageController, :index<br>    live &quot;/home&quot;, HomeLive.Index, :index<br>  end</pre><p>If we now go to your browser “/home” , you will see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qwa9G7ZczrijesD7NA30lA.png" /></figure><p>Here, we have a simple counter, every time we hit + , the number increases by 1 and every time we hit — , the number reduces by 1.</p><p>Let us look at how we would test this.</p><h3>FIRST LIVE VIEW TESTS (PHX-CLICK)</h3><p>Before we even create the test file, just like we do with writing code, we first write pseudo code, to understand the flow.</p><p>So let us do so with our test.</p><p>What would we have our robot do</p><ol><li>Go to the “/home” route</li><li>We should see The word “Counter” on the HTML.</li><li>We should see the initial value of the counter “0”.</li><li>Whenever we click the + button, the value of 0 should change to 1</li><li>If we click the button again, the value should go to 2</li><li>If we now click the -button, then the value should drop to 1.</li></ol><p>Let us get started.</p><p>Create a folder called live inside test.</p><p>Inside live, create a file called home_live_test.exs .</p><p>Have the starter code as such</p><pre>defmodule TestingLiveviewWeb.HomeLiveTest do<br>  @moduledoc false<br>  use TestingLiveviewWeb.ConnCase<br><br>  import Phoenix.LiveViewTest<br><br>  describe(&quot;Testing the counter on home live &quot;) do<br>   <br>  end<br>end</pre><p>We shall be testing the functionalities listed above</p><h4>1. When we go to “/home”, we see the word “Counter” and an initial value of “0”</h4><p>Inside the description, we can add</p><pre> test &quot;We see the Counter and initial 0&quot;, %{conn: conn} do<br>      {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.home_index_path(conn, :index)<br>        )<br><br>      assert html =~ &quot;Counter&quot;<br>      assert html =~ &quot;0&quot;<br>  end</pre><p>This test goes to”/home” and gets the HTML, we assert the HTML has “Counter” and “0”.</p><p>To run this, on our terminal run</p><pre>mix test test/live/home_live_test.exs</pre><h4>2 . We are now testing that if we go to the HTML and click +, the 0 is now 1.</h4><p>For this, we will use 2 of the terms I introduced, element/2 to tell the robot which element we are identifying and render_click to hit the element.</p><p>This test would be something like this</p><pre><br>    test &quot;When we click the + button, the counter is incremented by 1&quot;, %{conn: conn} do<br>      {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.home_index_path(conn, :index)<br>        )<br><br>      assert html =~ &quot;0&quot;<br><br>      new_html =<br>        index_live<br>        |&gt; element(&quot;#increment-button&quot;, &quot;+&quot;)<br>        |&gt; render_click()<br><br>      assert new_html =~ &quot;1&quot;<br>      refute new_html =~ &quot;0&quot;<br>    end</pre><p>let us break it down, here we are saying that once our robot goes to “/home”, it will find HTML with “0”.</p><p>We are then instructing it to get the element with the id of increment-button that has inner content “+”, and then click it.</p><p>The HTML for that button is as such.</p><pre>&lt;button id=&quot;increment-button&quot;  phx-click=&quot;increment&quot;&gt;+&lt;/button&gt;</pre><p>We are asserting that in the new HTML that we will see after doing this action, we will see the number “1” but not the number “0”</p><h4>3 . We are now testing that the — button works, this should decrement the counter value.</h4><p>We can set this test up such that we click the add button twice and the reduce button once, hence, we will see the value “2”</p><pre>  test &quot;When we click the - button, the counter is decremented by 1&quot;, %{conn: conn} do<br>      {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.home_index_path(conn, :index)<br>        )<br><br>      assert html =~ &quot;0&quot;<br><br>      index_live<br>      |&gt; element(&quot;#increment-button&quot;, &quot;+&quot;)<br>      |&gt; render_click()<br><br>      index_live<br>      |&gt; element(&quot;#increment-button&quot;, &quot;+&quot;)<br>      |&gt; render_click()<br><br>      index_live<br>      |&gt; element(&quot;#increment-button&quot;, &quot;+&quot;)<br>      |&gt; render_click()<br><br>      new_html =<br>        index_live<br>        |&gt; element(&quot;#decrement-button&quot;, &quot;-&quot;)<br>        |&gt; render_click()<br><br>      assert new_html =~ &quot;2&quot;<br>    end</pre><p>Congratulations, we have written our first live view tests.</p><h3>SECOND LIVE VIEW TESTS (PHX-CHANGE)</h3><p>I want to now show you how we have to add some tables to our database, let us add a context file for Posts.</p><pre>mix phx.gen.context Posts Post posts title description </pre><p>We then create the live page for our posts.</p><p>In the web folder ie , lib/testing_liveview_web/live</p><p>Create a folder called post_live , Here we will just list all posts.</p><p>In the index.ex have</p><pre>defmodule TestingLiveviewWeb.PostLive.Index do<br>  use TestingLiveviewWeb, :live_view<br>  alias TestingLiveview.Posts<br><br>  def mount(_params, _session, socket) do<br>    {:ok,<br>     socket<br>     |&gt; assign(:posts, Posts.list_posts())}<br>  end<br>end</pre><p>In the index.html.heex</p><pre>&lt;div&gt;<br>  &lt;h2&gt;<br>    Posts<br>  &lt;/h2&gt;<br>  &lt;%= for post &lt;- @posts  do %&gt;<br>    &lt;span&gt;&lt;%= post.title %&gt;&lt;/span&gt;<br>    &lt;span&gt;&lt;%= post.description %&gt;&lt;/span&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>In your router file add</p><pre>  live &quot;/posts&quot;, PostLive.Index, :index</pre><p>So you now have</p><pre>scope &quot;/&quot;, TestingLiveviewWeb do<br>    pipe_through :browser<br><br>    get &quot;/&quot;, PageController, :index<br>    live &quot;/home&quot;, HomeLive.Index, :index<br>    live &quot;/posts&quot;, PostLive.Index, :index<br>  end</pre><p>Next, let us add some seed data.</p><p>in priv/repo/seeds.exs add</p><pre><br>alias TestingLiveview.Posts<br><br>Posts.create_post(%{<br>  title: &quot;first&quot;,<br>  description: &quot;first post&quot;<br>})<br><br><br>Posts.create_post(%{<br>  title: &quot;second&quot;,<br>  description: &quot;second post&quot;<br>})<br><br>Posts.create_post(%{<br>  title: &quot;third&quot;,<br>  description: &quot;third post&quot;<br>})</pre><p>and now in your terminal to run the seeds run</p><pre>mix run priv/repo/seeds.exs</pre><p>Now we are good to go.</p><p>If we go to “/posts” we see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMYfLoFcfGFPH4EoeSrJsQ.png" /></figure><p>Let us add a simple search filter.</p><p>edit the index.ex file for the post to be</p><pre>defmodule TestingLiveviewWeb.PostLive.Index do<br>  use TestingLiveviewWeb, :live_view<br>  alias TestingLiveview.Posts<br>  alias TestingLiveview.Posts.Post<br><br>  def mount(_params, _session, socket) do<br>    {:ok,<br>     socket<br>     |&gt; assign(:changeset, Posts.change_post(%Post{}))<br>     |&gt; assign(:posts, Posts.list_posts())}<br>  end<br><br>  def handle_event(&quot;search&quot;, %{&quot;post&quot; =&gt; %{&quot;search&quot; =&gt; query}}, socket) do<br>    posts =<br>      Posts.list_posts()<br>      |&gt; Enum.filter(fn post -&gt;<br>        String.contains?(String.downcase(post.title), String.downcase(query))<br>      end)<br><br>    {:noreply, socket |&gt; assign(:posts, posts)}<br>  end<br>end</pre><p>The index.html file to be</p><pre>&lt;div&gt;<br>  &lt;.form let={f} for={@changeset}  id=&quot;search-post-filter&quot; phx_change=&quot;search&quot;&gt;<br>    &lt;%= text_input(f, :search,<br>      placeholder: &quot;Search&quot;,<br>     <br>    ) %&gt;<br>  &lt;/.form&gt;<br>  &lt;h2&gt;<br>    Posts<br>  &lt;/h2&gt;<br>  &lt;%= for post &lt;- @posts  do %&gt;<br>    &lt;span&gt;&lt;%= post.title %&gt;&lt;/span&gt;<br>    &lt;span&gt;&lt;%= post.description %&gt;&lt;/span&gt;<br>  &lt;% end %&gt;<br>&lt;/div&gt;</pre><p>now we can test this out and the search works on the browser, let us write</p><p>tests for this.</p><p>In the test and live folder add the file</p><p>post_live_test.exs .</p><p>Have the boilerplate for this as such</p><pre>defmodule TestingLiveviewWeb.PostLiveTest do<br>  @moduledoc false<br>  use TestingLiveviewWeb.ConnCase<br><br>  import Phoenix.LiveViewTest<br><br>  describe(&quot;Testing the search functionality on the posts page&quot;) do<br>    <br>  end<br>end</pre><p>Before we run the search feature, we need to have some data to run the search against, we will now introduce setup in tests.</p><p>Let us have a sub-section for this.</p><h3>SETUP IN TESTING</h3><p>A setup is a function that will run before your test does.</p><p>Think of saying, before this robot goes to google.com, I want to make sure google.com has all the data I need.</p><p>I will put all the data in the setup.</p><p>If we want to test some feature like search, we need to have some data prior that we can test this search against.</p><p>For this, we will insert this data into our test database via the setup.</p><p>We need factories for this, you can read more about them here <a href="https://hexdocs.pm/ecto/test-factories.html">https://hexdocs.pm/ecto/test-factories.html</a> .</p><p>Let us look at factories</p><h3>FACTORY</h3><p>Factories provide convenience functions for producing different groups of data.</p><p>They work just as factories do, you build things there, so in this case, we are building some data.</p><p>For example, we may need to build a user or a post.</p><p>The structure of a factory file would be as follows.</p><pre>defmodule MyApp.Factory do<br>  alias MyApp.Repo<br><br>  # Factories<br><br>  def build(:post) do<br>    %MyApp.Post{title: &quot;hello world&quot;}<br>  end<br><br>  def build(:comment) do<br>    %MyApp.Comment{body: &quot;good post&quot;}<br>  end<br><br>  def build(:post_with_comments) do<br>    %MyApp.Post{<br>      title: &quot;hello with comments&quot;,<br>      comments: [<br>        build(:comment, body: &quot;first&quot;),<br>        build(:comment, body: &quot;second&quot;)<br>      ]<br>    }<br>  end<br><br>  def build(:user) do<br>    %MyApp.User{<br>      email: &quot;hello#{System.unique_integer()}&quot;,<br>      username: &quot;hello#{System.unique_integer()}&quot;<br>    }<br>  end<br><br>  # Convenience API<br><br>  def build(factory_name, attributes) do<br>    factory_name |&gt; build() |&gt; struct!(attributes)<br>  end<br><br>  def insert!(factory_name, attributes \\ []) do<br>    factory_name |&gt; build(attributes) |&gt; Repo.insert!()<br>  end<br>end</pre><p>In our context, we would want a factory to build posts for us.</p><p>Let us create a file in test/support called factory.ex , inside add.</p><pre>defmodule TestingLiveview.Factory do<br>  @moduledoc &quot;&quot;&quot;<br>  Generates builds and inserts data for use in tests<br>  &quot;&quot;&quot;<br>  alias TestingLiveview.Posts.Post<br>  alias TestingLiveview.Repo<br><br>  def build(:post) do<br>    %Post{<br>      title: &quot;This is the title&quot;,<br>      description: &quot;This is the description&quot;,<br>    }<br>  end<br><br>  def build(factory_name, attributes) do<br>    factory_name |&gt; build() |&gt; struct(attributes)<br>  end<br><br>  def insert!(factory_name, attrs \\ []) do<br>    factory_name |&gt; build(attrs) |&gt; Repo.insert!()<br>  end<br>end</pre><p>Here we have a factory to build a post with , now if we call</p><pre>Factory.insert!(:post)</pre><p>we get this inserted to the test database .</p><pre>%TestingLiveview.Posts.Post{<br>  __meta__: #Ecto.Schema.Metadata&lt;:loaded, &quot;posts&quot;&gt;,<br>  id: 1,<br>  description: &quot;This is an admin post&quot;,<br>  title: &quot;Admin Post&quot;,<br>  inserted_at: ~N[2023-11-29 13:18:37],<br>  updated_at: ~N[2023-11-29 13:18:37]<br>}<br></pre><p>We can add custom parameters when building,</p><pre>Factory.insert!(:post , title: &quot;First Post&quot; , description: &quot;This is the first post&quot;)Factory.insert!(:post , title: &quot;First Post&quot; , description: &quot;This is the first post&quot;)</pre><p>This is now added to the database</p><pre>%TestingLiveview.Posts.Post{<br>  __meta__: #Ecto.Schema.Metadata&lt;:loaded, &quot;posts&quot;&gt;,<br>  id: 2,<br>  description: &quot;This is the first post&quot;,<br>  title: &quot;First Post&quot;,<br>  inserted_at: ~N[2023-11-29 13:25:08],<br>  updated_at: ~N[2023-11-29 13:25:08]<br>}</pre><h3>SETUP AND FACTORY COMBINED</h3><p>Now, let us have our setup with factories, we can also now pass down the data you have created to each test.</p><p>The setup function will be done inside the describe function but outside each test.</p><p>The structure would be as such</p><pre>  describe(&quot;Testing the search functionality on the posts page&quot;) do<br>    setup %{conn: conn} do<br>        post = Factory.insert!(:post)<br>         [post: post]<br>    end<br><br>    test &quot;An individual test&quot;, %{conn: conn, post: post} do<br>     <br>    end<br>  end<br>end</pre><h3>TESTING THE SEARCH FUNCTIONALITY</h3><p>Let us now think of how this search functionality would look like to our very stupid robot.</p><p>Our robot would expect to go to the page when it passes “first” on the form, it expects to only see posts that have the word “first” in them.</p><p>Our test file for the search would now be</p><pre>defmodule TestingLiveviewWeb.PostLiveTest do<br>  @moduledoc false<br>  use TestingLiveviewWeb.ConnCase<br><br>  import Phoenix.LiveViewTest<br>  alias TestingLiveview.Factory<br><br>  describe(&quot;Testing the search functionality on the posts page&quot;) do<br>    setup %{conn: conn} do<br>      post_one =<br>        Factory.insert!(:post, title: &quot;First Post&quot;, description: &quot;This is the first post&quot;)<br><br>      post_two =<br>        Factory.insert!(:post, title: &quot;Second Post&quot;, description: &quot;This is the second post&quot;)<br><br>      [post_one: post_one, post_two: post_two]<br>    end<br><br>    test &quot;Once you search for a post, you get filtered results of records matching the searched term&quot;, %{conn: conn, post_one: post_one, post_two: post_two} do<br>      {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.post_index_path(conn, :index)<br>        )<br><br>      assert html =~ post_one.title<br>      assert html =~ post_two.title<br><br>      searched_html =<br>        index_live<br>        |&gt; form(&quot;#search-post-filter&quot;, post: %{search: &quot;Fi&quot;})<br>        |&gt; render_change()<br><br>      assert searched_html =~ post_one.title<br>      refute searched_html =~ post_two.title<br>    end<br>  end<br>end</pre><p>Let us break it down, we are setting it up by having 2 posts and passing them down.</p><p>We are using them in the test.</p><p>When we go to the page, we should see both posts.</p><p>When we go to the form and pass the params of</p><pre>post: %{search: &quot;Fi&quot;}</pre><p>We only now see posts that have “Fi” .</p><p>The tricky part with render change is knowing which params to pass through the form.</p><p>We match this with the handle event params so if we have</p><pre>  def handle_event(&quot;search&quot;, %{&quot;post&quot; =&gt; %{&quot;search&quot; =&gt; query}}, socket) do<br>  end</pre><p>When passing the params for the test we have</p><pre>post: %{search: &quot;Fi&quot;}</pre><p>if we had</p><pre>def handle_event(&quot;search&quot;, %{&quot;game&quot; =&gt; %{&quot;name&quot; =&gt; game_name}}, socket) do<br>end</pre><p>On the testing end, we would have</p><pre>game: %{name: &quot;test&quot;}</pre><h3>THIRD LIVE VIEW TESTS (PHX-SUBMIT)</h3><p>Let us now add a form that will allow us to add posts to our database.</p><p>Testing for a submission is very similar to change in a form.</p><p>We will be passing the same params to the form but this time instead of having render_click , we have render_submit.</p><p>If we imagine our search function works with submission, now the test would be.</p><pre>test &quot;We see the Counter and initial 0&quot;, %{conn: conn, post_one: post_one, post_two: post_two} do<br>      {:ok, index_live, html} =<br>        live(<br>          conn,<br>          Routes.post_index_path(conn, :index)<br>        )<br><br>      assert html =~ post_one.title<br>      assert html =~ post_two.title<br><br>      searched_html =<br>        index_live<br>        |&gt; form(&quot;#search-post-filter&quot;, post: %{search: &quot;Fi&quot;})<br>        |&gt; render_submit()<br><br>      assert searched_html =~ post_one.title<br>      refute searched_html =~ post_two.title<br>    end<br></pre><p>Same structure as the render change we had.</p><p>Now I believe you are set to write your first tests.</p><p>It will be hard for the first time but after you get the hang of it, it is easy peezy .</p><p>You can follow through in the repository I worked on parallel with this article</p><p><a href="https://github.com/MICHAELMUNAVU83/testing_liveview">GitHub - MICHAELMUNAVU83/testing_liveview</a></p><p>Thank you for your time. I hope we both learnt something.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7851ccca6e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CREATING A CALLBACK URL ENDPOINT FOR CHPTER API WITH ELIXIR.]]></title>
            <link>https://medium.com/@michaelmunavu83/creating-a-callback-url-endpoint-for-chpter-api-with-elixir-4c9a5ca44f43?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9a5ca44f43</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 11:28:17 GMT</pubDate>
            <atom:updated>2023-10-22T11:28:17.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRK5iI5OpRHzCQgxe7rrTw.png" /></figure><p>Hello , if you are getting here from the hex package Chpter , thanks so much for using it and I hope you love it .</p><p>We will be using an API for mpesa payments provided by chpter , <a href="http://v3.chpter.co/">https://v3.chpter.co </a>, Here is their documentation <a href="https://chpter.gitbook.io/chpter-3.0-public-api-reference/">https://chpter.gitbook.io/chpter-3.0-public-api-reference/</a> .</p><p>This article is a pre-read for <a href="https://medium.com/@michaelmunavu83/using-chpter-api-for-mpesa-payments-in-elixir-and-phoenix-live-view-9406ac4d1039">https://medium.com/@michaelmunavu83/using-chpter-api-for-mpesa-payments-in-elixir-and-phoenix-live-view-9406ac4d1039</a> , here I talk about how I impliment payment with chpter in my elixir and phoenix live view apps .</p><p>In this article , we will be solely building the callback url that we will use together with chpter to allow for Mpesa payments .</p><p>We create a new Phoenix app with the following command .</p><pre>mix phx.new chpter_callback_url</pre><p>Configure your database by setting the username and password in</p><pre>config/dev.exs</pre><p>Configure your database with</p><pre>mix ecto.setup</pre><p>Looking at the documentation chpter provides , <a href="https://chpter.gitbook.io/chpter-3.0-public-api-reference">https://chpter.gitbook.io/chpter-3.0-public-api-reference</a>/ ,they say the callack url needs to have the following columns</p><p>Message: string , Success: boolean , Status: integer , Amount: string , transaction_code:string and transaction_reference:string .</p><p>We need to create an endpoint that takes such a body , I realized in elixir, it is not possible to access columns starting with capital letters , in that case , for each of the columns that start with a capital letter , in our db , they will start with a small letter .</p><p>Thus for our callback url , our model will have</p><p>message: string , success: boolean , status: integer , amount: string , transaction_code:string and transaction_reference:string .</p><p>Every time chpter sends a POST request , we will intercept it before it enters our db and create a new map with our column names , you will see later how this works .</p><p>First , we create our model for the callback url , we will use the</p><h3>mix phx.gen.json</h3><p>command</p><p>on your terminal run</p><pre>mix phx.gen.json Transactions Transaction transactions message success:boolean status:integer amount transaction_code transaction_reference</pre><p>Add the resource to your :api scope in lib/chpter_phoenix_web/router.ex:</p><pre>resources &quot;/transactions&quot;, TransactionController, except: [:new, :edit]</pre><p>Such that you have this in your router file</p><pre>scope &quot;/api&quot;, ChpterCallbackUrlWeb do<br>    pipe_through :api<br>    resources &quot;/transactions&quot;, TransactionController, except: [:new, :edit]<br> end</pre><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>Now if we go to fire up our server with</p><pre>mix phx.server</pre><p>and go to localhost:4000/api/transactions , we see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/0*d7HR3xlHoM6_Rqib.png" /></figure><p>Currently , we have no data in our api endpoint .</p><p>Let us go to our transaction schema file in chpter_callback_url/transactions/transaction.ex and change</p><pre>def changeset(transaction, attrs) do<br>    transaction<br>    |&gt; cast(attrs, [:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>    |&gt; validate_required([:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>  end</pre><p>To</p><pre>def changeset(transaction, attrs) do<br>    transaction<br>    |&gt; cast(attrs, [:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>    |&gt; validate_required([:success, :status, :transaction_reference])<br>  end</pre><p>The body sent by chpter may have nil values for the message and amount but will always send data in regards to the transaction reference , status and success .</p><p>Now we move to our transaction controller , Remember , chpter sends the body in the format</p><pre>%{<br>   &quot;Message&quot; =&gt; &quot;message&quot;,<br>    &quot;Amount&quot; =&gt; &quot;1.000&quot;,<br>    &quot;Status&quot; =&gt; 200,<br>    &quot;Success&quot; =&gt; true,<br>    &quot;transaction_code&quot;=&gt; &quot;RTJVSJF69&quot;,<br>    &quot;transaction_reference&quot; =&gt; &quot;254740769596&quot;<br>}</pre><p>But in our database , we have the columns in starting in capital letters starting in small letters .</p><p>The whole idea here is to take the params we get when a body is posted and make a new map that can get into our database with the corresponding columns .</p><p>Let us to go the controller file in chpter_callback_url/controllers/transactions/transaction.ex</p><p>Edit the create function to</p><pre> def create(conn, transaction_params) do<br>    new_transaction_params = %{<br>      &quot;message&quot; =&gt; transaction_params[&quot;Message&quot;],<br>      &quot;success&quot; =&gt; transaction_params[&quot;Success&quot;],<br>      &quot;status&quot; =&gt; transaction_params[&quot;Status&quot;],<br>      &quot;amount&quot; =&gt; transaction_params[&quot;Amount&quot;],<br>      &quot;transaction_code&quot; =&gt; transaction_params[&quot;transaction_code&quot;],<br>      &quot;transaction_reference&quot; =&gt; transaction_params[&quot;transaction_reference&quot;]<br>    }<br><br>    <br><br>    with {:ok, %Transaction{} = transaction} &lt;-<br>           Transactions.create_transaction(new_transaction_params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.transaction_path(conn, :show, transaction))<br>      |&gt; render(&quot;show.json&quot;, transaction: transaction)<br>    end<br>  end</pre><p>Now we are set on the callback URL side, if you have Postman, we can test this out by sending a body to /api/transactions .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mCCNAMiGJg5THhsNMBflg.png" /></figure><p>Now you have a callback url ie /api/transactions where chpter will send objects after payment and where all your transactions will be stored .</p><p>You can view the codebase here <a href="https://github.com/MICHAELMUNAVU83/chpter_callback_url">https://github.com/MICHAELMUNAVU83/chpter_callback_url</a> .</p><p>Thanks for reading , I hope you have learnt a thing or 2 , to know how I implemented this in a full Phoenix application , you can read the article here <a href="https://medium.com/@michaelmunavu83/using-chpter-api-for-mpesa-payments-in-elixir-and-phoenix-live-view-9406ac4d1039">https://medium.com/@michaelmunavu83/using-chpter-api-for-mpesa-payments-in-elixir-and-phoenix-live-view-9406ac4d1039</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9a5ca44f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USING CHPTER API FOR MPESA PAYMENTS IN ELIXIR AND PHOENIX LIVE VIEW]]></title>
            <link>https://medium.com/@michaelmunavu83/using-chpter-api-for-mpesa-payments-in-elixir-and-phoenix-live-view-9406ac4d1039?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/9406ac4d1039</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[mpesa-api]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 10:50:11 GMT</pubDate>
            <atom:updated>2023-10-22T11:13:57.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoEw0xXiSWwQs0LhqBKPbA.png" /></figure><p>Payments are something we all need in our systems, In Kenya, the most popular payment API but their documentation is hell in my opinion and that is why I have opted for chpter in my systems, I have implemented it with Elixir and Phoenix Live View to create ticketing systems that never fail.</p><p>All these payment systems work the same, It took some time for me to understand the whole concept, but I’ll try and make this journey shorter for you.</p><p>Anytime you get a prompt to pay for something via mpesa in a web system , what happens is that after you pay , whether successful or not , a POST request with a body containing some data is sent to a certain endpoint . You may have heard of it being called a callback url. Yes , a callback url , this is where MPESA or chpter in this case will send a POST request with details showing whether the payment was successful or not .</p><p>In this article , we will build a simple system with a orders , for you to make the order , you will have to complete payment . We will be using an API for this provided by chpter , <a href="http://v3.chpter.co/">https://v3.chpter.co </a>, Here is their documentation <a href="https://chpter.gitbook.io/chpter-3.0-public-api-reference/">https://chpter.gitbook.io/chpter-3.0-public-api-reference/</a> .</p><p>As I wrote this article, I also decided to make a hex package to make it easy for us all, Here it is <a href="https://hexdocs.pm/chpter/0.1.1/Chpter.html">https://hexdocs.pm/chpter/0.1.1/Chpter.html</a> and the documentation is here <a href="https://hexdocs.pm/chpter/Chpter.html">https://hexdocs.pm/chpter/Chpter.html</a> , I’d advise you to read the whole article as it will help you understand the whole process flow better .</p><p>You can also find the GitHub repository for this project here .</p><p><a href="https://github.com/MICHAELMUNAVU83/chpter_phoenix">https://github.com/MICHAELMUNAVU83/chpter_phoenix</a></p><p>Enough with the intro, let us get our hands dirty.</p><p>We create a new Phoenix app with the following command .</p><pre>mix phx.new chpter_phoenix</pre><p>Configure your database by setting the username and password in</p><pre>config/dev.exs</pre><p>Configure your database with</p><pre>mix ecto.setup</pre><p>Now let us working on creating some models , here no one signs up , the flow is such that , users come into the system and can make a new order , for this , they have to make a payment</p><p>Our model will look as such</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*Natz2jYB42qTHT5HjN5sBA.png" /></figure><p>Before we start working on these , Let us first work on the callback url , Looking at the documentation chpter provides , <a href="https://chpter.gitbook.io/chpter-3.0-public-api-reference">https://chpter.gitbook.io/chpter-3.0-public-api-reference</a>/ ,they say the callack url needs to have the following columns</p><p>Message: string , Success: boolean , Status: integer , Amount: string , transaction_code:string and transaction_reference:string .</p><p>We need to create an endpoint that takes such a body , I realized in elixir, it is not possible to access columns starting with capital letters , in that case , for each of the columns that start with a capital letter , in our db , they will start with a small letter .</p><p>Thus for our callback url , our model will have</p><p>message: string , success: boolean , status: integer , amount: string , transaction_code:string and transaction_reference:string .</p><p>Every time chpter sends a POST request , we will intercept it before it enters our db and create a new map with our column names , you will see later how this works .</p><p>First , we create our model for the callback url , we will use the</p><h4>mix phx.gen.json</h4><p>command</p><p>on your terminal run</p><pre>mix phx.gen.json Transactions Transaction transactions message success:boolean status:integer amount transaction_code transaction_reference<br></pre><p>Add the resource to your :api scope in lib/chpter_phoenix_web/router.ex:</p><pre>resources &quot;/transactions&quot;, TransactionController, except: [:new, :edit]<br></pre><p>Such that you have this in your router file</p><pre> scope &quot;/api&quot;, ChpterPhoenixWeb do<br>    pipe_through :api<br>    resources &quot;/transactions&quot;, TransactionController, except: [:new, :edit]<br> end</pre><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>Now if we go to fire up our server with</p><pre>mix phx.server</pre><p>and go to localhost:4000/api/transactions , we see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*rl65W0tNZ5PXUPC7o14xQg.png" /></figure><p>Currently , we have no data in our api endpoint .</p><p>Let us go to our transaction schema file in chpter_phoenix/transactions/transaction.ex and change</p><pre>def changeset(transaction, attrs) do<br>    transaction<br>    |&gt; cast(attrs, [:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>    |&gt; validate_required([:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>  end</pre><p>To</p><pre>def changeset(transaction, attrs) do<br>    transaction<br>    |&gt; cast(attrs, [:message, :success, :status, :amount, :transaction_code, :transaction_reference])<br>    |&gt; validate_required([:success, :status, :transaction_reference])<br>  end</pre><p>The body sent by chpter may have nil values for the message and amount but will always send data in regards to the transaction reference , status and success .</p><p>Now we move to our transaction controller , Remember , chpter sends the body in the format</p><pre>%{<br>   &quot;Message&quot; =&gt; &quot;message&quot;,<br>    &quot;Amount&quot; =&gt; &quot;1.000&quot;,<br>    &quot;Status&quot; =&gt; 200,<br>    &quot;Success&quot; =&gt; true,<br>    &quot;transaction_code&quot;=&gt; &quot;RTJVSJF69&quot;,<br>    &quot;transaction_reference&quot; =&gt; &quot;254740769596&quot;<br>}<br></pre><p>But in our database , we have the columns in starting in capital letters starting in small letters .</p><p>The whole idea here is to take the params we get when a body is posted and make a new map that can get into our database with the corresponding columns .</p><p>Let us to go the controller file in chpter_phoenix_web/controllers/transactions/transaction.ex</p><p>Edit the create function to</p><pre> def create(conn, transaction_params) do<br>    new_transaction_params = %{<br>      &quot;message&quot; =&gt; transaction_params[&quot;Message&quot;],<br>      &quot;success&quot; =&gt; transaction_params[&quot;Success&quot;],<br>      &quot;status&quot; =&gt; transaction_params[&quot;Status&quot;],<br>      &quot;amount&quot; =&gt; transaction_params[&quot;Amount&quot;],<br>      &quot;transaction_code&quot; =&gt; transaction_params[&quot;transaction_code&quot;],<br>      &quot;transaction_reference&quot; =&gt; transaction_params[&quot;transaction_reference&quot;]<br>    }<br><br>    <br><br>    with {:ok, %Transaction{} = transaction} &lt;-<br>           Transactions.create_transaction(new_transaction_params) do<br>      conn<br>      |&gt; put_status(:created)<br>      |&gt; put_resp_header(&quot;location&quot;, Routes.transaction_path(conn, :show, transaction))<br>      |&gt; render(&quot;show.json&quot;, transaction: transaction)<br>    end<br>  end</pre><p>Now we are set on the callback URL side, if you have Postman, we can test this out by sending a body to /api/transactions .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mCCNAMiGJg5THhsNMBflg.png" /></figure><p>This means that we are good to go , Now we can work on creating the orders .</p><p>In your terminal run</p><pre>mix phx.gen.live Orders Order orders phone_number customer_name customer_email  delivery_location</pre><p>Add the live routes to your browser scope in lib/chpter_phoenix_web/router.ex:</p><pre>live &quot;/orders&quot;, OrderLive.Index, :index<br>live &quot;/orders/new&quot;, OrderLive.Index, :new<br>live &quot;/orders/:id/edit&quot;, OrderLive.Index, :edit<br>live &quot;/orders/:id&quot;, OrderLive.Show, :show<br>live &quot;/orders/:id/show/edit&quot;, OrderLive.Show, :edit</pre><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>Now if we fire up our server again ,</p><pre>mix phx.server </pre><p>And we go to /orders , we see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRWfQbhDeLuu5VJSR2J4Rg.png" /></figure><p>And we can also create a new order</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*si_JhnL5zGe53S_xLYlF7Q.png" /></figure><p>First and foremost , we would like to validate this data , ensure Numbers start with 254 and are 12 digits , emails have a certain format , for this , we can add some code to our orders schema files .</p><p>Head over to lib/chpter_phoenix/orders/order.ex and edit the changeset function to</p><pre> def changeset(order, attrs) do<br>    order<br>    |&gt; cast(attrs, [:phone_number, :customer_name, :customer_email, :delivery_location])<br>    |&gt; validate_required([:phone_number, :customer_name, :customer_email, :delivery_location])<br>    |&gt; validate_format(<br>      :phone_number,<br>      ~r/^254\d{9}$/,<br>      message: &quot;Number has to start with 254 and have 12 digits&quot;<br>    )<br>    |&gt; validate_format(:customer_email, ~r/^[^\s]+@[^\s]+$/, message: &quot;must have the @ sign and no spaces&quot;)<br>  end</pre><p>Here , we have added 2 extra validations using regex to ensure the right format of data enters our db .</p><p>Now if we give it a try</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HufTLB88V-UhMDkFpjwaSg.png" /></figure><p>This now works well , Let us now dive into payment .</p><p>For most payment systems , it is divided into 2 steps</p><ol><li>Initiation</li><li>Checking for payment .</li></ol><h3>Initiation</h3><p>Here , we send a post request to <a href="https://api.chpter.co/v1/initiate/mpesa-payment">https://api.chpter.co/v1/initiate/mpesa-payment</a> with the following body format as shown in their documentation.</p><pre>   body = %{<br>          customer_details: %{<br>            &quot;full_name&quot; =&gt; &quot;name,<br>            &quot;location&quot; =&gt; &quot;location&quot;,<br>            &quot;phone_number&quot; =&gt; phone_number,<br>            &quot;email&quot; =&gt; email<br>          },<br>          products: [<br>            <br>          ],<br>          amount: %{<br>            &quot;currency&quot; =&gt; &quot;KES&quot;,<br>            &quot;delivery_fee&quot; =&gt; 0.0,<br>            &quot;discount_fee&quot; =&gt; 0.0,<br>            &quot;total&quot; =&gt; 1<br>          },<br>          callback_details: %{<br>            &quot;transaction_reference&quot; =&gt; phone_number,<br>            &quot;callback_url&quot; =&gt; callback url<br>          }<br>        }</pre><p>And the header tag as follows .</p><pre><br>        headers = [<br>          {<br>            &quot;Content-Type&quot;,<br>            &quot;application/json&quot;<br>          },<br>          {<br>            &quot;Api-Key&quot;,<br>            &quot;api-key&quot;<br>          }<br>        ]</pre><p>In the header tag , we are sending 2 things , the Content Type and Api Key , the api key is provided by chpter upon registration and provision of KYC docs .</p><p>Now onto the body , for me , the most important details are</p><p>the customer details , the total amount , the callback url and the transaction reference .</p><p>I personally like having the transaction reference as a random unique number , there are various ways to do this , I use Timex for this . Using timex , we can get umique numbers as such 20231021160626 that we can concat with a phone number to make it really unique .</p><p>We will be using HTTPoison and Poison to make http requests so we need to add them to our mix.exs in addition to the</p><pre> {:poison, &quot;~&gt; 5.0&quot;},<br> {:httpoison, &quot;~&gt; 2.1&quot;},<br> {:timex, &quot;~&gt; 3.0&quot;},</pre><p>Run</p><pre>mix deps.get</pre><p>Since elixir is functional we can break this down into functions , one for getting the header , another one for the body and one for initiating payment.</p><p>In lib/chpter_phoenix , create a file and call it chpter.ex , this will be a module .</p><pre>defmodule ChpterPhoenix.Chpter do<br><br><br><br>end</pre><p>For initiation , we can have these functions</p><pre>defmodule ChpterPhoenix.Chpter do<br>  def initiate_payment(<br>        api_key,<br>        phone_number,<br>        name,<br>        email,<br>        amount,<br>        location,<br>        callback_url,<br>        transaction_reference<br>      ) do<br>    header = header(api_key)<br><br>    body =<br>      body(<br>        phone_number,<br>        email,<br>        name,<br>        location,<br>        amount,<br>        callback_url,<br>        transaction_reference<br>      )<br><br>    url = &quot;https://api.chpter.co/v1/initiate/mpesa-payment&quot;<br><br>    request_body = Poison.encode!(body)<br><br>    HTTPoison.post(url, request_body, header)<br>  end<br><br>  defp header(api_key) do<br>    [<br>      {<br>        &quot;Content-Type&quot;,<br>        &quot;application/json&quot;<br>      },<br>      {<br>        &quot;Api-Key&quot;,<br>        api_key<br>      }<br>    ]<br>  end<br><br>  defp body(<br>         phone_number,<br>         email,<br>         name,<br>         location,<br>         amount,<br>         callback_url,<br>          transaction_reference<br>       ) do<br>    %{<br>      customer_details: %{<br>        &quot;full_name&quot; =&gt; name,<br>        &quot;location&quot; =&gt; location,<br>        &quot;phone_number&quot; =&gt; phone_number,<br>        &quot;email&quot; =&gt; email<br>      },<br>      products: [],<br>      amount: %{<br>        &quot;currency&quot; =&gt; &quot;KES&quot;,<br>        &quot;delivery_fee&quot; =&gt; 0.0,<br>        &quot;discount_fee&quot; =&gt; 0.0,<br>        &quot;total&quot; =&gt; amount<br>      },<br>      callback_details: %{<br>        &quot;transaction_reference&quot; =&gt; transaction_reference,<br>        &quot;callback_url&quot; =&gt; callback_url<br>      }<br>    }<br>  end<br>end</pre><p>Now if we run</p><pre>iex -S mix phx.server</pre><pre>alias ChpterPhoenix.Chpter</pre><pre>Chpter.initiate_payment(                 <br>         &quot;pk_4aff02227456f6b499820c2621ae181c9e35666d25865575fef47622265dcbb9&quot;,<br>          &quot;254740769596&quot;,<br>          &quot;Michael Munavu&quot;,<br>          &quot;michaelmunavu83@gmail.com&quot;,<br>          1,<br>         &quot;Nairobi&quot;,<br>         &quot;thekultureke.com/api/mpesa_transactions&quot;,<br>&quot;transaction_ref&quot;<br><br>)</pre><p>If you replace the phone number with yours , you should get an stk push .</p><p>Now we are good on initiation.</p><p>Next , let us add a function to check whether a payment is successful , we will use recursion for this . Add this function in your chpter.ex file</p><pre> def check_for_payment(transaction_reference, api_endpoint) do<br>    body = HTTPoison.get!(api_endpoint)<br><br>    customer_record =<br>      Poison.decode!(body.body)[&quot;data&quot;]<br>      |&gt; Enum.find(fn record -&gt; record[&quot;transaction_reference&quot;] == transaction_reference end)<br><br>    customer_record<br><br>    if customer_record != nil do<br>      customer_record<br>    else<br>      Process.sleep(1000)<br>      check_for_payment(transaction_reference, api_endpoint)<br>    end<br> end</pre><p>This function checks to see if there is a record in our api whose transaction reference matches the unique transaction reference we pass when making our initiation and returns its body .</p><p>Let us now go to our form component for adding orders and impliment this , we shall edit the save function</p><p>We will set it up such that when you click create , you will get a prompt and immediately , we will also start checking for a payment .</p><pre>alias ChpterPhoenix.Chpter</pre><p>Add this at the top of lib/chpter_phoenix_web/live/order_live/form_component.ex</p><p>So you can have access to the function we wrote there.</p><p>Change the save function for a new record to</p><pre>defp save_order(socket, :new, order_params) do<br>    timestamp =<br>      Timex.local()<br>      |&gt; Timex.format!(&quot;{YYYY}{0M}{0D}{h24}{m}{s}&quot;)<br><br>    transaction_reference = order_params[&quot;phone_number&quot;] &lt;&gt; timestamp<br><br>    case Chpter.initiate_payment(<br>           &quot;pk_4aff02227456f6b499820c2621ae181c9e35666d25865575fef47622265dcbb9&quot;,<br>           &quot;254740769596&quot;,<br>           &quot;Michael Munavu&quot;,<br>           &quot;michaelmunavu83@gmail.com&quot;,<br>           1,<br>           &quot;Nairobi&quot;,<br>           &quot;https://720a-102-135-173-116.ngrok-free.app/api/transactions&quot;,<br>           transaction_reference<br>         ) do<br>      {:ok, %HTTPoison.Response{status_code: 200, body: body}} -&gt;<br>        customer_record =<br>          Chpter.check_for_payment(<br>            transaction_reference,<br>            &quot;http://localhost:4000/api/transactions&quot;<br>          )<br><br>        if customer_record[&quot;success&quot;] == true do<br>          case Orders.create_order(order_params) do<br>            {:ok, _order} -&gt;<br>              {:noreply,<br>               socket<br>               |&gt; put_flash(:info, &quot;Order created successfully&quot;)<br>               |&gt; push_redirect(to: socket.assigns.return_to)}<br><br>            {:error, %Ecto.Changeset{} = changeset} -&gt;<br>              {:noreply, assign(socket, changeset: changeset)}<br>          end<br>        else<br>          {:noreply,<br>           socket<br>           |&gt; put_flash(:error, &quot;Payment Failed , #{customer_record[&quot;message&quot;]}&quot;)<br>           |&gt; push_redirect(to: socket.assigns.return_to)}<br>        end<br><br>      {:ok, %HTTPoison.Response{status_code: 400, body: body}} -&gt;<br>        {:noreply,<br>         socket<br>         |&gt; put_flash(:info, &quot;Payment Failed &quot;)}<br><br>      {:error, %HTTPoison.Error{reason: reason}} -&gt;<br>        {:noreply,<br>         socket<br>         |&gt; put_flash(:info, &quot;Payment Failed , Timeout error&quot;)}<br>    end<br>  end</pre><p>For the callback url , chpter only allows it to be https urls , so we can use ngrok to translate our localhost:4000 to a https url , that is what I use for it .</p><p>Let us break down this code , we are initiating payment , we are having case statements to check if the initiation is correct , if it is right , we are then checking if a payment is made , once we get the payment , we see if it is succesful or not , if it is , we create the order .</p><p>Now , when we create an order , we see this .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dhwFa_1QGf6LjsW0rRchw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cr-ttNbMP10m-ZaVFaa9HA.png" /></figure><p>Thank you for reading this article , I beleive we have both learnt a thing or 2 and we can now easily integrate payments in our systems .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9406ac4d1039" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SENDING SMS USING YOUR PHOENIX APPLICATIONS.]]></title>
            <link>https://medium.com/@michaelmunavu83/sending-sms-using-your-phoenix-applications-69f29a1892f3?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f29a1892f3</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix]]></category>
            <category><![CDATA[sms-api]]></category>
            <category><![CDATA[sms]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 06:02:34 GMT</pubDate>
            <atom:updated>2023-09-04T06:02:34.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrwNK5m-UadmBcs311Hlbw.jpeg" /></figure><p>In today’s digital age, sending text messages through third-party APIs has become as natural as breathing in the world of communication. Imagine having a simple, user-friendly way to seamlessly integrate text messaging into your applications, websites, or business operations. Well, look no further, because Tiara Connect is your partner in taking your communication game to the next level. In this article, we’ll dive into the world of Tiara Connect and walk you through the process of using it to send SMS messages via third-party APIs.</p><p>Before we get started, go to <a href="https://app.tiaraconnect.io/#/dashboard">https://app.tiaraconnect.io/#/dashboard</a> and create an account.</p><p>Let us create A small Phoenix application that will allow us to send messages right from our website to a client&#39;s phone.</p><p>To get started.</p><pre>mix phx.new tiara_phoenix_sms</pre><p>Configure your database credentials in config/dev.exs</p><p>Create your database with</p><pre>mix ecto.create</pre><p>and migrate it with</p><pre>mix ecto.migrate .</pre><p>To fire up our server, we run</p><pre>mix phx.server</pre><p>Now if you visit localhost:4000, you should see something of the sort, depending on the version you are on .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNnSTGiwJCHQK_78PZnLyA.png" /></figure><h3><strong>Next step .</strong></h3><p>We can create a model of Messages that we would want to send, this would include the phone number of the person we want to send the text to and the actual text.</p><p>We will be using live view for this.</p><p>In your terminal run,</p><pre>mix phx.gen.live Messages Message messages phone_number text_message</pre><p>Add the live routes to your browser scope in lib/tiara_phoenix_sms_web/router.ex:</p><pre>live &quot;/messages&quot;, MessageLive.Index, :index<br>live &quot;/messages/new&quot;, MessageLive.Index, :new<br>live &quot;/messages/:id/edit&quot;, MessageLive.Index, :edit<br>live &quot;/messages/:id&quot;, MessageLive.Show, :show<br>live &quot;/messages/:id/show/edit&quot;, MessageLive.Show, :edit</pre><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>Now if we fire up our server once again, and go to /messages, we will see this.</p><p>We can go on and create a few messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fu2L9tuOVTRm9j0fgBPvyg.png" /></figure><p>As you can see, we can create messages, but the phone number is not in the right format, to avoid any issues, let us add a validation for this to allow for only numbers with the right format to be added to the database.</p><p>In the messages context file ie lib/tiara_phoenix_sms/messages/message.ex .</p><p>Let us add a new validation to our changeset function, add this line</p><pre>|&gt; validate_format(<br>:phone_number,<br>~r/²⁵⁴\d{9}$/,<br>message: &quot;Number has to start with 254 and have 12 digits&quot;<br>)</pre><p>such that we now have</p><pre>def changeset(message, attrs) do<br>message<br>|&gt; cast(attrs, [:phone_number, :text_message])<br>|&gt; validate_format(<br>:phone_number,<br>~r/²⁵⁴\d{9}$/,<br>message: &quot;Number has to start with 254 and have 12 digits&quot;<br>)<br>|&gt; validate_required([:phone_number, :text_message])<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qg4cKjn3A6pVqnEKn7S-3g.png" /></figure><p>Now we can only add numbers that have the right format.</p><h3>Now it is time to integrate the Tiara Connect third-party API .</h3><p>To get started, we will need to send HTTP requests from our Phoenix application, for this we will use httppotion , <a href="https://hexdocs.pm/httpoison/readme.html">https://hexdocs.pm/httpoison/readme.html</a> , we will also use Poison when encoding the body to a format elixir understands.</p><p>So in our mix file, mix.exs , add the following</p><pre>{:poison, &quot;~&gt; 5.0&quot;},<br>{:httpoison, &quot;~&gt; 2.1&quot;},</pre><p>and run mix deps.get</p><p>We will need an api key from tiara connect , for that visit <a href="https://app.tiaraconnect.io/#/csettings/applications">https://app.tiaraconnect.io/#/csettings/applications</a> under the http tab and create a new api key .</p><p>Now we are set .</p><p>Following their documentation, we will need to send a post request to a URL with certain headers and body.</p><p>Read more here.</p><p><a href="https://www.tiaraconnect.io/developer">https://www.tiaraconnect.io/developer</a>.</p><p>We would want to send a text every time a message is created in our Phoenix application , go into lib/tiara_phoenix_sms_web/live/messages/form_component.ex .</p><p>We will be working on this function.</p><pre>defp save_message(socket, :new, message_params) do<br>    case Messages.create_message(message_params) do<br>      {:ok, _message} -&gt;<br>        {:noreply,<br>         socket<br>         |&gt; put_flash(:info, &quot;Message created successfully&quot;)<br>         |&gt; push_redirect(to: socket.assigns.return_to)}<br><br>      {:error, %Ecto.Changeset{} = changeset} -&gt;<br>        {:noreply, assign(socket, changeset: changeset)}<br>    end<br>  end</pre><p>Just before the case statement add this piece of code.</p><pre> sms_url = &quot;https://api.tiaraconnect.io/api/messaging/sendsms&quot;<br><br>      sms_headers = [<br>        {<br>          &quot;Content-Type&quot;,<br>          &quot;application/json&quot;<br>        },<br>        {<br>          &quot;Authorization&quot;,<br>          &quot;Bearer &lt;api_key&gt;&quot;<br>        }<br>      ]<br><br>      sms_body =<br>        %{<br>          &quot;from&quot; =&gt; &quot;TIARACONECT&quot;,<br>          &quot;to&quot; =&gt; message_params[&quot;phone_number&quot;],<br>          &quot;message&quot; =&gt; message_params[&quot;text_message&quot;],<br>          &quot;refId&quot; =&gt; &quot;09wiwu088e&quot;<br>        }<br>        |&gt; Poison.encode!()<br><br>      <br><br>    <br>        HTTPoison.post(sms_url, sms_body, sms_headers)<br></pre><p>Add the API key you got from them in the Authorization header.</p><p>This piece of code sends a post request to the url provided with the necessary headers and body and thus sends an SMS.</p><p>The whole function should now look as such.</p><pre>defp save_message(socket, :new, message_params) do<br>    sms_url = &quot;https://api.tiaraconnect.io/api/messaging/sendsms&quot;<br><br>    sms_headers = [<br>      {<br>        &quot;Content-Type&quot;,<br>        &quot;application/json&quot;<br>      },<br>      {<br>        &quot;Authorization&quot;,<br>        &quot;Bearer &lt;api_key&gt;&quot;<br>      }<br>    ]<br><br>    sms_body =<br>      %{<br>        &quot;from&quot; =&gt; &quot;TIARACONECT&quot;,<br>        &quot;to&quot; =&gt; message_params[&quot;phone_number&quot;],<br>        &quot;message&quot; =&gt; message_params[&quot;text_message&quot;],<br>        &quot;refId&quot; =&gt; &quot;09wiwu088e&quot;<br>      }<br>      |&gt; Poison.encode!()<br><br>    HTTPoison.post(sms_url, sms_body, sms_headers)<br><br>    case Messages.create_message(message_params) do<br>      {:ok, _message} -&gt;<br>        {:noreply,<br>         socket<br>         |&gt; put_flash(:info, &quot;Message created successfully&quot;)<br>         |&gt; push_redirect(to: socket.assigns.return_to)}<br><br>      {:error, %Ecto.Changeset{} = changeset} -&gt;<br>        {:noreply, assign(socket, changeset: changeset)}<br>    end<br>  end</pre><p>So now when we create a message , it sends an SMS to that phone number .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Fit8GggyG3XcRH8dVUbutA.jpeg" /></figure><p>As we wrap up our journey through the world of Tiara Connect, you’ve not only learned how to use third-party APIs to send SMS messages but also witnessed the magic of modern communication solutions. Tiara Connect isn’t just a tool; it’s your trusted companion, guiding you from traditional communication methods to a world of seamless integration and unparalleled connectivity.</p><p>You can view the project from github here <a href="https://github.com/MICHAELMUNAVU83/tiara_phoenix_sms">https://github.com/MICHAELMUNAVU83/tiara_phoenix_sms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f29a1892f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCHE]]></title>
            <link>https://medium.com/@michaelmunavu83/mche-9c825a19b3d3?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c825a19b3d3</guid>
            <category><![CDATA[agriculture]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 13:03:11 GMT</pubDate>
            <atom:updated>2023-08-18T13:03:11.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kViZ5GV8RbTFE5tLePEhWw.png" /></figure><p>When you go up to any farmer in Kenya, Nigeria, in Africa and ask them the problems they face in their everyday life, they will tell you it is either poor productivity, lack of direct access to the market, or post-harvest losses, if they don’t, they are most likely not farmers.</p><p>A smallholder farmer is one who owns land between 0.5 ha — 5ha, In Kenya, this number is at 7.5 million, these farmers feed 75% of the</p><p>Kenyan population.</p><p>In Africa, this number rises up to around 33 million farms, the farmers in these farms feeding 70% of the continent.</p><p>It is smallholder farmers who face all these problems, smallholder farmers who feed 70% of the African continent, and farmers who were inspired to help.</p><p>What is Mche? Mche is a platform built for smallholder farmers. In this system farmers can select the location they want to farm, they then get the best crops to grow in this location, and they later get full advisory on how to best grow and manage a selected crop, in case they have any questions, they can contact extension officers in the system, additionally, they can talk to other farmers in a community tab within the system. There is also an AI chatbot that allows the farmer to ask the assistant any question.</p><p>Currently, they get this advisory in either English or Swahili, we plan on adding more languages to the system as only 53% of the smallholder farmers in Kenya understand English.</p><p>When it comes to harvesting , on Mche , farmers are given enough market intelligence to know the best point to price their crops at, we do this by showing trends of both retail and wholesale prices for that crop .</p><p>They can sell their high-quality produce directly to the buyers as we have an online marketplace that allows the farmer to post their crops and allows buyers to log in and buy these products.</p><p>In the case of any low-quality produce, they can also sell it through the platform to Animal feeds Suppliers and Livestock farmers .</p><p>We believe this platform solves the problems the Kenyan and African farmers have and we cannot wait to launch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c825a19b3d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Pagination in Phoenix Live View with Scrivener]]></title>
            <link>https://medium.com/@michaelmunavu83/streamlining-pagination-in-phoenix-live-view-with-scrivener-5ceb6e6fe642?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ceb6e6fe642</guid>
            <category><![CDATA[phoenix-liveview]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 07:43:29 GMT</pubDate>
            <atom:updated>2023-07-31T07:43:29.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWdpmoogplitU0DEFPdjBQ.png" /></figure><p>In the ever-evolving landscape of web development, finding efficient ways to handle pagination remains a crucial aspect of building responsive and user-friendly applications. Phoenix Live View, a cutting-edge real-time web framework, has gained popularity for its ability to create interactive user experiences without the need for traditional full-page reloads. When combined with Scrivener, a powerful pagination library, Phoenix Live View becomes an unstoppable duo for managing paginated data effortlessly. In this article, we’ll explore the seamless integration of Scrivener in Phoenix Live View and witness how it transforms the way we handle pagination.</p><p>First , create a new project with</p><pre>mix phx.new phoenix_pagination </pre><p>configure your database and run</p><pre>mix ecto.create .</pre><p>Before we set up pagination, let us set up a simple model so we can see our pagination in play</p><pre>mix phx.gen.live Books Book books title</pre><p>Add the live routes to your browser scope in</p><pre>lib/phoenix_pagination_web/router.ex:<br>live &quot;/&quot;, BookLive.Index, :index<br>live &quot;/books/new&quot;, BookLive.Index, :new<br>live &quot;/books/:id/edit&quot;, BookLive.Index, :edit<br>live &quot;/books/:id&quot;, BookLive.Show, :show<br>live &quot;/books/:id/show/edit&quot;, BookLive.Show, :edit</pre><p>Remove this line in the routes file .</p><pre>get &quot;/&quot;, PageController, :index .</pre><p>We want to ensure that in the root route , we see all our books</p><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>Let us fire up our server and have a look at what we have so far .</p><pre>mix phx.server </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKx7KGm7rvaQcSdTtjSDiw.png" /></figure><p>Let us add 10 records and see why we would need pagination for our phoenix systems .</p><p>We have this ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lF5HFhCtP1qn7Km_vAhsEg.png" /></figure><p>Now imagine if we had 10,000 records, it would be inefficient to display them all in one page, this is where pagination comes into play .</p><p>For this, we will use scrivener_ecto <a href="https://hex.pm/packages/scrivener_ecto">https://hex.pm/packages/scrivener_ecto</a></p><p>Add this to your mix.exs file</p><pre>{:scrivener_ecto, &quot;~&gt; 2.7&quot;}</pre><p>and run</p><pre>mix deps.get</pre><p>We’ll want to use Scrivener in our Repo module and set the page_size we want to use.</p><p>Let’s set ours to 5.</p><p>In <em>lib/phoenix_pagination/repo.ex</em> , modify it to</p><pre>defmodule PhoenixPagination.Repo do<br>  use Ecto.Repo,<br>     otp_app: :phoenix_pagination,<br>      adapter: Ecto.Adapters.Postgres<br>   use Scrivener, page_size: 5<br>end</pre><p>Let us create a function in our books context file in <em>lib/phoenix_pagination/books.ex</em></p><pre>def paginate_books(params) do<br>    Repo.paginate(Book, params)<br>  end</pre><p>Let us jump into our index.ex of the Books live module and modify how we are listing all books on our database.</p><p>This is how the mount function looks like ,</p><pre> def mount(_params, _session, socket) do<br>    {:ok, assign(socket, :books, list_books())}<br>  end</pre><p>We will be using the params parameter so we need to remove the _ before the params, update this function to</p><pre>def mount(params, _session, socket) do<br>    IO.inspect(Books.paginate_books(params))<br>    {:ok, assign(socket, :books, list_books())}<br>end</pre><p>Looking at our terminal, this is what we see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R71QQsFhArsU6dIdANcLVA.png" /></figure><p>We can access our books via the entries, the page_size refers to the number we set in our repo file, and since we set 5, we have 2 pages.</p><p>Have variables for each of these and pass them down the socket as such</p><pre> def mount(params, _session, socket) do<br><br>    books = Books.paginate_books(params).entries<br>    total_pages = Books.paginate_books(params).total_pages<br>    page_number = Books.paginate_books(params).page_number<br>    total_entries = Books.paginate_books(params).total_entries<br><br>    {:ok,<br>     socket<br>     |&gt; assign(:books, books)<br>     |&gt; assign(:total_pages, total_pages)<br>     |&gt; assign(:page_number, page_number)<br>     |&gt; assign(:total_entries, total_entries)}<br>  end</pre><p>We also need to update our handle_params as it will be the function that will help in navigating from one page to the other.</p><pre>  def handle_params(params, _url, socket) do<br>    books = Books.paginate_books(params).entries<br>    total_pages = Books.paginate_books(params).total_pages<br>    page_number = Books.paginate_books(params).page_number<br>    total_entries = Books.paginate_books(params).total_entries<br><br>    {:noreply,<br>     socket<br>     |&gt; assign(:books, books)<br>     |&gt; assign(:total_pages, total_pages)<br>     |&gt; assign(:page_number, page_number)<br>     |&gt; assign(:total_entries, total_entries)<br>     |&gt; apply_action(socket.assigns.live_action, params)}<br>  end</pre><p>Now when we look at our localhost server , we can only see 5 records as it is only showing the first page, just as we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUMpQgCEmfopcqi9KllIHQ.png" /></figure><p>We are on the right track, we now need to add links for going to different pages, the next and previous page.</p><p>In our index.html.heex file, just below the table add this div.</p><pre>&lt;div  style=&quot;display: flex; flex-direction: row; padding: 2px;&quot;&gt;<br>       <br>        &lt;div&gt;<br>        &lt;%= if @page_number &gt; 1 do %&gt;<br>          &lt;%= live_patch(<br>            to: Routes.book_index_path(@socket, :index, page: @page_number - 1),<br>            class: &quot;pagination-link&quot;<br>          ) do %&gt;<br>            &lt;div class=&quot;flex gap-2 items-center &quot;&gt;<br>              Previous<br>            &lt;/div&gt;<br>          &lt;% end %&gt;<br>        &lt;% end %&gt;<br>        &lt;/div&gt;<br><br>        &lt;div  style=&quot;display: flex; flex-direction: row; padding: 2px;&quot;&gt;<br><br>        &lt;%= for idx &lt;-  Enum.to_list(1..@total_pages) do %&gt;<br>          &lt;%= live_patch(<br>            to: Routes.book_index_path(@socket, :index, page: idx),<br>            class: &quot;pagination-link&quot;<br>          ) do %&gt;<br>            &lt;%= if @page_number == idx do %&gt;<br>              &lt;p style=&quot;border: 1px solid black; padding-left: 5px; padding-right: 5px;&quot;&gt;<br>                &lt;%= idx %&gt;<br>              &lt;/p&gt;<br>            &lt;% else %&gt;<br>              &lt;p style=&quot;padding-left: 5px; padding-right: 5px;&quot;&gt;<br>                &lt;%= idx %&gt;<br>              &lt;/p&gt;<br>            &lt;% end %&gt;<br>          &lt;% end %&gt;<br>        &lt;% end %&gt;<br>        &lt;/div&gt;<br><br>        &lt;div&gt;<br><br>        &lt;%= if @page_number &lt; @total_pages do %&gt;<br>          &lt;%= live_patch(<br>            to: Routes.book_index_path(@socket, :index, page: @page_number + 1),<br>            class: &quot;pagination-link&quot;<br>          )  do %&gt;<br>            &lt;div class=&quot;flex gap-2 items-center &quot;&gt;<br>              Next<br>            &lt;/div&gt;<br>          &lt;% end %&gt;<br>        &lt;% end %&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;</pre><p>In this div, we are first checking if we are on a page other than the first one, if so, we are displaying the previous link which takes us to a page number less one.</p><p>In the middle div, we want to show a link for each page that we have,</p><p>We also have different styles for when we are on that page.</p><p>The final div is for when the page_number is less than the total_pages we have a button for the Next Page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBQ-KqusT3WA7NpTOefsRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWO6G3VxMmJlPPgvclzOZQ.png" /></figure><p>Now we have Pagination added to our phoenix projects .</p><p>In conclusion, combining Scrivener with Phoenix Live View empowers developers to tackle pagination challenges like never before. By leveraging the power of live updates, seamless rendering, and streamlined pagination, you can enhance your users’ experiences and make data exploration a breeze.</p><p>To delve into the code and see firsthand how Scrivener and Phoenix Live View work together, check out the GitHub repository: <a href="https://github.com/MICHAELMUNAVU83/phoenix_pagination">https://github.com/MICHAELMUNAVU83/phoenix_pagination</a></p><p>Try integrating Scrivener into your Phoenix Live View projects, and witness the magic it brings to your pagination tasks. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ceb6e6fe642" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing User Experience with Live Search Feature using Phoenix Live View and Elixir]]></title>
            <link>https://medium.com/@michaelmunavu83/enhancing-user-experience-with-live-search-feature-using-phoenix-live-view-and-elixir-41b215874f62?source=rss-c6ddf71c5b16------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b215874f62</guid>
            <category><![CDATA[phoenix-liveview]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Michael Munavu]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 06:34:06 GMT</pubDate>
            <atom:updated>2023-07-03T06:34:06.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing User Experience with Live Search Feature using Phoenix Live View</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MY_5l7OgjnYphQPDK11IA.png" /></figure><p>In today’s fast-paced digital world, providing users with a seamless and efficient search experience is crucial for the success of any web application. One way to achieve this is by implementing a live search feature using Phoenix Live View. Phoenix Live View, a real-time server-rendering library for Elixir, empowers developers to build dynamic, interactive web applications without relying on client-side JavaScript frameworks. In this article, we will explore how to leverage the power of Phoenix Live View to create a live search feature that instantly updates search results as users type, enhancing user experience and increasing engagement.</p><p>To get started , we will generate a new application using mysql as our database.</p><pre>mix phx.new phoenix_liveview_search - database=mysql</pre><p>Configure your database credentials in</p><pre>config/dev.exs</pre><p>and then run</p><pre>mix ecto.create</pre><p>to create your database .</p><p>Once your database is up and running we can now get our hands dirty ,</p><p>We will be creating Products each with a name , price and quantity .</p><p>Run the command</p><pre>mix phx.gen.live Products Product products name:string price:integer quantity:integer</pre><p>Add the live routes to your browser scope in lib/phoenix_liveview_search_web/router.ex</p><pre>lib/phoenix_liveview_search_web/router.ex:<br>live &quot;/products&quot;, ProductLive.Index, :index<br>live &quot;/products/new&quot;, ProductLive.Index, :new<br>live &quot;/products/:id/edit&quot;, ProductLive.Index, :edit<br>live &quot;/products/:id&quot;, ProductLive.Show, :show<br>live &quot;/products/:id/show/edit&quot;, ProductLive.Show, :edit</pre><p>Remember to update your repository by running migrations:</p><pre>mix ecto.migrate</pre><p>In our routes to make sure we see the index page of the products once we open our app , we change</p><pre> get &quot;/&quot;, PageController, :index</pre><p>and replace it with</p><pre>live &quot;/&quot;, ProductLive.Index, :index</pre><p>Let us run up our server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BId1tLSaVCkJ-fOGB7oTA.png" /></figure><p>Let us add a few records .</p><p>Okay , now that we have a few records , we need to impliment a search feature , let us think about how we would do this .</p><p>We would need a form that will have an input , and we need to capture the value of this input and run a function every time it changes , we will use this value as parameters in a function that will return products with a similar name as the value passed .</p><p>We already know where to get started , we need to add the form , but remember forms in phoenix have a for={@changeset} so we first need to define our changeset in our live/product_live/index.ex</p><p>In our mount function ,we will modify it to this</p><pre>def mount(_params, _session, socket) do<br> {:ok,<br>   socket<br>   |&gt; assign(:products, list_products())<br>   |&gt; assign(:changeset, Products.change_product(%Product{}))}<br>end</pre><p>Now in our index.html.heex , we will come and define our form, our form will have a phx-change event of search that we will define in our index.ex later, but first, let us define our form as follows</p><pre>&lt;.form  let={f} id=&quot;search&quot; phx-change=&quot;search&quot;  for={@changeset}  &gt;<br><br>  &lt;%= text_input f, :search , placeholder: &quot;Search&quot; %&gt; <br><br><br>&lt;/.form&gt;</pre><p>To test this search event, we can write a simple function to do this in our index.ex file</p><pre> def handle_event(&quot;search&quot;, %{&quot;product&quot; =&gt; product_params}, socket) do<br>    IO.inspect(product_params[&quot;search&quot;])<br><br>    {:noreply,<br>     socket<br>     |&gt; put_flash(:info, &quot;Searching&quot;)}<br>  end</pre><p>This function should let us see the value we input into our input and should also put a flash, let us test it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oukWdriNanv6nxiINig_tg.png" /></figure><p>When we search, we now see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntE3fMj3mIrwuWxFUKqFCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*H8qgKSgX9WG_cmPn_OZGxw.png" /></figure><p>And we also see this in our terminal.</p><p>Now we need to declare a function in our schema that will take this input and return to us products with names similar to it , for this we will use the ilike .</p><p>let us go into lib/phoenix_liveview_search/products.ex and add this</p><pre>def get_search_results(search) do<br>   query = from p in Product, where: fragment(&quot;? LIKE ?&quot;, p.name, ^&quot;%#{search}%&quot;)<br>    Repo.all(query)<br>end</pre><p>This function will return us Products that have names that start with what we have searched for,</p><p>Now we need to assign products to the result of this function in our handle_event function for search in index.ex.</p><p>Our function will now look like this</p><pre>def handle_event(&quot;search&quot;, %{&quot;product&quot; =&gt; product_params}, socket) do<br>  {:noreply,<br>    socket<br>    |&gt; assign(:products, Products.get_search_results(product_params[&quot;search&quot;]))}<br>end</pre><p>Now when we test out our feature it works , Congratulations .</p><p>In conclusion, the live search feature implemented using Phoenix Live View opens up a new realm of possibilities for web developers. By utilizing the power of Elixir and Phoenix Live View’s real-time rendering capabilities, we can create a highly responsive and interactive search experience for users. The live search feature provides instant feedback as users type, eliminating the need for page reloads and providing real-time updates to search results. This not only enhances the overall user experience but also improves engagement and satisfaction.</p><p>If you’re interested in exploring how to implement a live search feature using Phoenix Live View, you can find a detailed example in this GitHub repository: [<a href="https://github.com/MICHAELMUNAVU83/phoenix_liveview_search">https://github.com/MICHAELMUNAVU83/phoenix_liveview_search</a>]. The repository contains the necessary code and instructions to get started with building your own live search feature. Feel free to fork the repository, experiment with the code, and adapt it to fit your specific application requirements.</p><p>With Phoenix Live View’s simplicity and efficiency, implementing a live search feature becomes a breeze, making it a valuable addition to any web application seeking to optimize user search experiences. So, why not harness the power of Phoenix Live View and take your search functionality to the next level?</p><p>GitHub repository link: [<a href="https://github.com/MICHAELMUNAVU83/phoenix_liveview_search">https://github.com/MICHAELMUNAVU83/phoenix_liveview_search</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b215874f62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>