<?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 Jackson Chen on Medium]]></title>
        <description><![CDATA[Stories by Jackson Chen on Medium]]></description>
        <link>https://medium.com/@jacksonchen171?source=rss-a57861a30cf9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cjCV39950kwK_nT_s_HDuQ.png</url>
            <title>Stories by Jackson Chen on Medium</title>
            <link>https://medium.com/@jacksonchen171?source=rss-a57861a30cf9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 02 May 2026 18:44:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacksonchen171/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[How to Create a Rails Backend API]]></title>
            <link>https://medium.com/geekculture/how-to-create-a-rails-backend-api-871fcddd6e20?source=rss-a57861a30cf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/871fcddd6e20</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Jackson Chen]]></dc:creator>
            <pubDate>Fri, 29 Jan 2021 06:02:09 GMT</pubDate>
            <atom:updated>2021-01-29T06:02:09.709Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide for building a Rails REST API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gxa7MKTlDTakfPAf" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Are you starting a new project and need a dedicated backend API to persist data? Look no further; this guide should lead you in the right direction.</p><h3>0. Planning out Domain Model and Associations</h3><p>When starting a new project, it is always important to plan out your domain model and <a href="https://guides.rubyonrails.org/association_basics.html">associations</a> first. Refer to the following chart for drawing out your model associations.</p><figure><img alt="Crow’s Foot Reference Guide" src="https://cdn-images-1.medium.com/max/482/1*MqQZi5-uRZ3648Jb2hcqdQ.png" /><figcaption>Crow’s Foot notation reference</figcaption></figure><p>In this guide, we will be building a simple API for a library application using the following domain model:</p><figure><img alt="Domain model for our library-api" src="https://cdn-images-1.medium.com/max/784/1*jzAwtUu0eiGqpP8m_t4mbA.png" /><figcaption>Domain model for our library-API</figcaption></figure><p>The association between the two models is drawn out above using the “Crow’s Foot” notation.</p><p>An author has_many books. A book belongs_to an author.</p><h3>1. Initializing Rails API</h3><p>In your terminal, use the following command below to initialize a new <a href="https://guides.rubyonrails.org/api_app.html">Rails API</a>.</p><p><strong>Template:</strong></p><pre>$ rails new <strong>&lt;API NAME&gt;</strong> --api --database=postgresql</pre><p><strong>Example:</strong></p><pre>$ rails new <strong>library-api</strong> --api --database=postgresql</pre><p>The --api flag tells Rails to initialize a new application without the bloat and middleware that is not necessary in an API application.</p><p>The --database= flag specifies to Rails what database we will be using. In this case, we will be using PostgreSQL as it is <a href="https://www.heroku.com/postgres">Heroku</a>’s standard database if you plan on deploying your API onto Heroku.</p><p><em>Without specifying a database type, Rails will use SQLite by default.</em></p><p>Remember to change the directory into the root folder of your newly initialized API and run $ bundle to install your dependencies.</p><h3>2. Models</h3><p>Once Rails finishes initializing our API, use the following command to generate our <a href="https://guides.rubyonrails.org/active_model_basics.html">models</a> for our API and tables for our database.</p><p><strong>Template:</strong></p><pre>$ rails generate model <strong>&lt;MODEL NAME&gt;</strong> <strong>&lt;COLUMNS&gt;</strong></pre><h4>Generating the Author Model</h4><p>In our example, we created a model and migration for our <strong>Author </strong>table consisting of two columns (<strong>name</strong> and <strong>bio</strong>) with type string.</p><p><strong>Example:</strong></p><pre>$ rails generate model <strong>Author</strong> <strong>name:string bio:string</strong></pre><p>We can shorten the generate command by using the following rules:</p><ul><li><em>If the column type is a string, we can omit </em><em>:string as Rails will set each column type to string by default if not specified.</em></li><li><em>Shorten </em><em>rails generate model to </em><em>rails g model.</em></li></ul><p><strong>Example (shortened):</strong></p><pre>$ rails g model <strong>Author</strong> <strong>name bio</strong></pre><h4>Generating the Book Model</h4><p>Based on our domain model, an Author has many Books and a Book belongs to an Author. In order for our database to acknowledge the association between Book and Author, we can add a new column using the name of the model we’re trying to link to and set the column type to :belongs_to.</p><p><strong>Example:</strong></p><pre>$ rails g model Book title pages:integer <strong>author:belongs_to</strong></pre><p>Setting the column type as :belongs_to will tell Rails to automatically:</p><ul><li>Create an author_id column in the Book table that will store the Author’s ID as a foreign key.</li><li>Add the belongs_to association to the Book model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*ypKsdjJWfNw9wg5ZtXlfpQ.png" /><figcaption>app/model/book.rb</figcaption></figure><h4>Add Associations to Models</h4><p>Although Rails may have already set up the association between Book to Author during the Book model generation, we still need to manually set up the association from our Author to Book model.</p><p>In our app/models/author.rb file, add the association has_many :books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Z6iDu7xZ0IF_62JWT4Uupw.png" /><figcaption>app/models/author.rb</figcaption></figure><p><em>Note: When adding a </em><em>has_many association, remember to pluralize the model.</em></p><h4>Add Validations to Models</h4><p>To prevent invalid data from being saved to our database, we can set up <a href="https://guides.rubyonrails.org/active_record_validations.html">validators</a> for our models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*sadwoHqj_2Iq9Xi3TPlVsg.png" /><figcaption>app/models/author.rb</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk0cvKKg79BkEEUY6l0C9Q.png" /><figcaption>app/models/book.rb</figcaption></figure><h3>3. Starting the Database</h3><p>In order to start the database, we will need to create the database and migrate our changes to update the schema.</p><pre>$ rails db:create<br>$ rails db:migrate</pre><p>Confirm your migrations have taken place by checking the schema in db/schema.rb. If you find that you are missing a column in one of your tables, do not manually change the schema.rb as it can break your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeBad30IyDcD2lAk3x9Nhg.png" /><figcaption>db/schema.rb</figcaption></figure><h4>Generating a Migration</h4><p>Missing a column in one of the tables? We can generate a migration to add a column to our table.</p><p><em>Note: Remember to pluralize the table name to match database conventions.</em></p><p><strong>Template:</strong></p><pre>$ rails g migration add_<strong>&lt;COLUMN&gt;</strong>_to_<strong>&lt;TABLE NAME&gt;</strong> <strong>&lt;COLUMN&gt;:&lt;TYPE&gt;</strong></pre><p><strong>Example:</strong></p><pre>$ rails g migration add_<strong>genre</strong>_to_<strong>books</strong> <strong>genre:string</strong></pre><p>After generating your migration, simply run $ rails db:migrate to migrate any changes.</p><h3>4. Controllers</h3><p>Now that we have set up our database, we will need a way for the API to access the data. To do this, we will need to set up controllers.</p><h4>Generating Controllers</h4><p>Housing all the methods and actions, our controllers will act as the “control” for our collections as the name implies.</p><p><em>Note: The controller name should be plural as it contains all the methods for the collection.</em></p><p><strong>Template:</strong></p><pre>$ rails g controller <strong>&lt;CONTROLLER NAME&gt;</strong></pre><p><strong>Example:</strong></p><pre>$ rails g controller <strong>Authors<br></strong>$ rails g controller <strong>Books</strong></pre><h4><strong>Adding Actions to Controllers</strong></h4><p>After generating our controllers, we need to populate the controllers with actions we would like our API to perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9TLEuTEF5Je57RGVwJ4Bg.png" /><figcaption>Routes and Controller Actions Reference</figcaption></figure><p>Following RESTful architecture and CRUD conventions, we can use the chart above as a reference for common actions we’d like in our API.</p><p><em>Note: This does not limit us from creating our own custom actions. We will just need to do a little bit more configuring in our routes if you decide to add a custom action.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxPEEpTulvIyTVsGku9G7Q.png" /></figure><h3>5. Routes</h3><p>When setting up <a href="https://guides.rubyonrails.org/routing.html">routes</a>, we are basically setting up the APIs endpoints or URLs that will dispatch a certain action to return a response.</p><h4>Resource Routing</h4><p>If we followed the naming conventions that Rails like when setting up our controller actions, we can take advantage of Rails <a href="https://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default">resource routing</a>. Navigate to config/routes.rb and add resources <strong>&lt;CONTROLLER NAME&gt;</strong> to your routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*NMpv5ZFV4mYpN7f1sHvGQQ.png" /><figcaption>config/routes.rb</figcaption></figure><h4>Custom Routing</h4><p>If you added a custom action to your controller and wanted to dispatch that action to a <a href="https://guides.rubyonrails.org/routing.html#non-resourceful-routes">custom route</a>, we can use the following template.</p><p><strong>Template:</strong></p><pre><strong>&lt;HTTP VERB&gt;</strong> &#39;<strong>&lt;PATH&gt;</strong>&#39;, to: &#39;<strong>&lt;CONTROLLER&gt;#&lt;ACTION&gt;&#39;</strong></pre><p><strong>Example:</strong></p><pre>get &#39;custom/path&#39;, to: &#39;authors#index&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*7w2D_JNoov_q_TFIooZ32A.png" /><figcaption>config/routes.rb</figcaption></figure><h3>6. Test the API</h3><p>Now that we have our routes set up, we want to make sure our routes are working properly. However, our database currently does not have any data to send back yet. We need to seed our database first.</p><h4>Seed Database</h4><p>Navigate to db/seeds.rb, add some seed data and run $ rails db:seed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*b52LAxz5HjNyp88-nh6J3g.png" /><figcaption>db/seeds.rb</figcaption></figure><h4>Starting the Server</h4><p>Once your database is seeded, start the server by running $ rails s in your terminal. By default, your Rails server should start on port 3000. If you want to use a different port, you can add the -p <strong>&lt;PORT NUMBER&gt; </strong>flag to specify which port you want your server to run on.</p><p><strong>Example:</strong></p><pre>$ rails s -p 3000</pre><h4>Test Endpoints</h4><p>Once the server is running, we can check the authors route by navigating to <a href="http://localhost:3000/authors">http://localhost:3000/authors</a> in our browser.</p><p><em>Note: Keep in mind, our browsers are only able to perform GET requests. If you want to test out other requests, I recommend using </em><a href="https://www.postman.com/"><em>Postman</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWQNOwM0hVoO3Dk9nY14AQ.png" /><figcaption>JSON response from /authors</figcaption></figure><p>This is great that we are getting a response, but where are the books we seeded? This brings us to our next topic, Serializers.</p><h3>7. Serializers</h3><p>Serializers allow us to format our data in a way that is easy for developers like us to use. Perhaps, there are some things we want to omit to send back such as passwords or pointless metadata.</p><h4>Installation</h4><p>We will be using the <a href="https://rubygems.org/gems/active_model_serializers/versions/0.10.10">ActiveModelSerializer</a> gem. Navigate to your Gemfile and add gem &#39;active_model_serializers&#39; as a dependency. Then run $ bundle to install all dependencies.</p><h4>Generate Serializer</h4><p>Once ActiveModelSerializer is installed, we are given access to a new generate command.</p><p><strong>Template:</strong></p><pre>rails g serializer <strong>&lt;MODEL NAME&gt;</strong></pre><p><strong>Example:</strong></p><pre>rails g serializer author<br>rails g serializer book</pre><h4>Serialize your Data</h4><p>Navigate to your serializers located in app/serializers directory and add or remove attributes that you’d want in your JSON response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*7GrHoyBDx_dRtsTskgyD3w.png" /><figcaption>app/serializer/author_serializer.rb</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*OhWNxiRzWatw0ByiI1UXnQ.png" /><figcaption>app/serializer/book_serializer.rb</figcaption></figure><p>Now that you have set up your serializers, start up your server again and check out your API’s JSON responses. That looks clean!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZExgHHaVdMGBxenr2iw_9A.png" /></figure><h3>Conclusion</h3><p>Hopefully, this guide gave you a clear understanding of how to start your own Rails API. Being able to build your own API definitely has it’s perks and opens up a lot of opportunities for awesome project ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=871fcddd6e20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-create-a-rails-backend-api-871fcddd6e20">How to Create a Rails Backend API</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Action Cable With React and Rails]]></title>
            <link>https://medium.com/swlh/how-to-use-action-cable-with-react-and-rails-3129a554c7d?source=rss-a57861a30cf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3129a554c7d</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jackson Chen]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 06:05:05 GMT</pubDate>
            <atom:updated>2020-09-30T17:27:42.994Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beginner’s tutorial on how to utilize WebSockets via Action Cable</h4><figure><img alt="Data" src="https://cdn-images-1.medium.com/max/1024/0*ZWv8NASE2_dbIDMC" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wondered how some websites are able to stream real-time sports data or how users are able to receive messages almost as instantly as soon as they were sent?</p><figure><img alt="WebSockets" src="https://cdn-images-1.medium.com/max/534/0*VjSpKarCsib9A7i5.jpg" /></figure><p>In this tutorial, we’ll go over how to utilize WebSockets via Action Cable in a React frontend and Rails backend simple chat web application for real-time communication between multiple clients.</p><h3>1. Initial Setup</h3><h4>Rails Backend</h4><p>After initializing your new rails application, enable the redis gem in your Gemfile and add the following route to your <em>routes.rb</em> file.</p><pre><em># rails-backend/config/routes.rb </em></pre><pre>mount ActionCable.server =&gt; &#39;/cable&#39;</pre><p>Remember to run $ bundle install after enabling redis.</p><h4>React Frontend</h4><p>Next we will need to install Action Cable on our React frontend.</p><pre>$ npm install @rails/actioncable</pre><p>Create a separate JavaScript file that will be responsible for handling and creating the initial WebSocket connection to your Rails backend.</p><pre>$ touch ./src/cable.js</pre><p>Import createConsumer from the Action Cable library. Assuming your Rails server is running on port 3000, fill in the following.</p><pre><em>// react-frontend/src/cable.js</em></pre><pre>import { createConsumer } from &#39;@rails/actioncable&#39;;</pre><pre>const URL = &#39;ws://localhost:3000/cable&#39;;<br>const consumer = createConsumer(URL);<br> <br>export default consumer;</pre><p>Notice for the URL, we’re not using <em>http</em> anymore; instead, we’re using <em>ws</em> which stands for WebSocket. This creates an open connection between the consumer and the server that will allow them to receive any message(s) broadcasted as long as they are subscribed or connected.</p><p>Import consumer<em> </em>to the React component where you want the connection to be present. In this example, we’ll be displaying our messages to a React component called ChatBox.</p><pre>// react-frontend/src/ChatBox.js</pre><pre>import React from &#39;react&#39;;<br>import consumer from &#39;./src/cable&#39;;</pre><pre>export default class ChatBox extends React.Component {</pre><pre>   . . .</pre><pre>};</pre><h3>2. Initialize Channels</h3><h4>Rails Backend</h4><p>In our Rails backend server, we will need to initialize channels for our consumers/subscribers to connect to. In your terminal, use the following command to generate a channel. In this example, we’ll be creating a channel called <em>chat</em>.</p><pre>$ rails generate channel chat</pre><p>This will generate the following in your Rails directory.</p><pre><em># rails-backend/app/channels/application_cable/chat_channel.rb</em></pre><pre>class ChatChannel &lt; ApplicationCable::Channel</pre><pre>  def subscribed<br>  end</pre><pre>  def unsubscribed<br>  end</pre><pre>end</pre><h3>3. Create Subscriptions</h3><h4>React Frontend</h4><p>Now that the channels have been created, our clients or subscribers will need a way to connect to that channel. In the previous React Component where <em>consumer</em> was imported, add the following for creating subscriptions.</p><pre><em>// react-frontend/src/ChatBox.js</em></pre><pre>export default class ChatBox extends React.Component {</pre><pre>  componentDidMount() {<br>    consumer.subscriptions.create({<br>      channel: &#39;ChatChannel&#39;,<br>      username: &#39;cool_kid_20&#39;,<br>    })<br>  };</pre><pre>  componentWillUnmount() {<br>    consumer.disconnect()<br>  };</pre><pre>  . . .</pre><pre>};</pre><p>This will create a subscription or connection to our ChatChannel as soon as the ChatBox component renders. In this case, a username param will also be sent as well.</p><p>Upon unmounting of the component, the WebSocket connection will close. This is important to prevent memory leaks or hidden open connections within your web application.</p><h3>4. Handling Subscriptions</h3><h4>Rails Backend</h4><p>Once subscribed to a channel, we will have our subscribers actively listen for broadcasts sent to streams. In our example, the subscriber will begin listening for broadcasts sent to the &#39;public_chat’ upon subscribing and broadcast the string &#39;cool_kid_20 joined!&#39; to every subscriber currently listening to the ‘public_chat` stream.</p><pre><em># rails-backend/app/application_cable/channels/chat_channel.rb</em></pre><pre>def subscribed<br>  user = params[&#39;username&#39;]<br>  stream_for &#39;public_chat&#39;<br>  ActionCable.server.broadcast &#39;public_chat&#39;, &quot;#{user} joined!&quot;<br>end</pre><h3>5. Handling Broadcasts</h3><h4>React Frontend</h4><p>When any message is broadcasted at anytime and as long as we are subscribed and listening to the same stream, our subscriber will be able to receive that data. In this example, we will just console.log() the data that was broadcasted.</p><pre><em>// react-frontend/src/ChatBox.js</em></pre><pre>ComponentDidMount() {</pre><pre>  consumer.subscriptions.create({<br>    channel: &#39;ChatChannel&#39;,<br>    username: &#39;cool_kid_20&#39;,<br>  }, {<br>    connected: () =&gt; console.log(&#39;connected&#39;),<br>    disconnected: () =&gt; console.log(&#39;disconnected&#39;),<br>    received: data =&gt; console.log(data),<br>  })</pre><pre>};</pre><h3>6. Broadcasting Messages</h3><h4>React Frontend</h4><p>Assuming we have a form that will send a POST request to our backend upon submit, we can send a message to be broadcasted to the ChatChannel public_chat stream.</p><pre><em>// react-frontend/src/ChatBox.js</em></pre><pre>state = {<br>  content: &#39;Hi!&#39;,<br>  username: &#39;cool_kid_20&#39;<br>}</pre><pre>handleSubmit = () =&gt; {<br>  fetch(&#39;http://localhost:3000/messages&#39;, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify(this.state)<br>  })<br>}</pre><h4>Rails Backend</h4><p>In the controller that will be handling the POST request, we will have the message broadcasted to &#39;public_chat&#39; as long as the created message passes validation.</p><pre><em># rails-backend/app/controllers/messages_controller.rb</em></pre><pre>def create</pre><pre>  user = User.find_by(params[&#39;username&#39;])<br>  message = Message.create(<br>    content: params[&#39;content&#39;],<br>    user_id: user.id<br>  )<br>  if message.valid?   <br>    ActionCable.server.broadcast &#39;public_chat&#39;, message.content<br>  end</pre><pre>  render json: message</pre><pre>end</pre><p>In order to fully test this out, open up a second browser in incognito mode and start sending messages!</p><p>There are a multitude of uses that WebSockets offer besides messaging. Whether it’s streaming live sports data, multiplayer game data or real-time collaboration, the uses are endless. Hopefully this tutorial was a good starting point for learning how to integrate WebSockets into your React/Rails web application. I know you’ll make something awesome.</p><h3>Resources</h3><ul><li><a href="https://guides.rubyonrails.org/action_cable_overview.html">Action Cable Documentation</a></li><li><a href="https://www.npmjs.com/package/@rails/actioncable">Action Cable NPM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3129a554c7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-use-action-cable-with-react-and-rails-3129a554c7d">How to Use Action Cable With React and Rails</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy Your JavaScript Application]]></title>
            <link>https://javascript.plainenglish.io/how-to-deploy-your-javascript-application-e907251c6af1?source=rss-a57861a30cf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e907251c6af1</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jackson Chen]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 09:45:57 GMT</pubDate>
            <atom:updated>2020-08-28T09:45:57.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Deploy Your JavaScript Web Application</h3><h4>Deploy your JavaScript web application in less than 30 minutes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKDNvL6XMQkI_55M7WaImA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa">clark_fransa</a> on <a href="https://unsplash.com/photos/f77Bh3inUpE">Unsplash</a></figcaption></figure><p>Have you just finished your first JavaScript application and are now wondering “How do I get my application online?” In this tutorial, we’ll go over the quickest and easiest way on how to deploy your JavaScript application on to <a href="https://www.heroku.com/">Heroku</a>, using <a href="https://git-scm.com/">Git</a>, <a href="https://nodejs.org/en/">Node</a>, <a href="https://npmjs.com/">Node Package Manager</a>(NPM), and <a href="https://expressjs.com/">Express</a>.</p><p>Heroku, is a cloud-based platform which offers a free plan for web developers to manage and deploy their projects. In order to utilize their services, we will have to <a href="https://signup.heroku.com/">sign up</a>.</p><h4>0. Prerequisites</h4><p>Before we get started, please verify that Git, Node and NPM is installed by running the below commands in your terminal:</p><p>* $ means to run the command in your terminal.</p><pre>$ node --version</pre><p>If Node is not installed, download it <a href="https://nodejs.org/en/download/">here</a>.</p><pre>$ npm --version</pre><p>NPM is normally installed alongside with Node. However, if NPM isn’t installed on your system, try to reinstall a more current version of Node.</p><pre>$ git --version</pre><p>If Git is not installed, download it <a href="https://git-scm.com/downloads">here</a>. After Git is installed, let’s initialize a local repository for our application.</p><pre>$ git init</pre><h4>1. Install Heroku CLI</h4><p>Once we have signed up for Heroku and installed all prerequisites, install the <a href="https://devcenter.heroku.com/articles/heroku-cli">Heroku CLI</a> and login through your terminal.</p><pre>$ heroku login</pre><h4>2. Initialize a package.json in your Application Directory</h4><p>If you already have a <em>package.json</em> file already in your root application directory, you can skip to step 3.</p><p>Otherwise, in your root application directory, run the following command to initialize a <em>package.json</em> file. This file acts as an identifier (like an ID card for your application) and is required by NPM to know which dependencies to install for your application.</p><pre>$ npm init</pre><p>After running the command, you will be prompted with a series of questions which will auto-populate your <em>package.json</em> file with metadata from your answers. You can skip the questions for now by pressing enter as you are able to edit the file later.</p><h4>3. Installing Express</h4><p>Next, we will be using a Node.js web application framework called <a href="https://expressjs.com/">Express</a> to set up our server. To install Express, we’ll need to run the following command:</p><pre>$ npm install --save express</pre><p>Using NPM, this will help us download and install the necessary files for the Express module into the application directory. The --save flag will also list Express as a dependency in our <em>package.json</em> file.</p><h4>4. <strong>Setting up the Express server</strong></h4><p>Create a <em>server.js</em> file. This will act as our initializer script when we deploy our application on Heroku.</p><pre>$ touch server.js</pre><p>Next open the <em>server.js </em>file and save in the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a611b01a3deca653cb86d9e109994228/href">https://medium.com/media/a611b01a3deca653cb86d9e109994228/href</a></iframe><p>What does this even mean? Let’s go into a little bit more detail.</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const path = require(&#39;path&#39;);</pre><p>In order for our <em>server.js</em> script to use Express, we need to require the Express module by initializing const express = require(&#39;express&#39;).</p><p>The following line, const app = express(), then initializes the <em>app</em> variable with a new Express object. This will allow us to use the methods provided by the Express module.</p><p>Another module we’ll be using is the <a href="https://nodejs.org/api/path.html">Path</a> module provided by Node which we can access by const path = require(&#39;path&#39;). This will provide us with a set of methods we can use when working with path directories. In our case, we’ll mostly be using path.join(...).</p><pre>app.use(express.static(path.join(__dirname)));</pre><p>The app.use(path, callback) is called whenever a request (GET, POST, PATCH, DELETE) is sent to the <em>path</em> which triggers the callback function. Simply put, think of an event listener being placed on the denoted path with a callback function. However; if a <em>path</em> is <strong>not</strong> specified, the <em>callback</em> will trigger on every request regardless of the path. Since we currently don’t have a path set, our callback function express.static(...) will trigger on every request our site receives.</p><p>The express.static(...) is a middleware function which allows us to expose a directory or file for public usage. In our case, we have passed in path.join(__dirname) as the argument in our middleware function where __dirname represents the root directory of our application. This means every directory and file in our root application directory can be accessed by the client when their browser performs a request.</p><p>Don’t be alarmed! Remember that each time a client goes on to our website, their browser is performing a GET request. In turn, our server should send back a response along with <em>html</em>, <em>css</em>, and <em>js</em> file which makes up the basic web application. If we want to only allow a certain directory to be accessed publicly, we can pass in path.join(__dirname, &#39;<em>[name of the directory]</em>&#39;) instead. As our web applications become more sophisticated in manner, we may want to keep certain files hidden which may contain our API keys, secrets, etc. by limiting which files can be accessed publicly.</p><pre>app.get(&#39;/&#39;, function (req, res) {<br>  res.sendFile(path.join(__dirname, &#39;index.html&#39;));<br>});</pre><p>Here is where we set our routes. In the app.get(path, callback) function, the callback triggers when a GET request is made to the specified path. In our example, we currently have one route to &#39;/’ in which we are sending back <em>index.html</em> to the client. As long as our app.use(express.static(...)) allows our <em>css </em>and <em>js</em> files to be publicly used, the client browser will be able to receive those files for use as well. For now, this is enough to get our site up and running.</p><pre>app.listen(process.env.PORT || 3000);</pre><p>This line tells our web application which port to listen on. When we deploy our web application, Heroku will set a default port value for the server to use which will be denoted as process.env.PORT. If a port is not provided, our web application will default to port 3000.</p><p>To quickly test this out, we can run $ node server.js and go to <a href="http://localhost:3000">http://localhost:3000</a> in our browser. Once everything looks good, press Ctrl + C in your terminal to shut down the local server.</p><h4><strong>4. Configuring package.json</strong></h4><p>Once we have our <em>server.js</em> configured, we will have to set up instructions for Heroku to run our server when deployed. In your <em>package.json</em> file under <em>scripts</em> add &quot;start&quot;: &quot;node server.js&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d1d8d8689eb0e16963f43d75d4ea702/href">https://medium.com/media/0d1d8d8689eb0e16963f43d75d4ea702/href</a></iframe><p>Heroku will automatically look for the <em>start</em> script and execute it when deployed.</p><h4>5. Commit all changes using Git</h4><p>Now that we have configured all the files we need, run the following commands to commit our changes. First, we will need to stage our changes.</p><pre>$ git add .</pre><p>This command will add all our files to the staging area. Next, we will need to commit the changes.</p><pre>$ git commit -m &#39;[type some detailed message here]&#39; </pre><p>After committing your changes, we can finally deploy our application!</p><h4>6. Deploying our application to Heroku</h4><p>Run the following command and replacing the [] with a name of your application.</p><pre>$ heroku create [name of your app]</pre><p>This will initialize an app on the Heroku website and set up Heroku as a remote repository in your <em>.git</em> file. Once that is done, let’s push our local repository to the remote Heroku repository.</p><pre>$ git push heroku master</pre><p>Once our web application has successfully been pushed up to the remote repository, Heroku will automatically run the npm start script which we have previously defined in our <em>package.json</em> file. In turn, this will run node server.js and start up our server! If all goes well, we will be returned a URL to our web application!</p><p>Good luck and happy coding!</p><h4>Resources</h4><ul><li><a href="https://devcenter.heroku.com/articles/getting-started-with-nodejs?singlepage=true#provision-a-database">Getting Started on Heroku with Node.js</a></li><li><a href="https://nodejs.org/docs/latest-v13.x/api/path.html">Node.js Path Documentation</a></li><li><a href="https://docs.npmjs.com/about-npm/">About Node Package Manager</a></li><li><a href="https://git-scm.com/about">About Git</a></li><li><a href="https://expressjs.com/en/guide/using-middleware.html">Using ExpressJS Middleware</a></li><li><a href="https://www.tutorialspoint.com/expressjs/expressjs_static_files.htm">ExpressJS - Serving static files</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e907251c6af1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-deploy-your-javascript-application-e907251c6af1">How to Deploy Your JavaScript Application</a> was originally published in <a href="https://javascript.plainenglish.io">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Arrow Functions]]></title>
            <link>https://medium.com/@jacksonchen171/javascript-arrow-functions-31b21e84781c?source=rss-a57861a30cf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b21e84781c</guid>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jackson Chen]]></dc:creator>
            <pubDate>Wed, 12 Aug 2020 04:55:13 GMT</pubDate>
            <atom:updated>2021-03-19T13:15:45.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beginner’s guide to understanding and writing Arrow Functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEvfDpu6mhAl9vDcxp7w-Q.jpeg" /></figure><p>Whether you are starting your programming journey in a coding bootcamp or dabbling into JavaScript for the first time, encountering the Arrow Function can be quite daunting and confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*In49hWTEzZjOEZTQL78uTA.gif" /></figure><p>In fact, learning how to use Arrow Functions can be a powerful tool to have under your belt when used properly.</p><p>By this time, you are probably familiar with the classic <em>function declaration </em>method function foo() {...} as seen below:</p><pre>function greet(name) {<br>  return `Hello ${name}.`<br>}</pre><pre>greet(&#39;Joe&#39;)</pre><pre>// &quot;Hello Joe.&quot;</pre><p>Or as a <em>function expression </em>let foo = function() {...}</p><pre>let greet = function(name) {<br>  return `Hello ${name}.`<br>}</pre><pre>greet(&#39;Joe&#39;)</pre><pre>// &quot;Hello Joe.&quot;</pre><p>Although still effective, writing our functions this way can be quite repetitious and bulky at times. What if we were able to <em>condense </em>our code?</p><blockquote><em>Want to read this story later? </em><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text"><em>Save it in Journal.</em></a></blockquote><p>That’s where Arrow Functions come in. let foo = () =&gt; {...}</p><pre>let greet = (name) =&gt; {return `Hello ${name}.`}</pre><pre>greet(&#39;Joe&#39;)</pre><pre>// &quot;Hello Joe.&quot;</pre><p>We are able to further condense our Arrow Function given <em>certain limitations</em>.</p><p><strong>If your Arrow Function :</strong></p><ul><li>only has <strong>one parameter</strong>, you are allowed to omit the parenthesis () from the parameter.</li><li><strong>expression is only one-line in length</strong>, you can omit the curly brackets {} and the return from the expression. This is known as implicit return.</li></ul><pre>let greet = name =&gt; `Hello ${name}.`</pre><pre>greet(&#39;Joe&#39;)</pre><pre>// &quot;Hello Joe.&quot;</pre><p>Pretty awesome right? More commonly, you will probably encounter them when using iterators such as .map or .forEach. Here you can see an example of using function declaration vs the Arrow Function as a callback function for .map.</p><p><strong><em>Function Declaration</em></strong></p><pre>let numbers = [1, 2, 3]</pre><pre>numbers.map(<strong>function(number) {<br>  return number * 2<br>}</strong>)</pre><pre>// [2, 4, 6]</pre><p><strong><em>Arrow Function</em></strong></p><pre>let numbers = [1, 2, 3]</pre><pre>numbers.map(<strong>number =&gt; number * 2</strong>)</pre><pre>// [2, 4, 6]</pre><p>Arrow Functions makes it easier for us to write short-hand code which can increase in code readability, open to less bug opportunities and often used in more advanced libraries such as React. Of course there will be times when using the function declaration method is preferred. Ultimately, it is up to you as the programmer to decide which method is better suited for the task.</p><p>Thanks for reading and happy coding!</p><h4>Resources</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow Functions by MDN</a></li><li><a href="https://www.w3schools.com/js/js_arrow_function.asp">Arrow Functions by W3Schools</a></li></ul><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b21e84781c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>