<?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 Oliver DS on Medium]]></title>
        <description><![CDATA[Stories by Oliver DS on Medium]]></description>
        <link>https://medium.com/@oliver.seq?source=rss-2fbe925d92ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HhBa4nWNk4lWzhN4CJP9vg.jpeg</url>
            <title>Stories by Oliver DS on Medium</title>
            <link>https://medium.com/@oliver.seq?source=rss-2fbe925d92ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:14:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oliver.seq/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[Securing your AWS instances with a bastion host.]]></title>
            <link>https://medium.com/@oliver.seq/securing-your-aws-instances-with-a-bastion-host-1c52d6dbc1bd?source=rss-2fbe925d92ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c52d6dbc1bd</guid>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bastion-host]]></category>
            <dc:creator><![CDATA[Oliver DS]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 11:59:51 GMT</pubDate>
            <atom:updated>2020-06-23T11:59:51.092Z</atom:updated>
            <content:encoded><![CDATA[<p>Security is extremely important, especially when handling user data. Usually you’ll want to secure your data and applications by hosting these on instances within a private subnet of a VPC (Virtual Private Cloud). This prevents external access to your instances, but it can also make it difficult for approved staff to access them securley too. One tool that can help add a layer of security to your AWS instances is the bastion host.</p><p>Bastion hosts sit within the public subnet of your VPC and act as a link between the outside world and your private subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*XPvXlIMmVZQg9RNVHuPzIw.png" /><figcaption>image courtesy of aws.amazon.com</figcaption></figure><h3>Goals</h3><p>There are several key aims we want to achieve from this.</p><ol><li>Connection to bastion should be restricted to select sources via SSH.</li><li>Bastion can only access specific instances within the same VPC.</li><li>Each instance only accepts inbound traffic from bastion outside of its private subnet.</li></ol><h4>Step One — Creating a new Security Group for Bastion</h4><p>Firstly, create a new security group that will allow you to specify the inbound/outbound rules for your bastion host. You’ll want to add any trusted sources to your inbound rules, for example the IP address of the Admins permitted access to AWS:</p><figure><img alt="An image showing the menu for creating a security group in AWS" src="https://cdn-images-1.medium.com/max/1024/1*qUO_HY1IzxGA4Mm8P6trtg.png" /></figure><p>For the ‘Outbound rules’ make sure to remove the option to allow all traffic and instead restrict this to the instances you wish to connect to. For your source, make sure you select the specific security group belonging to that instance.</p><h4>Step Two — Updating the security policies of your other instances</h4><p>One example setup you might have is an API hosted on an EC2 instance that is connected to your RDS. Your RDS instance would only allow inbound traffic from your EC2 instance, but your EC2 instance may allow traffic from outside the private subnet.</p><p>Instead, restrict connections to the EC2 instance to within the VPC by allowing only bastion to connect to it via SSH. This adds an effective layer of security by disabling access from outside the VPC.</p><figure><img alt="Inbound rules amended to accept only inbound traffic from Bastion on port 22" src="https://cdn-images-1.medium.com/max/1024/1*bf-5erfu0KER7hX59vrE_g.png" /></figure><p>For the source, make sure to select the bastion security group.</p><h4>Step Three — Creating the bastion host</h4><p>Next you’ll want to create an EC2 instance that you’ll use to connect to your other private instances. In this example I’ve opted for a micro service (free tier). To get started follow the below routes in the AWS console:</p><p><em>Services → Compute → EC2 → Launch Instance → Amazon Linux → Select</em></p><p>From here, you’ll want to choose the <strong><em>General Purpose t2.micro</em></strong> which is again, free tier. Select ‘Review and Launch’ and select ‘Edit Security Groups’. Here you’ll want to select an existing group and select the group you previously made (ours was Bastion):</p><figure><img alt="an example image of the ‘review and launch’ stage of the EC2 instance setup. Our bastion security group is added." src="https://cdn-images-1.medium.com/max/1024/1*Zx9yfHAhHLADoaXe_pc8Ng.png" /></figure><p>When you’re ready to launch, hit “Launch”. It will ask you to use a secret key, so choose to create one. Save the [name_of_file].pem file and copy the Public DNS address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXWYaealuz8P6m2pqfNXRQ.png" /></figure><p>Then go to your bash terminal and run the following:</p><pre>ssh <strong>public-dns-address</strong> -i <strong>~/.ssh/bastion.pem</strong> -l ec2-user</pre><p>Replacing the <strong>public-dns-address</strong> with the one copied from your EC2 instance, and the <strong>~/.ssh/bastion.pem</strong> file location on your local drive. If successful, you should now be inside the EC2 instance.</p><h4>Step Four — Accessing other instances</h4><p>The final step is to establish a secure connection to your other instances. There are several methods to do this, you could set up SSH Agent Forwarding (which you can read more about <a href="https://aws.amazon.com/blogs/security/securely-connect-to-linux-instances-running-in-a-private-amazon-vpc/">here</a>) but we chose another method which was to add the Bastion public key as a trusted source to each of our private instances. To do this, you’ll need to:</p><ul><li>copy the bastion public key.</li><li>ssh into your private EC2 instance.</li><li>Locate the ssh directory and open the authorized_keys file (I used vim):</li></ul><pre>cd .ssh<br>cat authorized_keys<br>vim authorized_keys</pre><ul><li>paste the bastion public key, save the changes and exit vim.</li><li>check that the list of authorized_keys includes the changes.</li></ul><pre>cat authorized_keys</pre><p>If you exit and ssh into bastion, you should be able to SSH into your private EC2 instances from there.</p><h3>Troubleshooting Errors</h3><p>Whilst setting up the bastion host you may run into a series of errors. Hopefully the following can help you resolve these.</p><h4>Permission denied (publickey,gssapi-keyex,gssapi-with-mic)</h4><p>You may get this error if your ssh keys directory isn’t secured. To resolve this you’ll need to run the following command (replacing <strong>name-of-file</strong>):</p><pre>sudo chmod 600 ~/.ssh/<strong>name-of-file</strong></pre><p>If you try again, you should find that you can now successfully connect.</p><h3>Host key verification failed.</h3><p>This can be a pretty scary warning message to come across, as the example below shows:</p><pre>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@</pre><pre>@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @</pre><pre>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@</pre><pre>IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!</pre><pre>Someone could be eavesdropping on you right now (man-in-the-middle attack)!</pre><p>This can happen if your not using an Elastic IP (the ip address can change on a restart etc) or if you’re using Elastic Beanstalk. This is because the EC2 instance you’re trying to connect to has moved so you need to refresh your connection with AWS. To do so you need to run the following command to firstly remove the old connection (replacing the public DNS in bold):</p><pre>ssh-keygen -f “/root/.ssh/known_hosts” -R “<strong>your-</strong><a href="http://ec2-34-247-162-111.eu-west-1.compute.amazonaws.com/"><strong>ec2-endpoint.region</strong>.<strong>compute.amazonaws.com</strong></a>”</pre><p>Then when you run your ssh command to connect to the EC2 instance it should re-establish a fresh connection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c52d6dbc1bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Carousel in React]]></title>
            <link>https://medium.com/octopus-wealth/creating-a-carousel-in-react-e45918738212?source=rss-2fbe925d92ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45918738212</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[carousel]]></category>
            <dc:creator><![CDATA[Oliver DS]]></dc:creator>
            <pubDate>Fri, 21 Jun 2019 09:42:37 GMT</pubDate>
            <atom:updated>2019-07-03T16:10:03.712Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilising React, Hooks, TypeScript and Styled Components.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1EU92t1NUdsFh3WxkRw5g.jpeg" /></figure><p>I recently had the task of implementing a Carousel for a project at work. Initially, the plan was to use a pre-existing library to quickly scaffold the carousel and add our images and copy and then move on to the next task.</p><p>It quickly became apparent however, that not only would we require the ‘bloat’ from the package installation itself, but we’d need roughly 300 lines of CSS too, given that we didn’t want to directly import any themes due to our Content Security Policy (see more <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">here</a>).</p><p>Additionally, it also started proving quite difficult to implement some custom designs we had mocked up for the left/right scrolling arrows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*t84SZVbeF6kJrSGn6qJy0Q.gif" /><figcaption>The struggle was real</figcaption></figure><p>As such, after consulting with the team, the decision was made to go ahead and try and create a custom carousel. Here’s how I did it, with far less code and more control over the component.</p><h3>The Basics</h3><p>First we need the content for our slides. First, I created a Carousel component which will contain several children. These will be our individual slide components that will be passed as JSX elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36272a38dfca2d0131ac9fdbcce54ab4/href">https://medium.com/media/36272a38dfca2d0131ac9fdbcce54ab4/href</a></iframe><p>Each individual component looks like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32ff160c8f8c6a3d533dc6e13637ba9/href">https://medium.com/media/e32ff160c8f8c6a3d533dc6e13637ba9/href</a></iframe><p>Now to import the Carousel.tsx to App.tsx and pass through those child components. <strong>NB:</strong> <em>The reason we decided to design the Carousel this way was so that if we ever needed to use it elsewhere (which eventually we did) we could just call our </em><em>Carousel component again and pass in different slides as children.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc95b111e82fccd8dafeab72ea52643d/href">https://medium.com/media/bc95b111e82fccd8dafeab72ea52643d/href</a></iframe><p>The result will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z37qXti9vgW9NXtWJvrdCA.png" /></figure><p>Not <em>really</em> what we want, but this is good progress. We wanted our carousel to have various features, but for the sake of this post, I’ll cover some basics which we’ll quickly scaffold:</p><ol><li>We only want to display the active slide at any one time. We can achieve this by tweaking opacity settings on the slides depending on whether they are active or not.</li><li>We’ll need two buttons to navigate left and right between the slides. It should also feature continuous scrolling. We can achieve this using a modulus.</li></ol><h3>Opacity:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/801b9b44172be0ab2e15ec732f398926/href">https://medium.com/media/801b9b44172be0ab2e15ec732f398926/href</a></iframe><h3>Scrolling Logic:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e8e3e897b602be1ea966acddbfc64bd/href">https://medium.com/media/4e8e3e897b602be1ea966acddbfc64bd/href</a></iframe><h3><strong>The final code for the Carousel:</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a080c6221f275bb2dd3447d645a93647/href">https://medium.com/media/a080c6221f275bb2dd3447d645a93647/href</a></iframe><p>You should now have the scaffolding for a Carousel without needing to add further dependencies and the added flexibility of using your own styling methods. You may choose to replace the buttons with custom icons you might have or alternatively employ setInterval() to automate the scroll every x seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*s7piGEO9MyiAPwyZdDqt8g.gif" /></figure><blockquote>Special thanks to <a href="https://medium.com/@anthonyatp?source=post_page">Anthony Panagi</a>, <a href="https://medium.com/@fredrivett?source=post_page">Fred Rivett</a> and <a href="https://medium.com/@pgjones">Phil Jones</a> for their contributions to the original code and subsequent blog.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45918738212" width="1" height="1" alt=""><hr><p><a href="https://medium.com/octopus-wealth/creating-a-carousel-in-react-e45918738212">Creating a Carousel in React</a> was originally published in <a href="https://medium.com/octopus-wealth">NOVA Wealth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Rails With Auth0]]></title>
            <link>https://medium.com/@oliver.seq/authentication-in-rails-with-auth0-4cc8ead3bd78?source=rss-2fbe925d92ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cc8ead3bd78</guid>
            <category><![CDATA[api-authentication]]></category>
            <category><![CDATA[api-endpoint]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Oliver DS]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 21:27:58 GMT</pubDate>
            <atom:updated>2019-02-22T21:27:58.453Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post (<a href="https://medium.com/@oliver.seq/creating-a-rest-api-with-rails-2a07f548e5dc">link here</a>) I went through the process of setting up a really simple RESTful API using Rails. I skipped over some important features such as authentication and password hashing in favour of keeping the tutorial short and sweet (and for those preferring to use their own methods).</p><p>In this post I’ll be going over authentication using Auth0. <em>Note that this tutorial requires you to have an Auth0 account (</em><a href="https://auth0.com/"><em>Auth0 website</em></a><em>).</em></p><h3>Initial Setup</h3><p>Firstly let’s set up our Rails API application:</p><p>rails new rest-api-with-auth0-guide --api database=postgresql</p><p>Next, we’ll need to set up our Auth0 API configurations which can be found <a href="https://manage.auth0.com/#/apis">here</a> ensuring you are in the APIs section. Click on the <strong>+ CREATE API</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUgIF0kUA_7nYzlRkT3Vzw.png" /><figcaption>Auth0 Dashboard</figcaption></figure><p>This will require you to enter some details. <strong><em>Note </em></strong>— here I assign the URL <a href="http://localhost:3000/">http://localhost:3000/</a><strong> </strong>but you can use whatever URL necessary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueM65cPVO8xL13_t9AE3bg.png" /><figcaption>Creating the API</figcaption></figure><p>Once created, Auth0 will provide us with some code for <strong>C# / Node.js / PHP</strong> to get up and running immediately, but as we’re using Rails you can ignore it and we’ll configure our own setup.</p><p>The final part of our initial setup is going to be installing the JWT gem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*x2zIyt73Jip389-8TZJ0_A.png" /><figcaption>Adding the JWT Gem.</figcaption></figure><h3>Creating Authentication Files</h3><p>Since Rails 5.2 there have been some important changes to note. Firstly, you will not be able to directly use the /lib directory for non-domain specific classes. One simple method around this is to move the /lib directory inside the /app directory. From inside the /app/lib/ directory, create a new file called <strong>json_web_token.rb</strong> and insert the following code (taken directly from Auth0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WlkjboFjkbXuSYvzqqHSQ.png" /></figure><p>The second change is that Rails 5.2 comes with a way to edit the config/credentials.yml.enc file so you won’t have to decrypt and encrypt your file each time on your own. For this to work, in your command line run the following: EDITOR=”code — wait” bin/rails credentials:edit replacing code with the relevant key for your editor (Atom = atom, Sublime Text= subl, VS Code Insiders = code-insiders).</p><p>A new file will open, add the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWuzf8VvXWQmk0QLm5AY2Q.png" /><figcaption>12345.credentials.yml</figcaption></figure><p>Save and close the file and your command line should complete with the message “New credentials encrypted and saved.”</p><p>The final part is to edit the <strong>json_web_token.rb</strong> file, changing the highlighted code on the left, to that on the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*02OSDHRFoiV0Wi_4E6Suyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*033e6BNShfzratYX9a2RkA.png" /><figcaption>Change from Left (old) to Right (new)</figcaption></figure><h3>Controllers</h3><p>Next we will create a custom Concern called Secured which checks for the AccessToken in the Authorization request header. If the token is present, it should be passed to JsonWebToken.verify.</p><p>Create the following file in the following directory:</p><p>/app/controllers/concerns/<strong>secure.rb</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lzs4WQj-fLUg4Yeq3KoHjA.png" /><figcaption>secured.rb</figcaption></figure><p>Let’s add a couple of test controllers and then test to see how our API endpoints are working. I created a public and private controller for Hello:</p><ol><li>rails generate controller Public hello</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urogdgUBbvrcuX6mdSkB3Q.png" /><figcaption>Public controller</figcaption></figure><p>2. rails generate controller Private hello</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxVu-DfFobnSmfiT-PpoAw.png" /><figcaption>Private controller</figcaption></figure><p>Then rails db:create and rails db:migrate to initialise our database, followed by rails s to start our local server <a href="http://localhost:3000/">http://localhost:3000/.</a> If we check the routes, we should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA61SD9lmURq56lPOisBpQ.png" /><figcaption>Public path</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*WRio7kKEroSVKPslPP1a0g.png" /><figcaption>Private path</figcaption></figure><p>Excellent! So as we can see, we can gain access to the public path but not the private path. This is super valuable for securing our API endpoints.</p><h3>Accessing the Private path</h3><p>The final chapter in this tutorial is exploring how to issue tokens that allow access to private endpoints. This requires sending a request via your frontend application to receive an ‘Access Token’.</p><p>You can find more information on how to go about sending the request here:</p><p><a href="https://auth0.com/docs/quickstart/backend/rails/02-using">Auth0 Ruby On Rails API SDK Quickstarts: Using your API</a></p><p>If you are using a popular JavaScript framework, I suggest looking at these documents too, as provided by Auth0:</p><p><a href="https://auth0.com/docs/quickstart/spa">Auth0 Single-Page App Quickstarts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cc8ead3bd78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a REST API with Rails]]></title>
            <link>https://medium.com/@oliver.seq/creating-a-rest-api-with-rails-2a07f548e5dc?source=rss-2fbe925d92ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a07f548e5dc</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Oliver DS]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 13:32:20 GMT</pubDate>
            <atom:updated>2019-02-08T13:32:20.767Z</atom:updated>
            <content:encoded><![CDATA[<p>Having spent a lot of time working with JavaScript and React recently, I thought I’d revisit Rails for some practice, and wanted to write a post about creating a RESTful API using Ruby on Rails.</p><p>Rails now has the option to create an API application which is a slimmed down version of a traditional Rails web app. According to Rails 5 release notes, generating an API only application will:</p><ol><li>Make the <strong>ApplicationController </strong>inherit from <strong>ActionController::API </strong>instead of <strong>ActionController::Base</strong>.</li><li>Skip generation of view files and slim-down the middleware.</li></ol><p>For this tutorial, I’ll be creating an API containing a list of user submitted facts. We’ll be using PostgreSQL for our database which will allow easier integration with Heroku, should be decide to host it.</p><p><em>This post requires that you have an understanding of Ruby / Rails and are comfortable using the command line terminal. I won’t be covering the subject of password hashing or testing here for simplicity sake, but will cover these topics in more detail in a separate post.</em></p><p>To get started and instruct Rails to build our API, we issue the following:</p><p>$ rails new rest-api-guide --api --database=postgresql</p><p>We specify it is an API using --api and the database using --database=.</p><p><em>NB — if you would like to use a test-suite such as Rspec, you would need to append </em><em>-T to the end of the command during setup and then install Rspec and any other necessary gems separately.</em></p><h3>Models and Controllers</h3><p>The next stage in our setup is preparing our models and controllers. As mentioned previously, we’ll be keeping things simple in this tutorial, with just 2 models, User and Fact.</p><h4>Models</h4><p>To create the models, issue the following commands in your terminal:</p><p>$ rails generate model User username:string password:string</p><p>$ rails generate model Fact user:references fact:string likes:integer</p><p>Note that user:references creates a relationship with the User model, telling us that we’ll need a foreign key called user_id. This is because we want our Fact to belong_to a User.</p><p>If we check our models, we should see the Fact model now has the association belongs_to :user set up already. We can now add a has_many :facts relationship to User and our models will be ready to migrate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3bKkQCDtubLTUbgBnxvvg.png" /><figcaption>model relationships.</figcaption></figure><p>If you’re using PostgreSQL for your database as I chose to, migration will be a 2 step process. Step one requires that we set up the database, before running the migration:</p><ol><li>$ rails db:setup</li><li>$ rails db:migrate</li></ol><p>Once complete, you’ll be able to check the schema.rb file in your db folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*tSNxu_f9kequTz4-3SgdZA.png" /><figcaption>The schema.</figcaption></figure><p>Now we can move on to our controllers, where we will make use of RESTful architecture.</p><h4>Controllers</h4><p>We can set up our controllers much like we did with our models, except this time we are going to create them in a sub-folder ‘v1’. This is good practice for when creating future API’s where you may decide to work on an updated version (v2) whilst keeping v1 live and stable:</p><ol><li>$ rails g controller api/v1/Users</li><li>$ rails g controller api/v1/Facts</li></ol><p><em>Note how for models we use the singular (User) and for controllers we use plural (Users). This is an important syntactical requirement of Rails and must be adhered to for Active Record to function properly.</em></p><p>Once we have our controllers loaded, we’ll need to establish our routes, which can be found in config/routes.rb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*AEQAOnWGk7gZidLRdJuOyA.png" /><figcaption>Routes</figcaption></figure><p>Once set, you can check your routes using $ rails routes.</p><p>With this done, it’s time to define our controller methods using the RESTful architecture. I began with the Users controller:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JosU5IyR7_2EMtI2CFELCg.png" /><figcaption>User controller</figcaption></figure><p>Note here that we have a <strong>private</strong> area, with the method <strong>user_params</strong> defined beneath it. This is a private class and is used for security purposes. By passing in <strong>user_params</strong> in our create and update methods, we utilise ‘strong parameters’ which is described as:</p><blockquote>It provides an interface for protecting attributes from end-user assignment. This makes Action Controller parameters forbidden to be used in Active Model mass assignment until they have been explicitly enumerated.</blockquote><p>It is highly recommended you use strong params in your Rails applications for security purposes. You may also note that our code wasn’t very DRY, we used .find(params[:id]) three separate times. Better practice would be to create a separate method for this and tell Rails to run this method for specific methods each time they are run.</p><p>See the Facts controller below for a comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*9gi72FBOkenM6LjebYxpEw.png" /><figcaption>Fact controller</figcaption></figure><p>With the controllers done and our routes set up, we can run our rails server and check to see if our routes are working. Start the server using$ rails s and then head to http://localhost:3000/api/v1/users in your web browser. You should see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*shZOd0r-g8kfP-9k5zMlzw.png" /><figcaption>Empty JSON file.</figcaption></figure><h3>Adding Data</h3><p>Great. Currently our database is empty so we won’t actually return anything, so let’s create a User and some Facts linked to that User.</p><p>We can either create some seed data or just use the Rails console to create our instances. I’ll be using the rails console, $ rails c.</p><p>$ oliver = User.create( username: &#39;Oliver&#39;, password: &#39;password&#39; )</p><p>$fact_one = Fact.create( fact: &#39;Wiley Hardeman Post was the first pilot to fly solo around the world.&#39;, likes: 1, user_id: 1 )</p><p>$ fact_two = Fact.create( fact: &#39;The Symphony No1 in E flat major, K.16, was written by Wolfgang Amadeus Mozart at the age of 8.’ likes: 2, user_id: 1 )</p><p>Now if we check our paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*fhoN88GqqbWxsiO6ba-yGA.png" /><figcaption>Users</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hS5HI45ycEjNjkN9Oik0jw.png" /><figcaption>Facts</figcaption></figure><p>Of course, in a practical application, we will be making queries and fetch requests to our database using a variety of methods, for example using JavaScript to click on a button and sign up to a website, where the users information would be sent to our database and saved.</p><p>Hopefully for now, this has helped to form a basic understanding of how to setup a RESTful API using Rails.</p><h3>Final Note</h3><p>If you wanted your facts to be accessible all in one place, separate from the users that created them, in the routes file, instead of having Facts nested within Users, you could have it as a separate entity like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ftOgnH_2i9JG6rPsWulkPg.png" /></figure><p>Then instead of this path: <a href="http://localhost:3000/api/v1/users/1/facts">http://localhost:3000/api/v1/users/1/facts</a> you could have <a href="http://localhost:3000/api/v1/facts">http://localhost:3000/api/v1/facts</a> which would no longer be user specific:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVLro78b58sI2PY46nOMIg.png" /><figcaption>All the Facts!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a07f548e5dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code-Splitting in React.]]></title>
            <link>https://medium.com/@oliver.seq/code-splitting-in-react-64549ab8d820?source=rss-2fbe925d92ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/64549ab8d820</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Oliver DS]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 10:12:23 GMT</pubDate>
            <atom:updated>2018-12-11T10:12:23.913Z</atom:updated>
            <content:encoded><![CDATA[<p>Code-splitting can dramatically improve the performance of your application by using a technique described as a “lazy-load” which loads only the code that is currently needed by the user.</p><p>Whilst code-splitting won’t reduce the actual amount of code in your app, it will avoid loading code that the majority of users may not need, reducing the amount of code needed during the initial load.</p><p>If you use the create-react-app method (<em>recommended for this walkthrough</em>) then your React app will automatically have its files “bundled” using the <a href="https://webpack.js.org/">Webpack</a> tool. Bundling is the process of following imported files and merging them into a single file, aka a “bundle”. Bundling is great, but as your app grows, your bundle will grow too so you’ll need to ensure your app doesn’t grow so large that it takes a long time to load, otherwise you’ll damage the user experience.</p><h3>import()</h3><p>The best way to introduce code-splitting into your app is through the dynamic import()syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*HlaS4qSNmkmpKsCeGh7bXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*7gszuLU1jGM0BhHHZELMJw.png" /><figcaption>Before Code-Splitting (LEFT) and After Code-Splitting (RIGHT)</figcaption></figure><p>When Webpack comes across this import() syntax, it automatically starts code-splitting your app, in which you can import the direct path and then call the method needed (such as ‘add’) using the .then method.</p><h3>React.lazy</h3><p>The React.lazy function lets you render a dynamic import as a regular component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*Z7Gp_BqNpcoPH2rJ5PtmQw.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtGPh4FqE6iDe40ayaCRDA.png" /><figcaption>After</figcaption></figure><p>This will automatically load the bundle containing the OtherComponent when this component gets rendered.</p><p>React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.</p><h3>Route-based code splitting</h3><p>Deciding where in your app to introduce code splitting can be a bit tricky. You want to make sure you choose places that will split bundles evenly, but won’t disrupt the user experience.</p><p>A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.</p><p>Here’s an example of how to setup route-based code splitting into your app using libraries like <a href="https://reacttraining.com/react-router/">React Router</a> with React.lazy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLo7LWrR_o-Ud1oJqBTdeQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64549ab8d820" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>