• Stars
    star
    397
  • Rank 104,496 (Top 3 %)
  • Language
    Elixir
  • License
    GNU General Publi...
  • Created over 8 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“ˆ General purpose hits (page views) counter

Hits

hits-dwyl-teal-banner

GitHub Workflow Status codecov.io HitCount contributions welcome

Why?

@dwyl we have a few projects on GitHub ...

We want to instantly see the popularity of each of our repos to know what people are finding useful and help us decide where we need to be investing our time.

While GitHub has a basic "traffic" tab which displays page view stats, GitHub only records the data for the past 14 days and then it gets reset. The data is not relayed to the "owner" in "real time" and you would need to use the API and "poll" for data ... Manually checking who has viewed a project is exceptionally tedious when you have more than a handful of projects.


Why Phoenix (Elixir + PostgreSQL/Ecto)?

We wrote our MVP in Node.js, see: https://github.com/dwyl/hits-nodejs
That worked quite well to test the idea while writing minimal code.

We decided to re-write in Elixir/Phoenix because we want the reliability and fault tolerance of Erlang, built-in application monitoring (supervisor) and metrics (telemetry) and the built-in support for highly scalable WebSockets that will allow us to build an awesome real-time UX!

For more on "Why Elixir?" see: dwyl/learn-elixir#102


What?

A simple & easy way to see how many people have viewed your GitHub Repository.

There are already many "badges" that people use in their repos. See: github.com/dwyl/repo-badges
But we haven't seen one that gives a "hit counter" of the number of times a GitHub page has been viewed ...
So, in today's mini project we're going to create a basic Web Counter. https://en.wikipedia.org/wiki/Web_counter The counter is incremented only when the user agent or the ip addres is different. When testing the counter you can open a new browser to see the badge changed.

A Fully Working Production Phoenix App And Step-by-Step Tutorial?

Yes, that's right! Not only is this a fully functioning web app that is serving millions of requests per day in production right now, it's also a step-by-step example/tutorial showing you exactly how it's implemented.


How?

If you simply want to display a "hit count badge" in your project's GitHub page, visit: https://hits.dwyl.com to get the Markdown!

Run the App on localhost

To run the app on your localhost follow these easy steps:

0. Ensure your localhost has Node.js & Phoenix installed

see: before you start

1. Clone/Download the Code

git clone https://github.com/dwyl/hits.git && cd hits

2. Install the Dependencies

Install elixir/node dependencies and setup Webpack static asset compilation (with hot reloading):

mix deps.get
cd assets && npm install
node node_modules/webpack/bin/webpack.js --mode development && cd ..

3. Create the database

mix ecto.create && mix ecto.migrate

4. Run the App

mix phx.server

That's it!

Visit: http://localhost:4000/ (in your web browser)

hits-homepage-phoenix

Or visit any endpoint that includes .svg in the url, e.g: http://localhost:4000/yourname/project.svg

hits-example-badge

Refresh the page a few times and watch the count go up!

hit-count-42

note: the "Zoom" in chrome to 500% for effect.

Now, take your time to peruse the code in /test and /lib, and ask any questions by opening GitHub Issues: https://github.com/dwyl/hits/issues

Run the Tests

To run the tests on your localhost, execute the following command in your terminal:

mix test

To run the tests with coverage, run the following command in your terminal:

MIX_ENV=test mix cover

If you want to view the coverage in a web browser:

mix coveralls.html && open cover/excoveralls.html



Implementation

This is a step-by-step guide to building the Hits App from scratch in Phoenix.

Assumptions / Prerequisites

Create New Phoenix App

mix phx.new hits

When prompted to install the dependencies:

Fetch and install dependencies? [Yn]

Type Y and the Enter key to install.

You should see something like this in your terminal:

* running mix deps.get
* running cd assets && npm install && node node_modules/webpack/bin/webpack.js --mode development
* running mix deps.compile

We are almost there! The following steps are missing:

    $ cd hits

Then configure your database in config/dev.exs and run:

    $ mix ecto.create

Start your Phoenix app with:

    $ mix phx.server

You can also run your app inside IEx (Interactive Elixir) as:

    $ iex -S mix phx.server

Follow the instructions (run the following commands) to create the PostgreSQL database for the app:

cd hits
mix ecto.create

You should see the following in your terminal:

Compiling 13 files (.ex)
Generated hits app
The database for Hits.Repo has already been created

Run the default tests to confirm everything is working:

mix test

You should see the following output

Generated hits app
...

Finished in 0.03 seconds
3 tests, 0 failures

Randomized with seed 98214

Start the Phoenix server:

mix phx.server

That spits out a bunch of data about Webpack compilation:

[info] Running HitsWeb.Endpoint with cowboy 2.6.3 at 0.0.0.0:4000 (http)
[info] Access HitsWeb.Endpoint at http://localhost:4000

Webpack is watching the files…

Hash: 1fc94cc9b786e491ad40
Version: webpack 4.4.0
Time: 609ms
Built at: 05/05/2019 08:58:46
                Asset       Size       Chunks             Chunk Names
       ../css/app.css   10.6 KiB  ./js/app.js  [emitted]  ./js/app.js
               app.js   7.26 KiB  ./js/app.js  [emitted]  ./js/app.js
       ../favicon.ico   1.23 KiB               [emitted]
        ../robots.txt  202 bytes               [emitted]
../images/phoenix.png   13.6 KiB               [emitted]
   [0] multi ./js/app.js 28 bytes {./js/app.js} [built]
[../deps/phoenix_html/priv/static/phoenix_html.js] 2.21 KiB {./js/app.js} [built]
[./css/app.css] 39 bytes {./js/app.js} [built]
[./js/app.js] 493 bytes {./js/app.js} [built]
    + 2 hidden modules
Child mini-css-extract-plugin node_modules/css-loader/dist/cjs.js!css/app.css:
    [./node_modules/css-loader/dist/cjs.js!./css/app.css] 284 bytes {mini-css-extract-plugin} [built]
    [./node_modules/css-loader/dist/cjs.js!./css/phoenix.css] 10.9 KiB {mini-css-extract-plugin} [built]
        + 1 hidden module

Visit the app in your web browser to confirm it's all working: http://localhost:4000 phoenix-app-default-homepage

The default Phoenix App home page should be familiar to you if you followed our Chat example/tutorial github.com/dwyl/phoenix-chat-example

Create the Static Home Page

In order to help people understand what Hits is and how they can add a counter badge to their project, we have a simple (static) home page. In the interest of doing a "feature parity" migration from the Node.js MVP to the Phoenix version, we are just copying over the index.html at this stage; we can/will enhance it later.

Phoenix has the concept of a Layout template which allows us to put all layout related code in a single file and then each subsequent page of content does not have to worry about static (CSS/JS) assets and metadata. Open the file /lib/hits_web/templates/layout/app.html.eex in your text editor. It should look like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Hits Β· Phoenix Framework</title>
    <link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
  </head>
  <body>
    <header>
      <section class="container">
        <nav role="navigation">
          <ul>
            <li><a href="https://hexdocs.pm/phoenix/overview.html">Get Started</a></li>
          </ul>
        </nav>
        <a href="https://phoenixframework.org/" class="phx-logo">
          <img src="<%= Routes.static_path(@conn, "/images/phoenix.png") %>" alt="Phoenix Framework Logo"/>
        </a>
      </section>
    </header>
    <main role="main" class="container">
      <p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
      <p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
      <%= render @view_module, @view_template, assigns %>
    </main>
    <script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
  </body>
</html>

Let's remove the cruft and keep only the essential layout html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Hits</title>
    <!-- <link rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/> -->
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/css/tachyons.min.css"/>
  </head>
  <body class="">
    <main role="main"">

      <%= render @view_module, @view_template, assigns %>
    </main>
    <script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
    <style> /* custom classes for specific @dwyl color scheme */
      .teal {
        color: #4DB6AC;
      }
      .bg-teal {
        background: #4DB6AC;
      }
      body { /* dwyl font */
        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
      }
    </style>
  </body>
</html>

We removed the link to app.css and a couple of elements as we don't need them; we can always add them back later, that's the beauty of version control, nothing is ever "lost".

If you refresh the page you should see the following: phoenix-homepage-no-style

Don't panic, this is expected! We just removed app.css in the layout template and Phoenix does not have/use any Tachyons classes so no styling is present. We'll fix it in the next step.

Open the homepage template file in your editor: lib/hits_web/templates/page/index.html.eex

You should see something like this:

<section class="phx-hero">
  <h1><%= gettext "Welcome to %{name}!", name: "Phoenix" %></h1>
  <p>A productive web framework that<br/>does not compromise speed or maintainability.</p>
</section>

<section class="row">
  <article class="column">
    <h2>Resources</h2>
    <ul>
      <li>
        <a href="https://hexdocs.pm/phoenix/overview.html">Guides &amp; Docs</a>
      </li>
      <li>
        <a href="https://github.com/phoenixframework/phoenix">Source</a>
      </li>
      <li>
        <a href="https://github.com/phoenixframework/phoenix/blob/v1.4/CHANGELOG.md">v1.4 Changelog</a>
      </li>
    </ul>
  </article>
  <article class="column">
    <h2>Help</h2>
    <ul>
      <li>
        <a href="https://elixirforum.com/c/phoenix-forum">Forum</a>
      </li>
      <li>
        <a href="https://webchat.freenode.net/?channels=elixir-lang">#elixir-lang on Freenode IRC</a>
      </li>
      <li>
        <a href="https://twitter.com/elixirphoenix">Twitter @elixirphoenix</a>
      </li>
    </ul>
  </article>
</section>

Notice how the page template only has the HTML code relevant to rendering this page.
Let's replace the code in the file with the markup relevant to the Hits homepage:

<h2 class="bg-teal white h-25 tc ttu f1 lh-title lh-solid mt0 pa2 pb3 mb0 pb0">
  Hits!
  <a href="https://hits.dwyl.com/" >
    <img src="https://hits.dwyl.com/dwyl/homepage.svg" alt="Hit Count" class="pa0 ba bw1 b--white">
  </a>
</h2>
<h4 class="mt0 tc fw5 f5 teal pa2 mb0">
  The <em>easy</em> way to know how many people are
  <strong><em>viewing</em></strong> your GitHub projects!
</h4>

<h2 class="mt0 fw5 tc f2 bg-teal white pa2"><em>How?</em></h2>
<div id="how" class="dn pa3">

  <table class="collapse pv2 ph3 w-100 pa4">
    <tr class="bb-0">
      <td class="pv2 ph3 w-30">
        Input your <strong class="fw5">GitHub Username</strong>
        (<em> <strong class="u">or</strong> org name</em>):
      </td>
      <td class="pv2 ph3 w-30">
        <input class="input-reset f4 pa2 ba mr5 w-80" type="text"
        id="username" name="username" placeholder="username" autofocus maxlength="50">
      </td>
    </tr>
    <tr class="">
      <td class="pv2 ph3 w-40">
        Input the <strong class="fw5">GitHub Project/Repository</strong>
        name:
      </td>
      <td class="pv2 ph3 w-40">
        <input class="input-reset f4 pa2 ba mr5 w-80" type="text"
        id="repo" name="repo" placeholder="repo/project" maxlength="100">
      </td>
    </tr>
    <tr class="">
      <td class="pv2 ph3 w-40">
        Choose a style for your badge:
      </td>
      <td class="pv2 ph3 w-40">
    <select id="styles">
      <option value="flat-square" selected>Flat Square</option>
      <option value="flat">Flat</option>
    </select>
      </td>
    </tr>
  </table>
</div>

<h3 class="mt3 fw5 tc db f3 bg-teal white pa2">Your Badge <em>Markdown:</em></h3>
<pre id="badge" class="fw4 ba bw1 pa3 ma2" style="white-space: pre-wrap; word-break: keep-all;">
  [![HitCount](https://hits.dwyl.com/{username}/{repo}.svg?style={style})](https://hits.dwyl.com/{username}/{repo})
</pre>

<p class="pl2" id="nojs">
  Using the above markdown as a template, <br />
  <em>Replace</em> the <strong class="code">{username}</strong> with <em>your</em> GitHub username <br />
  <em>Replace</em> the <strong class="code">{repo}</strong> with the repo name.
</p>

<p class="pl2 ml2">
<em>Copy</em> the markdown snippet and <em>Paste</em> it into your
<strong class="code">README.md</strong> file <br />
  to start tracking the view count on your GitHub project!
</p>

<h2 class="mt0 fw5 tc f4 bg-teal white pa2 mt5"><em>Recently</em> Viewed Projects (<em>tracked by Hits</em>)</h2>
<div class="h5 pl2" id='hits'>
  <div style="display:none">Dummy Child Node for insertBefore to work</div>
</div>

Note: we are using Tachyons (Functional) CSS for styling the page, if you haven't yet learned about Tachyons, we recommend reading: github.com/dwyl/learn-tachyons

This is a fairly simple homepage. The only interesting part are the Tachyons styles which are fairly straightforward.

Finally we need to update assets/js/app.js to add the code to render a badge when people input their username and repo name.

Open the assets/js/app.js which should look like this:

// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import css from "../css/app.css"

// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import dependencies
//
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative paths, for example:
// import socket from "./socket"

Add the following lines to the end:

// Markdown Template
var mt = document.getElementById('badge').innerHTML;

function generate_markdown () {
  var user = document.getElementById("username").value || '{username}';
  var repo = document.getElementById("repo").value || '{project}';
  var style = document.getElementById("styles").value || '{style}';
  // console.log('user: ', user, 'repo: ', repo);
  user = user.replace(/[.*+?^$<>()|[\]\\]/g, ''); // trim and escape
  repo = repo.replace(/[.*+?^$<>()|[\]\\]/g, '');
  return mt.replace(/{username}/g, user).replace(/{repo}/g, repo).replace(/{style}/g, style);
}

function display_badge_markdown () {
  var md = generate_markdown()
  var pre = document.getElementById("badge").innerHTML = md;
}

setTimeout(function () {
  var how = document.getElementById("how");
  // show form if JS available (progressive enhancement)
  if(how) {
    document.getElementById("how").classList.remove('dn');
    document.getElementById("nojs").classList.add('dn');
    display_badge_markdown(); // render initial markdown template
    var get = document.getElementsByTagName('input');
   for (var i = 0; i < get.length; i++) {
       get[i].addEventListener('keyup', display_badge_markdown, false);
       get[i].addEventListener('keyup', display_badge_markdown, false);
   }

    // changing markdown preview whenever an option is selected
    document.getElementById("styles").onchange = function(e) {
      display_badge_markdown()
    }
  }
}, 500);

Run the Phoenix server to see the static page:

mix phx.server

Now visit the route in your web browser: http://localhost:4000

hits-static-homepage

Now that the static homepage is working, we can move on to the interesting part of the Hits Application!

As always, if you have questions or got stuck at any point, please open an issue and we will help! https://github.com/dwyl/hits/issues

Fix The Failing Test

Before moving on to building the app, let's make sure that the default tests are passing ...

mix test

failing-test

The reason for this failing test is pretty clear, the page no longer contains the words "Welcome to Phoenix!".

Open the file test/hits_web/controllers/page_controller_test.exs and update the assertion text.

From:

test "GET /", %{conn: conn} do
  conn = get(conn, "/")
  assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end

To:

test "GET /", %{conn: conn} do
  conn = get(conn, "/")
  assert html_response(conn, 200) =~ "Hits!"
end

Re-run the test:

mix test

hits-static-page-test-passing

The test should now pass and we can crack on with creating the schemas!

Create The Database for Storing Data

As is typical of most Phoenix applications, we will be using a PostgreSQL database for storing data.

In your terminal, run the create script:

mix ecto.create

In your terminal you should see:

Compiling 2 files (.ex)
The database for Hits.Repo has been created

This tells you the PostgreSQL database hits_dev was successfully created.

Note on Database Normalization

In designing the Hits App database, we decided to normalize the database tables for efficient storage because we wanted to make the storage of an individual hit as minimal as possible. This means we have 4 schemas/tables to ensure there is no duplicate data and each bit of data is only stored once. We could have stored all the data in a single table and on the surface this is appealing because it would only require one insert query and no "joins" when selecting/counting hits. But the initial benefit of a single table would be considerably outweighed by the wasted space of duplicate data.

This is not the time or place to dive into the merits of database normalization and denormalisation. We will have a chance to explore it later when we need to optimise query performance. For now we are focussing on building the App with a database normalized to the third normal form (3NF) because it achieves a good balance of eliminating data duplication thus maximising storage efficiency while still having adequate query performance.

You won't need to understand any of these concepts to follow along with building the Hits app. But if you are curious about any of these words, read the following pages:

Create the 4 Schemas

  • users - for simplicity sake we are assuming that all repositories belong to a "user" and not an organisation.
  • repositories - the projects on GitHub
  • useragents - the web browsers viewing the project pages
  • hits - the record of each "hit" (page view).
mix phx.gen.schema User users name:string
mix phx.gen.schema Repository repositories name:string user_id:references:users
mix phx.gen.schema Useragent useragents name:string ip:string
mix phx.gen.schema Hit hits repo_id:references:repositories useragent_id:references:useragents

In your terminal, you will see a suggestion in the terminal output similar to this:

Before we can run the database migration, we must create the database.

Now we can run the scripts to create the database tables:

mix ecto.migrate

In your terminal, you should see:

Compiling 17 files (.ex)
Generated hits app
[info] == Running 20190515211749 Hits.Repo.Migrations.CreateUsers.change/0 forward
[info] create table users
[info] == Migrated 20190515211749 in 0.0s
[info] == Running 20190515211755 Hits.Repo.Migrations.CreateRepositories.change/0 forward
[info] create table repositories
[info] create index repositories_user_id_index
[info] == Migrated 20190515211755 in 0.0s
[info] == Running 20190515211804 Hits.Repo.Migrations.CreateUseragents.change/0 forward
[info] create table useragents
[info] == Migrated 20190515211804 in 0.0s
[info] == Running 20190515211819 Hits.Repo.Migrations.CreateHits.change/0 forward
[info] create table hits
[info] create index hits_repo_id_index
[info] create index hits_useragent_id_index
[info] == Migrated 20190515211819 in 0.0s

Note: the dates of your migration files will differ from these. The 14 digit number corresponds to the date and time in the format YYYYMMDDHHMMSS. This is helpful for knowing when the database schemas/fields were created or updated.

To make sure users, useragents and repositories are unique, three more migrations are created to add unique_index:

For users we want the name to be unique

  def change do
    create unique_index(:users, [:name])
  end

For useragents, we want the name and the ip address unique

  def change do
    create unique_index(:useragents, [:name, :ip])
  end

Finally for repositories we want the name and the relation to the user to be unique

  def change do
    create unique_index(:repositories, [:name, :user_id])
  end

These unique indexes insure that no duplicates are created at the database level.

We can now use the upsert Ecto/Postgres feature to only create new items or updating the existing items.

For example with useragent:

    Repo.insert!(changeset,
      on_conflict: [set: [ip: changeset.changes.ip, name: changeset.changes.name]],
      conflict_target: [:ip, :name]
    )
  • conflict_target: Define which fields to check for existing entry
  • on_conflict: Define what to do when there is a conflict. In our case we update the ip and name values.

View the Entity Relationship (ER) Diagram

Now that the Postgres database tables have been created, you can fire up your database client (e.g: DBeaver in this case) and view the Entity Relationship (ER) Diagram:

hits-er-diagram

This us shows us the four tables we created above and how they are related (with foreign keys). It also shows us that there is schema_migrations table, which is unrelated to the tables we created for our app, but contains the log of the schema migrations that have been run and when they were applied to the database:

hits-schema-migrations

The keen observer will note that the migration table data:

version       |inserted_at        |
--------------|-------------------|
20190515211749|2019-05-15 21:18:38|
20190515211755|2019-05-15 21:18:38|
20190515211804|2019-05-15 21:18:38|
20190515211819|2019-05-15 21:18:38|

The version column corresponds to the date timestamps in the migration file names:

priv/repo/migrations/20190515211749_create_users.exs
priv/repo/migrations/20190515211755_create_repositories.exs
priv/repo/migrations/20190515211804_create_useragents.exs
priv/repo/migrations/20190515211819_create_hits.exs

Run the Tests

Once you have created the schemas and run the resulting migrations, it's time to run the tests!

mix test

Everything should still pass because phx.gen.schema does not create any new tests and our previous tests are unaffected.


SVG Badge Template

We created the SVG badge template for our MVP template.svg and it still serves our needs so there's no need to change it.

Create a new file lib/hits_web/templates/hit/badge_flat_square.svg and paste the following SVG code in it:

<?xml version="1.0"?> <!-- SVG container is 80 x 20 pixel rectangle -->
<svg xmlns="http://www.w3.org/2000/svg" width="80" height="20">
	<rect width="30" height="20" fill="#555"/> <!-- grey rectangle 30px width -->
	<rect x="30" width="50" height="20" fill="#4c1"/> <!-- green rect 30px -->
	<g fill="#fff" text-anchor="middle" font-size="11"
    font-family="DejaVu Sans,Verdana,Geneva,sans-serif">   <!-- group & font -->
	    <text x="15" y="14">hits</text>                      <!-- "hits" label -->
	    <text x="54" y="14">{count}</text>  <!-- count is replaced with number -->
	</g>
</svg> <!-- that's it! pretty simple, right? :-) Any questions? Ask! -->

The comments are there for beginner-friendliness, they are stripped out before sending the badge to the client to conserve bandwidth.

Alternative Badge Formats 🌈

Several people have requested an alternative badge format. Rather than spend a lot of time customizing the badges ourselves, we are going to use shields.io/endpoint that allows full badge customization.

Adding JSON Content Negotiation

First thing we need to do is add the ability to return JSON instead of SVG. In HTTP this is referred to as Content Negotiation: wikipedia.org/wiki/Content_negotiation

Installing params and content

We are using params to validate the query parameters and content to add content negotiation on our endpoints.

Let's install these by adding them to the deps section mix.exs:

  defp deps do
    [
      # For content negotiation
      {:content, "~> 1.3.0"},

      # Query param schema validation
      {:params, "~> 2.0"},
    ]
  end

Defining Validation Schema

The schema must be compatible with shield.io. We make use of a schema validator so we know that the parameters passed by the users are valid.

The possible values of each field were determined according to shields.io/endpoint

The valid parameters are:

defparams schema_validator %{
  user!: :string,
  repository!: :string,
  style: [
    field: Ecto.Enum, 
    values: [
      plastic: "plastic", 
      flat: "flat", 
      flatSquare: "flat-square", 
      forTheBadge: "for-the-badge", 
      social: "social"
    ], 
    default: :flat
  ],
  color: [field: :string, default: "lightgrey"],
  show: [field: :string, default: nil],
}

By default, each badge is lightgrey and has a flat style.

This defparams defintion is in the /lib/hits_web/controllers/hit_controller.ex file.

Content negotiation

Luckily, the content package makes it relatively easy to differentiate HTTP and JSON requests.

The way we implement different behaviours for JSON requests is made through the following template:

  if Content.get_accept_header(conn) =~ "json" do
    # return json 
  else
    # render page
  end

You will notice this behaviour in lib/hits_web/controllers/hit_controller.ex

After correct setup, the returned JSON object depends on the parameters the user defines.

  def render_json(conn, count, params) do
    json_response = %{
      "schemaVersion" => "1",
      "label" => "hits",
      "style" => params.style,
      "message" => count,
      "color" => params.color
    }
    json(conn, json_response)
  end

This function effectively makes it so the endpoint returns a JSON object following Shields.io schema convention which can later be used in shields.io/endpoint

Expected JSON response

If you run mix phx.server and open a separate terminal session, paste the following cURL command and run:

curl -H "Accept: application/json" http://localhost:4000/user/repo\?color=blue

The output will be the following.

{"color":"blue","label":"hits","message":6,"schemaVersion":"1","style":"flat"}%

You can easily check the JSON in a web browser too. Simply open Firefox and visit the URL: http://localhost:4000/user/repo.json?color=blue

json-in-browser

And if you replace the .json in the URL with .svg you will see the badge as expected: http://localhost:4000/user/repo.svg

svg-in-browser

The same endpoint is used for both HTTP requests and also outputs a JSON object.

Now for the fun part!!

Using Shields to Create Any Style of Button!

https://img.shields.io/endpoint?url=https://hits.dwyl.com/dwyl/hits.json?style=flat-square&show=unique?color=orange

Fully customizable:

fully-custom

Custom badge Custom badge Custom badge

Plenty of logos to chose from at: https://simpleicons.org

tl;dr

draw-the-dog

But seriously, if you want a step-by-step tutorial, leave a comment on: #74

Add Channel

If you are new to Phoenix Channels, please recap: https://github.com/dwyl/phoenix-chat-example

In your terminal, run the following command:

mix phx.gen.channel Hit

You should see the following output:

* creating lib/hits_web/channels/hit_channel.ex
* creating test/hits_web/channels/hit_channel_test.exs

Add the channel to your `lib/hits_web/channels/user_socket.ex` handler, for example:

    channel "hit:lobby", HitsWeb.HitChannel

If you want to see the code required to render the hits on the homepage in realtime, please see: https://github.com/dwyl/hits/pull/80/files

Research & Background Reading

If you found this repository useful, please ⭐️ it so we (and others) know you liked it!

We found the following links/articles/posts useful when learning how to build this mini-project:

More Repositories

1

english-words

πŸ“ A text file containing 479k English words for all your dictionary/word-based projects e.g: auto-completion / autosuggestion
Python
9,337
star
2

learn-json-web-tokens

πŸ” Learn how to use JSON Web Token (JWT) to secure your next Web App! (Tutorial/Example with Tests!!)
JavaScript
4,178
star
3

learn-to-send-email-via-google-script-html-no-server

πŸ“§ An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
HTML
3,047
star
4

repo-badges

⭐ Use repo badges (build passing, coverage, etc) in your readme/markdown file to signal code quality in a project.
HTML
2,831
star
5

learn-tdd

βœ… A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
JavaScript
2,698
star
6

start-here

πŸ’‘ A Quick-start Guide for People who want to dwyl ❀️ βœ…
1,725
star
7

learn-elixir

πŸ’§ Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
Elixir
1,586
star
8

learn-travis

😎 A quick Travis CI (Continuous Integration) Tutorial for Node.js developers
JavaScript
1,251
star
9

Javascript-the-Good-Parts-notes

πŸ“– Notes on the seminal "JavaScript the Good Parts: by Douglas Crockford
1,173
star
10

aws-sdk-mock

🌈 AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
JavaScript
1,079
star
11

learn-aws-lambda

✨ Learn how to use AWS Lambda to easily create infinitely scalable web services
JavaScript
1,035
star
12

book

πŸ“— Our Book on Full-Stack Web Application Development covering User Experience (UX) Design, Mobile/Offline/Security First, Progressive Enhancement, Continuous Integration/Deployment, Testing (UX/TDD/BDD), Performance-Driven-Development and much more!
Rust
816
star
13

hapi-auth-jwt2

πŸ”’ Secure Hapi.js authentication plugin using JSON Web Tokens (JWT) in Headers, URL or Cookies
JavaScript
795
star
14

learn-hapi

β˜€οΈ Learn to use Hapi.js (Node.js) web framework to build scalable apps in less time
HTML
794
star
15

phoenix-chat-example

πŸ’¬ The Step-by-Step Beginners Tutorial for Building, Testing & Deploying a Chat app in Phoenix 1.7 [Latest] πŸš€
Elixir
721
star
16

learn-tachyons

😍 Learn how to use Tachyons to craft beautiful, responsive and fast UI with functional CSS!
HTML
670
star
17

learn-phoenix-framework

πŸ”₯ Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. πŸš€
Elixir
639
star
18

learn-nightwatch

🌜 Learn how to use Nightwatch.js to easily & automatically test your web apps in *real* web browsers.
JavaScript
585
star
19

javascript-todo-list-tutorial

βœ… A step-by-step complete beginner example/tutorial for building a Todo List App (TodoMVC) from scratch in JavaScript following Test Driven Development (TDD) best practice. 🌱
JavaScript
565
star
20

learn-elm

🌈 discover the beautiful programming language that makes front-end web apps a joy to build and maintain!
HTML
472
star
21

learn-redux

πŸ’₯ Comprehensive Notes for Learning (how to use) Redux to manage state in your Web/Mobile (React.js) Apps.
HTML
446
star
22

learn-devops

🚧 Learn the craft of "DevOps" (Developer Operations) to Deploy your App and Monitor it so it stays "Up"!
Shell
411
star
23

hapi-socketio-redis-chat-example

πŸ’¬ Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub (example with tests!!)
Elm
363
star
24

hapi-typescript-example

⚑ Hapi.Js + Typescript = Awesomeness
TypeScript
351
star
25

phoenix-liveview-counter-tutorial

🀯 beginners tutorial building a real time counter in Phoenix 1.7.7 + LiveView 0.19 ⚑️ Learn the fundamentals from first principals so you can make something amazing! πŸš€
Elixir
345
star
26

learn-istanbul

🏁 Learn how to use the Istanbul JavaScript Code Coverage Tool
JavaScript
339
star
27

learn-redis

πŸ“• Need to store/access your data as fast as possible? Learn Redis! Beginners Tutorial using Node.js πŸš€
JavaScript
291
star
28

technology-stack

πŸš€ Detailed description + diagram of the Open Source Technology Stack we use for dwyl projects.
JavaScript
281
star
29

phoenix-ecto-encryption-example

πŸ” A detailed example for how to encrypt data in an Elixir (Phoenix v1.7) App before inserting into a database using Ecto Types
Elixir
269
star
30

learn-elasticsearch

πŸ” Learn how to use ElasticSearch to power a great search experience for your project/product/website.
Elixir
265
star
31

home

🏑 πŸ‘©β€πŸ’» πŸ’‘ home is where you can [learn to] build the future surrounded by like-minded creative, friendly and [intrinsically] motivated people focussed on health, fitness and making things people and the world need!
245
star
32

elixir-auth-google

πŸ‘€Minimalist Google OAuth Authentication for Elixir Apps. Tested, Documented & Maintained. Setup in 5 mins. πŸš€
Elixir
228
star
33

learn-docker

🚒 Learn how to use docker.io containers to consistently deploy your apps on any infrastructure.
Dockerfile
220
star
34

learn-elm-architecture-in-javascript

πŸ¦„ Learn how to build web apps using the Elm Architecture in "vanilla" JavaScript (step-by-step TDD tutorial)!
JavaScript
207
star
35

learn-environment-variables

πŸ“Learn how to use Environment Variables to keep your passwords and API keys secret. πŸ”
JavaScript
201
star
36

learn-postgresql

🐘 Learn how to use PostgreSQL and Structured Query Language (SQL) to store and query your relational data. πŸ”
JavaScript
195
star
37

learn-tape

βœ… Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial
JavaScript
185
star
38

sendemail

πŸ’Œ Simplifies reliably sending emails from your node.js apps using AWS Simple Email Service (SES)
JavaScript
181
star
39

phoenix-todo-list-tutorial

βœ… Complete beginners tutorial building a todo list from scratch in Phoenix 1.7 (latest)
Elixir
171
star
40

decache

:shipit: Delete Cached node_modules useful when you need to "un-require" during testing for a fresh state.
JavaScript
151
star
41

quotes

πŸ’¬ a curated list of quotes that inspire action + code that returns quotes by tag/author/etc. πŸ’‘
Elixir
150
star
42

learn-heroku

🏁 Learn how to deploy your web application to Heroku from scratch step-by-step in 7 minutes!
Python
149
star
43

learn-chrome-extensions

🌐 Discover how to build and deploy a Google Chrome Extension for your Project!
139
star
44

labels

🏷 Sync GitHub Labels from any Source to Target Repositories for Consistency across all your projects!
Elixir
136
star
45

ISO-27001-2013-information-technology-security

πŸ” Probably the most boring-but-necessary repo on GitHub. If you care about the security/privacy of your data...! βœ…
136
star
46

learn-ab-and-multivariate-testing

πŸ†Ž Tutorial on A/B and multivariate testing βœ”οΈ
135
star
47

web-form-to-google-sheet

A simple example of sending data from an ordinary web form straight to a Google Spreadsheet without a server.
HTML
133
star
48

app

Clear your mind. Organise your life. Ignore distractions. Focus on what matters.
Dart
133
star
49

auth

πŸšͺ πŸ” UX-focussed Turnkey Authentication Solution for Web Apps/APIs (Documented, Tested & Maintained)
Elixir
124
star
50

learn-circleci

βœ… A quick intro to Circle CI (Continuous Integration) for JavaScript developers.
121
star
51

learn-regex

⁉️ A simple REGular EXpression tutorial in JavaScript
120
star
52

learn-react

"The possibilities are numerous once we decide to act and not react." ~ George Bernard Shaw
HTML
108
star
53

learn-aws-iot

πŸ’‘ Learn how to use Amazon Web Services Internet of Things (IoT) service to build connected applications.
JavaScript
101
star
54

env2

πŸ’» Simple environment variable (from config file) loader for your node.js app
JavaScript
100
star
55

phoenix-liveview-chat-example

πŸ’¬ Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS
Elixir
98
star
56

how-to-choose-a-database

How to choose the right dabase
93
star
57

imgup

πŸŒ… Effortless image uploads to AWS S3 with automatic resizing including REST API.
Elixir
88
star
58

contributing

πŸ“‹ Guidelines & Workflow for people contributing to our project(s) on GitHub. Please ⭐ to confirm you've read & understood! βœ…
85
star
59

javascript-best-practice

A collection of JavaScript Best Practices
83
star
60

learn-amazon-web-services

⭐ Amazing Guide to using Amazon Web Services (AWS)! ☁️
83
star
61

range-touch

πŸ“± Use HTML5 range input on touch devices (iPhone, iPad & Android) without bloatware!
JavaScript
83
star
62

learn-pre-commit

βœ… Pre-commit hooks let you run checks before allowing a commit (e.g. JSLint or check Test Coverage).
JavaScript
80
star
63

product-owner-guide

πŸš€ A rough guide for people working with dwyl as Product Owners
78
star
64

phoenix-ecto-append-only-log-example

πŸ“ A step-by-step example/tutorial showing how to build a Phoenix (Elixir) App where all data is immutable (append only). Precursor to Blockchain, IPFS or Solid!
Elixir
78
star
65

mvp

πŸ“² simplest version of the @dwyl app
Elixir
78
star
66

goodparts

πŸ™ˆ An ESLint Style that only allows JavaScript the Good Parts (and "Better Parts") in your code.
JavaScript
77
star
67

hapi-error

β˜” Intercept errors in your Hapi Web App/API and send a *useful* message to the client OR redirect to the desired endpoint.
JavaScript
76
star
68

flutter-todo-list-tutorial

βœ… A detailed example/tutorial building a cross-platform Todo List App using Flutter πŸ¦‹
Dart
75
star
69

process-handbook

πŸ“— Contains our processes, questions and journey to creating a team
HTML
75
star
70

dev-setup

✈️ A quick-start guide for new engineers on how to set up their Dev environment
73
star
71

aws-lambda-deploy

☁️ πŸš€ Effortlessly deploy Amazon Web Services Lambda function(s) with a single command. Less to configure. Latest AWS SDK and Node.js v20!
JavaScript
72
star
72

terminate

♻️ Terminate a Node.js Process (and all Child Processes) based on the Process ID
JavaScript
71
star
73

fields

🌻 fields is a collection of useful field definitions (Custom Ecto Types) that helps you easily define an Ecto Schema with validation, encryption and hashing functions so that you can ship your Elixir/Phoenix App much faster!
Elixir
69
star
74

learn-flutter

πŸ¦‹ Learn how to use Flutter to Build Cross-platform Native Mobile Apps
JavaScript
69
star
75

hapi-login-example-postgres

🐰 A simple registration + login form example using hapi-register, hapi-login & hapi-auth-jwt2 with a PostgreSQL DB
JavaScript
69
star
76

phoenix-liveview-todo-list-tutorial

βœ… Beginners tutorial building a Realtime Todo List in Phoenix 1.6.10 + LiveView 0.17.10 ⚑️ Feedback very welcome!
Elixir
64
star
77

learn-security

πŸ” For most technology projects Security is an "after thought", it does not have to be that way; let's be proactive!
64
star
78

learn-javascript

A Series of Simple Steps in JavaScript :-)
HTML
63
star
79

chat

πŸ’¬ Probably the fastest, most reliable/scalable chat system on the internet.
Elixir
62
star
80

learn-jsdoc

πŸ“˜ Use JSDoc and a few carefully crafted comments to document your JavaScript code!
CSS
60
star
81

ampl

πŸ“± ⚑ Ampl transforms Markdown into AMP-compliant html so it loads super-fast!
JavaScript
57
star
82

aguid

❄️ A Globally Unique IDentifier (GUID) generator in JS. (deterministic or random - you chose!)
JavaScript
56
star
83

tudo

βœ… Want to see where you could help on an open dwyl issue?
Elixir
56
star
84

learn-apple-watch-development

πŸ“— Learn how to build Native Apple Watch (+iPhone) apps from scratch!
Swift
55
star
85

learn-qunit

βœ… A quick introduction to JavaScript unit testing with QUnit
JavaScript
51
star
86

learn-ngrok

☁️ Learn how to use ngrok to share access to a Web App/Site running on your "localhost" with the world!
HTML
50
star
87

hapi-auth-jwt2-example

πŸ”’ A functional example Hapi.js app using hapi-auth-jwt2 & Redis (hosted on Heroku) with tests!
JavaScript
49
star
88

learn-jshint

πŸ’© Learn how to use the ~~jshint~~ code quality/consistency tool.
JavaScript
49
star
89

tachyons-bootstrap

πŸ‘’Bootstrap recreated using tachyons functional css
HTML
49
star
90

esta

πŸ” Simple + Fast ElasticSearch Node.js client. Beginner-friendly defaults & Heroku support βœ… πŸš€
JavaScript
48
star
91

learn-node-js-by-example

☁️ Practical node.js examples.
HTML
47
star
92

product-roadmap

🌐 Because why wouldn't you make your company's product roadmap Public on GitHub?
46
star
93

redis-connection

⚑ Single Redis Connection that can be used anywhere in your node.js app and closed once (e.g in tests)
JavaScript
45
star
94

aws-lambda-test-utils

Mock event and context objects without fluff.
JavaScript
44
star
95

learn-graphQL

❓Learn to use GraphQL - A query language that allows client applications to specify their data fetching requirements
JavaScript
44
star
96

elixir-pre-commit

βœ… Pre-commit hooks for Elixir projects
Elixir
43
star
97

hapi-login

πŸšͺ The Simplest Possible (Email + Password) Login for Hapi.js Apps βœ…
JavaScript
43
star
98

learn-riot

🐎 Riot.js lets you build apps that are simpler and load/run faster than any other JS framework/library.
HTML
43
star
99

github-reference

⭐ GitHub reference for *non-technical* people following a project's progress
42
star
100

learn-codeclimate

🌈 Learn how to use CodeClimate to track the quality of your JavaScript/Node.js code.
41
star