<?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 Jeffery Shivers on Medium]]></title>
        <description><![CDATA[Stories by Jeffery Shivers on Medium]]></description>
        <link>https://medium.com/@jefferyshivers?source=rss-4445984ee3ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*15ikMKCyzlgRZOTsgm9vDA.jpeg</url>
            <title>Stories by Jeffery Shivers on Medium</title>
            <link>https://medium.com/@jefferyshivers?source=rss-4445984ee3ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 22:40:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jefferyshivers/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[GraphQL Composition with Fragments]]></title>
            <link>https://medium.com/@jefferyshivers/graphql-composition-with-fragments-2c56bfd11673?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c56bfd11673</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 17:42:17 GMT</pubDate>
            <atom:updated>2021-12-09T17:48:55.001Z</atom:updated>
            <content:encoded><![CDATA[<p>I have seen client-side GraphQL composition done the wrong way all too often. As it turns out, there is actually a fragment type built into GraphQL that makes type composition much easier to work with. In this article, I’ll provide examples in Javascript as if we are writing browser-side client code.</p><h3>Composition without fragments</h3><p>Here is an example of how we might reuse a GraphQL string with traditional interpolation:</p><pre>const DAYS = `<br>  monday tuesday wednesday thursday friday saturday sunday<br>`</pre><pre>const GET_STORE_INFO_QUERY = `<br>  query {<br>    getStoreInfo {<br>      schedule {<br>        ${DAYS}<br>      }<br>    }<br>  }<br>`</pre><p>This will certainly work if we simply try to use it to call the GraphQL server, but we’ll eventually run into some weird issues if we try to use any sort of static analysis tools like graphql-inspector (more on that later).</p><h3>Composition with fragments</h3><p>Here is the same example from above but using fragments:</p><pre>const DAYS_FRAGMENT = `<br>  fragment days on Schedule {<br>    monday tuesday wednesday thursday friday saturday sunday<br>  }<br>`</pre><pre>const GET_STORE_INFO_QUERY = `<br>  ${DAYS_FRAGMENT}</pre><pre>  query {<br>    getStoreInfo {<br>      schedule {<br>        ...days<br>      }<br>    }<br>  }<br>`</pre><p>Yes, we are still using template literals to add the fragments to the query string, but this is completely valid and how fragments are meant to be used.</p><p>If you want to experiment with fragments in the GraphQL playground, you can simply recreate the expression in its composed form:</p><pre>fragment days on Schedule {<br>  monday tuesday wednesday thursday friday saturday sunday<br>}</pre><pre>query {<br>  getStoreInfo {<br>    schedule {<br>      ...days<br>    }<br>  }<br>}</pre><h4>Fragments with variables</h4><p>You can even use variables with fragments just like other types.</p><pre>fragment days on Schedule {<br>  monday tuesday wednesday thursday friday saturday sunday<br>}</pre><pre>fragment employees on StoreInfo {<br>  employees(status: $status) {<br>    id<br>    name<br>  }<br>}</pre><pre>query GetStoreInfo($status: EmployeeStatus = ACTIVE) {<br>  getStoreInfo {<br>    schedule {<br>      ...days<br>    }<br>    ...employees<br>  }<br>}</pre><p>As you can see in this example, fragments can be queries or any other GraphQL struct.</p><p>Fragments are the canonical mechanism provided by GraphQL to compose types in clean, reusable ways. They give us the flexibility to breakup complex queries, reduce redundant code, and still leverage powerful static analysis tools in our projects. In a future article, I will demonstrate one of those tools, graphql-inspector which might save you from deploying broken queries to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c56bfd11673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Merge Patch (in Any Language)]]></title>
            <link>https://medium.com/@jefferyshivers/implementing-a-merge-patch-in-any-language-2efe601ea657?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/2efe601ea657</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 18:10:23 GMT</pubDate>
            <atom:updated>2020-07-17T00:22:59.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Visualization of merging two data objects." src="https://cdn-images-1.medium.com/max/1024/1*4_ZlZbmpt7ltA3bgFvqBgg.png" /></figure><p>RESTful patterns fit best into services that are rigid and basic in how they implement CRUD methods. The “U” in CRUD — the update method — is often the most complicated. On the surface, it is simple in concept (just <em>update some data</em>) but there are many ways to interpret that meaning and fit it into your system. The easiest update design to implement is to PUT new data <em>in place of</em> the old, and the most difficult is to PATCH new data <em>over</em> the old. A PATCH resource could itself be designed various ways, but this article is going to focus on the merge patch.</p><h3>What is a merge patch?</h3><p>The best explanation of what merge patch means would be the <a href="https://tools.ietf.org/html/rfc7386">original RFC</a> from 2014. The tldr is: a merge patch means modifying existing content with a literal merge of partial incoming data into the preexisting data. We are going to focus on doing this with JSON since it is the most common approach, but the same concepts could apply in other formats as well.</p><p>We can exemplify this with a simple scenario. If you have a resource with some data about a person and you want to make a modification, your original data might look like this:</p><pre>GET /people/{personId}<br>{<br>  &quot;firstName&quot;: &quot;John&quot;,<br>  &quot;lastName&quot;: &quot;Doe&quot;<br>}</pre><p>You want to be able to change some of the data with a request that includes only explicit modifications, like this:</p><pre>PATCH /people/{personId}<br>{ <br>  &quot;firstName&quot;: &quot;Jane&quot; <br>}</pre><p>The modified data will ideally include the preexisting data with those new modifications (in this case, only the “lastName” property) applied on top of it:</p><pre>GET /people/{personId}<br>{<br>  &quot;firstName&quot;: &quot;Jane&quot;,<br>  &quot;lastName&quot;: &quot;Doe&quot;<br>}</pre><p>So this all probably seems intuitive, and it really is. But the unintuitive part is actually implementing the design in whatever language/framework, and doing so such that it doesn’t wipe out unmodified data. You need your system to be able to know the difference between absent values and newly modified null values (e.g. &quot;lastName&quot;: null versus the complete absence of the “lastName” property), and this needs to be able happen at any depth in the tree. Well, you get to decide where things are literally merged versus replaced still, but we’re going to focus on making it possible to merge to any extent/depth necessary.</p><h3>The Language-Agnostic Details of an Implementation</h3><p>Let’s think through this and design as much as we can without focusing on a specific language. As I mentioned before, we need a way to distinguish between present and absent values in our merge request. This means, we need a mechanism that traverses/parses the incoming request and gives us the details about what is new. Ultimately, we don’t even care about what <em>isn’t</em> changed. In fact, if we are really designing a clean system, the request isn’t designed around the internal data structure at all, but rather a structured request which just might happen to mirror the internal design.</p><p>Let’s say that we are using an object-oriented language; this means we can have some object like “UpdatePersonRequest”, an instance of which gets deserialized from a JSON entity. We want to be able to find out from this object what new data has been provided/modified. In pseudo-code, that could look something like this:</p><pre>UpdatePersonRequest {<br>  string firstName<br>  string lastName<br>}</pre><p>Here, I’m left with not knowing whether any null values in this were actually set or not. In other words, if I deserialized an instance of this object from a JSON payload like { &quot;firstName&quot;: &quot;Jane&quot; }, I’d get an instance that looks like this:</p><pre>UpdatePersonRequest {<br>  firstName: &quot;Jane&quot;,<br>  lastName: null<br>}</pre><p>When I proceed to apply this request to my internal data, I have to assume that the “lastName” was updated to null. But that’s not what I intended, so let’s try something else. Instead of these literal values in the request object, I can set some sort of generic object type which contains information on whether each property was updated (and if so, what’s the new value).</p><pre>UpdatePersonRequest {<br>  MaybeUpdated&lt;string&gt; firstName = MaybeUpdated() // default<br>  MaybeUpdated&lt;string&gt; lastName = MaybeUpdated() // default<br>}</pre><pre>MaybeUpdated&lt;T&gt; {<br>  boolean wasUpdated = false // default<br>  T value<br>}</pre><p>Don’t get hung up on the notation here — remember, this is just pseudo code. The &lt;T&gt;-like syntax is a common way of notating type parameters in statically typed languages. If that’s confusing, you can visualize this example with all of those removed, and it conceptually means the same thing for our use case.</p><p>The takeaway in this example is that I now have a request object that I can somehow parse from the incoming JSON payload, and then use to apply changes for any of the values with the wasUpdated property set to true. I won’t go into how we actually do that, but the gist of it is: traverse the raw JSON and create an instance of UpdatePersonRequest with the sub-properties that are present (in our example, “firstName”) set in the object.</p><pre>UpdatePersonRequest {<br>  firstName: { wasUpdated: true, value: &quot;Jane&quot; }<br>  lastName: { wasUpdated; false, value: null }<br>}</pre><h4>Caveats and Alternatives</h4><p>In the best case scenario, you are using a framework that provides serialization and can do most (or all) of this work for you. You may be able to get mostly there and only need to provide some function/class to the framework that tells it how to parse/deserialize into these new objects (MaybeUpdated) specifically, but that’s usually not a heavy lift and is something you only have to do once.</p><p>If you aren’t working with types or classes, you can still simulate the approach here using whatever the language’s implementation of maps is (e.g. Maps in Java, object literals in Javascript, dictionaries in Python, and so on). However, those have their tradeoffs. Using generic maps/objects means that you are bound to doing reflection at some point or otherwise working with generic structures on both ends of the exchange (between updates and the resulting work you do with them), and that’s just not ideal.</p><p>If you are working in a language where you typically use generic maps/objects, I’m first going to suggest migrating towards a more strongly typed approach (even if you aren’t literally using types in your language, there are various schema validation libraries that are helpful for both the server and client side sanity). If that isn’t an option, then you just might have a little more work to do to simulate what we’ve done here; you’ll have to iterate/reflect over every provided updated value as generic data (or otherwise over the target object), and that just has the possibility of getting expensive (time-wise) fast and really isn’t best practice.</p><h3>Conclusion</h3><p>Note that I didn’t go into how you deal with the data once it is parsed from the request. Whether you are just applying the changes to an internal representation and then saving that in a single node in a database, or using a fancy ORM to magically do that for you, or even converting the updates into small bite-sized events to then be processed/published before ultimately resurfacing in your read model, the complexity in merge patches lies mostly within the interpretation/model of the data received from the outside. As soon as possible, you want to know and hold onto the difference between provided values and absent values, and let the rest of your system react to those explicit changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2efe601ea657" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Public API with gRPC]]></title>
            <link>https://medium.com/@jefferyshivers/create-a-public-api-with-grpc-ade4a8bfd1fc?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade4a8bfd1fc</guid>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Sat, 21 Mar 2020 20:22:28 GMT</pubDate>
            <atom:updated>2020-05-25T20:37:23.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Vvnv8jSeXSwSac3mM7UHRA.png" /></figure><p>In this article, I’ll demonstrate how to create a public API with gRPC. The application code itself will be relatively simple and won’t include authentication, with more focus instead on the tooling and methodology around building the service as a whole and exposing the protobufs so that consumers can generate clients from the same protos to use the service.</p><h4>Learning Objectives</h4><ul><li>Create a Protocol Buffer library</li><li>Create a gRPC service implementation (Java)</li><li>Create a gRPC client implementation (Node)</li></ul><h4>Requirements</h4><ul><li><a href="https://www.oracle.com/java/technologies/javase-jdk13-downloads.html">Java 9+</a></li><li><a href="https://nodejs.org/en/">Node 8+</a></li><li><a href="https://protop.io/">protop</a></li></ul><h3>Create a Protocol Buffer Library</h3><p>We first want to create the protobufs that will describe the API we want to build. In this example, I’m creating a service to convert money between currencies. Let’s say this is part of a larger numbers-oriented service.</p><h4>Initialize the project with protop</h4><p>If you haven’t installed protop before, you can do so either from Homebrew ( brew tap protop/io &amp;&amp; brew install protop) or from the source following the instructions <a href="https://protop-io.github.io/protop/">here</a>.</p><pre>$ mkdir numbers-protos &amp;&amp; cd $_<br>$ protop init</pre><p>Following the prompt, I’ll create a basic protop manifest:</p><pre>Organization name (required): awesomelabs<br>Project name (required): numbers<br>Initial revision (default 0.1.0):</pre><p>We won’t have to do anything with it after this point, but here’s the protop.json that was generated:</p><pre>{<br>  &quot;organization&quot; : &quot;awesomelabs&quot;,<br>  &quot;name&quot; : &quot;numbers&quot;,<br>  &quot;version&quot; : &quot;0.1.0&quot;,<br>  &quot;include&quot; : [ &quot;.&quot; ],<br>  &quot;dependencies&quot; : { }<br>}</pre><h4>Create some protos</h4><p>Now, I’ll create a small proto file to define a money service. Since this tutorial isn’t about writing protos themselves, I’ll skip going through it in depth; here’s the proto I’ve created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1347dbfc85efe8c5dd9db8ca7fb7a24/href">https://medium.com/media/b1347dbfc85efe8c5dd9db8ca7fb7a24/href</a></iframe><p>This basically just defines a few messages that hold information about money and a service with a single RPC to convert a value from one currency to the other.</p><p>To make it available to other projects, I can either publish locally (protop link), publish to an external registry (protop publish), or publish to a VCS platform like Github (just create a normal Git project, and push it up). I’ll do the latter — and you can find that repository <a href="https://github.com/jefferyshivers/numbers-protos">here</a>. Now, the library is available to any other project that wants to use it. In the next part, I’ll demonstrate doing that to create a gRPC service that implements the MoneyService proto.</p><h3>Create a gRPC Service Implementation (Java)</h3><h4>Initialize the application with Gradle</h4><p>Setting up a Java project is a little more involved than the previous step, but I’m using <a href="https://gradle.org/">Gradle</a> to make it easier. Here’s what that looks like for me using Gradle 6.2.1:</p><pre>$ mkdir numbers-service &amp;&amp; cd $_<br>$ gradle init</pre><pre>Select type of project to generate:<br>  1: basic<br>  2: application<br>  3: library<br>  4: Gradle plugin<br>Enter selection (default: basic) [1..4] 2</pre><pre>Select implementation language:<br>  1: C++<br>  2: Groovy<br>  3: Java<br>  4: Kotlin<br>  5: Swift<br>Enter selection (default: Java) [1..5] 3</pre><pre>Select build script DSL:<br>  1: Groovy<br>  2: Kotlin<br>Enter selection (default: Groovy) [1..2] 1</pre><pre>Select test framework:<br>  1: JUnit 4<br>  2: TestNG<br>  3: Spock<br>  4: JUnit Jupiter<br>Enter selection (default: JUnit 4) [1..4] 4</pre><pre>Project name (default: numbers-service):<br>Source package (default: numbers.service): awesomelabs.numbers</pre><pre>&gt; Task :init<br>Get more help with your project: <a href="https://docs.gradle.org/6.2.1/userguide/tutorial_java_projects.html">https://docs.gradle.org/6.2.1/userguide/tutorial_java_projects.html</a></pre><pre>BUILD SUCCESSFUL in 48s<br>2 actionable tasks: 2 executed</pre><h4>Make it a protop project as well</h4><p>Next, I’ll make this into a protop project so that I can import the numbers-protos library. Instead of going through the protop init interface, I can also of course just create a protop.json manually. Here’s what that looks like so far:</p><pre>{<br>  &quot;organization&quot; : &quot;awesomelabs-internal&quot;,<br>  &quot;name&quot; : &quot;numbers-service&quot;,<br>  &quot;version&quot; : &quot;0.1.0&quot;,<br>  &quot;include&quot; : [ &quot;.&quot; ],<br>  &quot;private&quot;: true,  <br>  &quot;dependencies&quot; : { }<br>}</pre><p>Now, I just need to add my protos library as a dependency. Since the awesomelabs/numbers library was published to a Github repository, I’ll use that URL instead of a version, prepended with “git:” so protop knows that it’s definitely a Git repository (note: Medium is wrapping the lines here):</p><pre>&quot;dependencies&quot;: {<br>  &quot;awesomelabs/numbers&quot;: &quot;git:https://github.com/jefferyshivers/numbers-protos&quot;<br>}</pre><h4>Sync the external protobuf dependencies</h4><p>This should be enough to run protop sync and import the dependencies for the project:</p><pre>$ protop sync<br>Syncing external dependencies.<br>Done syncing.</pre><p>And now if I look inside the project’s protop path in the project directory, I can see that the dependency was imported as expected from Github:</p><pre>$ ls .protop/path/awesomelabs/numbers/<br>README.md money.proto protop.json</pre><p>I’ll add that path to my Gradle configuration so that the protoc compiler can use those protos to generate the classes needed for the service implementation. After setting up my build.gradle to use the <a href="https://github.com/google/protobuf-gradle-plugin">protobuf</a> plugin, I just need to add the protop path as a proto source directory:</p><pre>sourceSets {<br>    main {<br>        proto {<br>            srcDirs += &quot;.protop/path&quot;<br>        }<br>        ...<br>    }<br>}</pre><p>To make things easier so that I don’t have to run protop sync manually, I can create a simple command line task in Gradle, and make it execute before protoc generates anything:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e33feba58a56d0bc7faf10c3b2e65d/href">https://medium.com/media/46e33feba58a56d0bc7faf10c3b2e65d/href</a></iframe><p>You’ll notice that I added a flag --git-refresh; this tells protop to refresh the Git sources every time sync is run. When it does this, it will re-clone the repository rather than <em>pulling</em>. While this might seem expensive, it means you can be as specific as you need with any dependencies down to the commit (e.g. https://github.com/&lt;repo_name&gt;/tree/&lt;commit_sha&gt;) without worrying that using --git-refresh will pull newer revisions if you don’t want them. Since I wasn’t that specific with this dependency, I’m ok with getting the latest version from the master branch every time.</p><p>When we build the project now, the output logs should look something like this:</p><pre>$ gradle clean &amp;&amp; gradle build</pre><pre>BUILD SUCCESSFUL in 720ms<br>1 actionable task: 1 executed</pre><pre>&gt; Task :protop<br>Syncing external dependencies.<br>Done syncing.</pre><pre>BUILD SUCCESSFUL in 4s<br>12 actionable tasks: 12 executed</pre><h4>Implement the gRPC service</h4><p>Finally, the generated protos (in this case, Java classes) should have been generated such that I can actually write out the service. Here’s a simple implementation of the service with the convert RPC call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e50ff7e5bcd234bdd4442f064a630d/href">https://medium.com/media/33e50ff7e5bcd234bdd4442f064a630d/href</a></iframe><p>You can see the full project here; the main files to look at are the build.gradle, awesomelabs.numbers.App, and awesomelabs.numbers.MoneyService. And now I should be able to start the service:</p><pre>gradle clean &amp;&amp; gradle run</pre><pre>BUILD SUCCESSFUL in 1s<br>1 actionable task: 1 executed</pre><pre>&gt; Task :protop<br>Syncing registered dependencies.<br>Done syncing.</pre><pre>&gt; Task :run<br>Server started on port 8080<br>&lt;===========--&gt; 87% EXECUTING [15s]<br>&gt; :run<br>|</pre><h3>Create a gRPC Client Implementation (Node)</h3><p>Now that the money service is running, it should be possible to create a gRPC client and interact with it. Since it doesn’t matter what language the service or client are in, I’ll do this part in Node.</p><pre>mkdir numbers-node-client &amp;&amp; cd $_</pre><h4>Create a new protop project</h4><p>As with the service implementation, I’ll create a protop manifest and add the awesomelabs/numbers package as a dependency.</p><pre>{<br>  &quot;name&quot;: &quot;numbers-node-client&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;organization&quot;: &quot;awesomelabs&quot;,<br>  &quot;include&quot;: [ &quot;.&quot; ],<br>  &quot;dependencies&quot;: {<br>  &quot;awesomelabs/numbers&quot;: &quot;git:https://github.com/jefferyshivers/numbers-protos&quot;<br>  }<br>}</pre><p>If you’re new to gRPC (or to using it with Node), I created the client to pretty closely mirror the <a href="https://grpc.io/docs/tutorials/basic/node/#loading-service-descriptors-from-proto-files">example Node client</a> in the official gRPC documentation. Here’s what it ended up looking like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/393f5267212a3c27cc462c75a4405a81/href">https://medium.com/media/393f5267212a3c27cc462c75a4405a81/href</a></iframe><p>As you can see, I am dynamically loading the protos from the protop path, and then creating a service client. The gRPC library allows me to use JSON to build the request protos and will handle serializing them in the RPC. Now, running the script in the project directory should result in console output similar to the following (with different numbers since they are always randomized):</p><pre>$ node .<br>Original: 7.3406037480265685 USD<br>Converted: 5.33649466631217 MXN</pre><p>And that’s it! I can continue to create any number of service implementations or clients using that original protobuf library without adding any fancy pipelines to generate artifacts.</p><h3>Conclusion</h3><p>I hope that this example helps demonstrate that protocol buffers and gRPC can be easier to work with than they initially might seem. They are great technologies with somewhat intimidating first impressions, but ultimately, with the right tools and development patterns, they can make your life building robust projects — whether it’s a public API, an internal microservice mesh, or even just a simple library of protocol buffers for others to build upon.</p><h4>Examples on Github</h4><p>I’ve published all the examples used in this tutorial to Github. Feel free to clone them, or use them as a basis for a new project. I’m also interested to see other examples out there, so please let me know if you’d like for me to share what you’ve created and I’ll gladly link to it here!</p><ul><li><a href="https://github.com/protop-io/numbers-protos">“numbers-protos” - protobuf library</a></li><li><a href="https://github.com/protop-io/numbers-service">“numbers-service” - gRPC service implementation (Java)</a></li><li><a href="https://github.com/protop-io/numbers-client">“numbers-client” - gRPC client implementation (Node)</a></li></ul><h4>Additional resources</h4><ul><li><a href="https://protop-io.github.io/protop/">protop - protocol buffer package manger</a></li><li><a href="https://developers.google.com/protocol-buffers">protocol buffers - official website</a></li><li><a href="https://grpc.io/">gRPC - official website</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade4a8bfd1fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing protop: a tool for protobufs]]></title>
            <link>https://medium.com/@jefferyshivers/introducing-protop-a-tool-for-protobufs-d81eaeb237be?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81eaeb237be</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Sat, 14 Mar 2020 17:43:30 GMT</pubDate>
            <atom:updated>2020-03-14T17:54:52.951Z</atom:updated>
            <content:encoded><![CDATA[<h3>protop: a Tool for Protocol Buffers and gRPC</h3><p><a href="https://protop-io.github.io/protop/">Protop</a> (“proto p”) is a new tool for working with protocol buffers. The core focus of the project is the challenge of dependency management and resource sharing, especially for projects that span beyond a single code base — think: distributed systems, public APIs, or even just common protobuf definitions.</p><figure><img alt="protop logo" src="https://cdn-images-1.medium.com/max/1024/1*fWjG4b08j7mIlX19sLZVJg.png" /></figure><h3>Motivation</h3><p>Monorepos for developing/building protobufs have become convention for a few reasons — mainly easy sibling dependency and pipeline aggregation. But this quickly becomes an anti-pattern when the monorepo itself becomes a complicated bottleneck for workflows. Unless your organization is <a href="https://research.google/pubs/pub45424/">all in on this pattern</a>, it can be painful, for example, to release new versions of a protobuf or to differentiate between small changes and significant ones.</p><p>On the other hand, we can look at tools like <a href="https://maven.apache.org/">Maven</a>, <a href="https://packaging.python.org/tutorials/installing-packages/">pip</a> and <a href="https://docs.npmjs.com/about-npm/">NPM</a> and see that a good pattern for resource sharing — or <em>package management</em> — has already been established and proven. With the potential simplicity of proto project structures and the availability of existing tools like <a href="https://github.com/uber/prototool">protoc</a> and <a href="https://github.com/uber/prototool">Prototool</a>, the foundation has been laid for robust project development, and the only missing piece is a mechanism for sharing/retrieving protos with an access pattern that can include external registries.</p><h3>Goals</h3><p>Protop is aimed at solving the problem of sharing protobufs. The tool attempts to be powerful but invisible — it generally stays out of the way and leaves only the smallest footprint in your projects. At a much higher level, I’m hoping to bring the community together with the common goal of building something that allows us to create/distribute protos with a standard approach that will facilitate more collaboration in general, as well as promote an easier path towards using protocol buffers and gRPC altogether.</p><h3>Deliverables</h3><p>The two main components of protop are:</p><ul><li><a href="https://github.com/protop-io/protop"><strong>the </strong></a><a href="https://github.com/protop-io/protop"><strong>protop CLI</strong></a><strong>:</strong> This is the main interface that allows you to compose projects and retrieve protos from other projects. The most significant features include the abilities to publish (protop publish), sync external dependencies via a <a href="https://github.com/protop-io/protop#initialize-a-project">simple manifest</a> (protop sync), and link a project locally (protop link) — this is analogous to npm link or gradle publishToMavenLocal.</li><li><a href="https://github.com/protop-io/nexus-repository-protop"><strong>Nexus repository integration</strong></a><strong>:</strong> This plugin allows anyone to add a protop repository to a new or existing Nexus instance.</li><li><strong>A public repository:</strong> I haven’t focused on creating a public repository yet, but that is something that’s very high on the roadmap. I’m partly hoping that your feedback/collaboration will help inform good decisions about how that will/should come to be.</li></ul><h3>Outcomes</h3><p>Here are the most significant ways that protop will impact projects and the biggest takeaways:</p><ul><li><strong>Artifacts don’t have to be shared.</strong> When working with protobufs, the protos themselves are the contracts that should be shared, <em>not</em> the artifacts that they generate.</li><li><strong>Pipelines are simplified.</strong> Protop removes the need to build pipelines that do overly complex tasks to compose/track protos in an organization.</li><li><strong>Protop works seamlessly with existing build tools.</strong> Because it doesn’t try to replicate any part of the protoc compiler or other build tools like Gradle, and due to its simple API, it integrates with minimal effort.</li><li><strong>Proto projects can become the small, composable units that they were meant to be.</strong></li></ul><h3>RFC (Request for Comments)</h3><p>This project was motivated by my own observations and wishes as a developer working with protobufs and gRPC, both on the job and in my personal projects. But that doesn’t mean that I’ve necessarily made something that is the most useful for other developers. With that said, I’d love to get feedback on the project.</p><h3>RFC (Request for Contributors)</h3><p>I need help building this tool and making it better! There is a huge roadmap ahead, and besides trying to build features and get to 1.0 faster, having more hands on deck will keep the project direction in check and ensure a better probability of building the best quality and most useful tool we can. Please visit the projects at <a href="https://github.com/protop-io">https://github.com/protop-io</a> and join in on the fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81eaeb237be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flux and Lightning Components]]></title>
            <link>https://medium.com/@jefferyshivers/flux-and-lightning-components-5ce975027bef?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce975027bef</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <category><![CDATA[flux]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Sun, 06 May 2018 16:44:40 GMT</pubDate>
            <atom:updated>2020-03-14T17:33:38.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK8qRbgtLl3BjxUQsWTjRg.png" /></figure><p>I recently began working with the Lightning Component Framework (Salesforce’s latest front-end toolset). As a Javascript — and particularly a React + Redux — developer at heart, of course one of the first questions I had when entering this new space was how it lends itself to flux architectures.</p><p>Out of the box, Lightning comes with a hefty load of useful features that can be uniquely composed to create a unidirectional data flow, but it doesn’t come with any specific suggestions for exactly how to set something like that up. Perhaps that’s because it really isn’t that difficult, or maybe they want to leave it open for developers to decide because the subtle differences between approaches could affect big changes that are hard to detect if one isn’t forced to consider them (oof); or maybe it just isn’t a big enough concern for Salesforce, compared to the broader idea of simple reusability, for example, which seems to have been the overarching theme of the framework from the beginning.</p><p>In any case, I figured the relatively low number of existing resources regarding this topic was the perfect excuse for me to share my own understanding of how flux might be successfully achieved in a Lightning component project. I’ll also discuss at a higher level why flux can in general be useful for Salesforce developers and things to keep in mind as one adopts such a pattern.</p><h4>A Brief Background of a Few Important Lightning Features</h4><p>Just to cover all my bases, these are some things you should definitely know about before trying to extend what Lighting is already capable of doing:</p><p><strong><em>Attributes:</em></strong> Enough can’t be said about the importance and usefulness of attributes in Lightning components. This includes the traditional HTML flavor of attributes that web developers are all familiar with, as well as the &lt;aura:attribute ...&gt; attributes which are set inside the body at the component level (well, technically not in the {!v.body}, but between the component tags at the top level) and can of course be reached/set through parent components in that traditional manner. Attributes allow us to chain values between parent/child components, they can hold a changing state at the individual component level, and they can be dynamically changed or referenced in javascript. That last part is a powerful feature because of its simplicity (which makes a world of difference when you are talking about building an API around existing functionality).</p><p><strong><em>Events:</em></strong><em> </em>The Lightning event API is another super handy feature of the framework, and it is probably the one of which I have the fewest complaints (I really don’t have many overall, to be fair). It carefully distinguishes between two types of events: <em>component</em> and <em>application</em>. The gist of that difference is that component events bubble, like the traditional DOM events we are used to (such as the almighty “click”) that are propagated up the stack (until/unless propagation is explicitly halted) and <em>not</em> received by sibling or descendent components. Application events, on the other hand, are broadcast application-wide; any component related in the application stack is eligible to receive the event, and all dispatchers and subscribers are entirely decoupled (thus, there is no order for who receives the event, and no recipient can change anything about that event once it has been fired).</p><p><strong><em>Components</em></strong>: These are the workhorses of the Lightning framework. They may or may not contain actual HTML markup. At its core, a component is an engine that may have attributes (and other things like handlers and methods, but we’ll brush over that for now) and a body, which is an array of zero or more elements/components. It delegates javascript to its controller (and optionally a separate <em>handler.js</em>), and can connect to a specific Apex controller as well. It knows how to update its own state whenever the value of a bound attribute ({!v.myAttribute}) is changed, so that you don’t have to. Just hook it up, and let the powerful lightning engine handle the rest.</p><h4>Why Flux?</h4><p>Let’s talk about application state. Say there is some value, such as the amount of time that has passed since page load, which two or more components care about (and display)— is it efficient, or <em>safe</em>, to have the same logic repeated across components to handle the updating value? The answer to that is clearly no. And in this case, we could simply put our clock in the top level component and chain it down to each child attribute that cares through good ole attributes. But eventually, if we have enough of these shared values and a scaling application, we’ll be left with quite a mess to pick through with our eyes (and our brains), so maintainability is something we want to keep in mind as well.</p><p>The biggest danger in our clock example is illustrated here: say we didn’t delegate the timing to one top level attribute but rather to the individual components, that one of the clocks could, for example, get out of sync; there is no way for it or any of the other components to know that this happened, and so the application would continue onward as if everything is fine. Clocks are pretty accurate, so let’s make this problem a little more real: one of the components has a pause button. Now, we have to notify all of the other components that time has stopped, and we still don’t know for sure that they are even synchronized. If we go back to having the clock at the top level, and simply chain the time value down to each child, this last problem is all of a sudden much less intimidating because now we only have to notify one component about the change, and we can count on that component to update all the children that care about it. And <em>that</em> is the beauty of flux: unidirectional data flow from a single source of truth.</p><h4>Disclaimer(-ish)</h4><p>I want to top this last part off and prepend the next section with a warning about using flux. It is unbelievably tempting to put <em>everything</em> in the application state when you start programming with this pattern. It seems awesome and smart and efficient and clean to just put it all in one place, but that really isn’t the idea behind unidirectional data flow. Use flux to only handle shared <em>application</em> state. That is, the stuff that is crucial to the success of some core application functionality (like persisting un-submitted form data across changing routes in a SPA, or more typically sharing data between components)— not something that only the little widget in the left side bar cares about and no one else. Don’t flood the flux highway with unnecessary pieces. You’ll end up creating way more work for yourself that way, and the value of flux will be lost.</p><p>Leverage component attributes when you can; Lightning has such a great way of handling stateful components through attributes (even more simply than React does in basic cases), and that should be taken advantage of. That is not to say that you can’t have overlapping flux hierarchies if you really need to; maybe that widget is super complex and comes with a bunch of children components that share data — just make sure that the pattern is justified. Otherwise, if you need it in only one place, keep it in that one place.</p><h4>An Example in Lightning</h4><p>Ah, at last, code. I know, these things usually come with so much more copy-and-pastable code examples, and I’m sorry for holding out. But my hope is that this article will have revealed enough that you can easily imagine how to set something like this up without much strain or need for further research, even as a newcomer to the Lightning framework like me.</p><p>In this solution, I am creating the following pieces:</p><ul><li>a base FluxContainer component, which is extensible so that other components can use it to manage their application state</li><li>a FluxContainer_getState application event which will be broadcast by the container</li><li>a FluxContainer_setState component event that can be fired by any component to update state</li><li>a parent component, which extends the FluxContainer</li><li>two instances of a child component, which has a button and shows the number of times the button (in either instance) has been clicked</li></ul><p><strong><em>FluxContainer.cmp</em></strong></p><pre>&lt;aura:component exstensible=&quot;true&quot;&gt;<br>  &lt;aura:registerEvent name=&quot;getState&quot;<br>                      type=&quot;e.c:FluxContainer_getState&quot; /&gt;<br>  &lt;aura:handler name=&quot;setState&quot; <br>                event=&quot;c:FluxContainer_setSTate&quot; <br>                action=&quot;{! c.setState }&quot; /&gt;<br>&lt;/aura:component&gt;</pre><p><strong><em>FluxContainer.controller.js</em></strong></p><pre>({<br>  setState: function (component, event, helper) {<br>    var update = event.getParam(&#39;update&#39;);<br><br>    if (<br>      update.containerName &amp;&amp;<br>      component.get(&#39;v.containerName&#39;) &amp;&amp;<br>      update.containerName == component.get(&#39;v.containerName&#39;)<br>    ) {<br>      helper.setState(<br>        component,<br>        update.containerName,<br>        update.state,<br>        update.callback<br>      );<br>    } else {<br>      console.error(&#39;There was a problem pairing containerNames.&#39;);<br>    }<br>  }<br>})</pre><p><strong><em>FluxContainer.helper.js</em></strong></p><pre>({<br>  setState : function (component, containerName, state, callback) {<br>    var res = {<br>      unavailable_attributes: []<br>    },<br>      updates = [];<br><br>    for (var param in state) {<br>      var attr = &#39;v.&#39; + param;<br>      var val = state[param];<br><br>      if (component.get(attr)) {<br>        component.set(attr, val);<br>        updates.push({<br>          attribute: attr,<br>          value: val<br>        });<br>      } else {<br>        res.unavailable_attributes.push(param);<br>      }<br>    }<br><br>    // post the update as an application event<br>    if (updates.length &gt; 0) {<br>      var updateEvent = <br>          component.getEvent(&#39;e.c:FluxContainer_getState&#39;);<br>      updateEvent.setParams({<br>        containerName: containerName,<br>        state: updates<br>      });<br>      updateEvent.fire();<br>    }<br><br>    // call the optional callback<br>    callback &amp;&amp; callback(res);<br>  }<br>})</pre><p><strong><em>FluxContainer_getState.evt</em></strong></p><pre>&lt;aura:event type=&quot;APPLICATION&quot; description=&quot;FluxContainer_getState&quot;&gt;<br>    &lt;aura:attribute name=&quot;update&quot; type=&quot;Object&quot; default=&quot;{}&quot;/&gt;<br>&lt;/aura:event&gt;</pre><p><strong><em>FluxContainer_setState.evt</em></strong></p><pre>&lt;aura:event type=&quot;COMPONENT&quot; description=&quot;FluxContainer_setState&quot;&gt;<br>    &lt;aura:attribute name=&quot;newState&quot; type=&quot;Object&quot; default=&quot;{}&quot;/&gt;<br>&lt;/aura:event&gt;</pre><p><strong><em>Parent.cmp</em></strong></p><p>Make a parent component that acts as the whole application container. Invoke two child components.</p><pre>&lt;aura:component description=&quot;parent&quot;<br>                extends=&quot;c:FluxContainer&quot;&gt;<br>  &lt;aura:handler name=&quot;init&quot; <br>                value=&quot;{! this }&quot;<br>                action=&quot;{! c.onInit }&quot;<br><br>  &lt;aura:attribute name=&quot;containerName&quot; <br>                  type=&quot;String&quot; <br>                  default=&quot;parentContainer&quot;/&gt;<br>  &lt;aura:attribute name=&quot;someAttribute&quot; <br>                  type=&quot;Integer&quot; <br>                  default=&quot;0&quot;/&gt;<br>  <br>  &lt;Child /&gt;<br>  &lt;Child /&gt;</pre><pre>&lt;/aura:component&gt;</pre><p><strong><em>Parent.controller.js</em></strong></p><p>Add the onInit function which will initialize its state and broadcast it.</p><pre>({<br>  onInit : function (component, event, helper) {<br>    var init = component.getEvent(&#39;c:FluxContainer_getState&#39;);<br>    init.setParams({<br>      containerName: component.get(&#39;v.containerName&#39;),<br>      state: [<br>        {<br>          attribute: &#39;count&#39;, <br>          value: component.get(&#39;v.count&#39;)<br>        }<br>      ]<br>    });<br>    init.fire();<br>  }<br>})</pre><p><strong><em>Child.cmp</em></strong></p><pre>&lt;aura:component&gt;<br>  &lt;aura:registerEvent name=&quot;addOne&quot; <br>                      type=&quot;c:FluxContainer_setState&quot;/&gt;<br>  &lt;aura:handler name=&quot;update&quot; <br>                event=&quot;e.c:FluxContainer_getState&quot; <br>                action=&quot;{! c.onUpdate }&quot;/&gt;<br>  &lt;aura:attribute name=&quot;count&quot; <br>                  type=&quot;Integer&quot;<br>                  default=&quot;0&quot;/&gt;</pre><pre>  &lt;button onclick=&quot;{! c.onButtonClick }&quot;&gt;<br>    You clicked me or my twin {! v.count } times.<br>  &lt;/button&gt;</pre><pre>&lt;/aura:component&gt;</pre><p><strong><em>Child.controller.js</em></strong></p><p>The onButtonClick function sends a new count (previous count plus one) up via the FluxContainer_setState event, which takes one parameter, “newState”, an object of just the updated items (if we had other stateful properties in the container, they would not be affected by this unless we explicitly added them).</p><pre>({<br>  onButtonClick : function (component, event, helper) {<br>    // dispatch the new count<br>    var update = component.getEvent(&#39;addOne&#39;);<br>    update.setParams({<br>      newState: {<br>        count: component.get(&#39;v.count&#39;) + 1<br>      }<br>    });<br>    update.fire();<br>  },<br><br>  onUpdate : function (component, event, helper) {<br>    var state = event.getParam(&#39;update&#39;).state;<br>    <br>    state.count &amp;&amp; component.set(&#39;v.count&#39;, state.count);<br>  }<br>})</pre><p>This child component explicitly handles getting state updates via onUpdate, but just like the FluxContainer base component, we could abstract that functionality to a base component which any child like this one could extend to automatically handle simple state updates. I wanted to exemplify how flexible this composition could be though; if your project is small enough, maybe you don’t need to abstract anything, and maybe the logic can remain in your immediate controller (and/or helper).</p><p>So the summary of things here goes like this: The top level container is initialized with a count of zero clicks. On initialization, it broadcasts that event application-wide through the getState event. The two child components subscribe to that event and update their own attributes then and any other time the getState event is fired with that attribute. When either of the children’s buttons are clicked, they dispatch the setState component event with a new count value. That value is received by the flux container, updated in its own attribute, then reposted application-wide with getState so that the other button (and technically the original button too) can have the latest value from state.</p><p>I hope that this example illuminates some of the possibilities with Lightning components and the flux pattern. The flexibility of the framework lends itself well to a multitude of possibilities, and it really comes down to what your project <em>needs</em> in order to succeed and be maintainable. Consider all the reasons for and against reducing state whenever you are setting each piece up. Likewise, consider all the reasons for why you set it up the way you do. If you want everything to be wireless, use events whenever you can. If your project is small, consider just directly chaining properties and actions through attributes. If you have a complex component nested somewhere inside the larger container component, consider making it a container too (this is where containerName would be useful, so different containers and children don’t get confused with updates from the wrong hierarchy).</p><p>Thanks for reading, and I hope to learn other ways people are using flux in Lightning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce975027bef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Chatbot with Amazon Lex, Loopback, and React]]></title>
            <link>https://medium.com/@jefferyshivers/create-a-chatbot-with-amazon-lex-loopback-and-react-5d034792b8d?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d034792b8d</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[loopback]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[amazon-lex]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 19:56:08 GMT</pubDate>
            <atom:updated>2018-02-01T19:33:50.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngCo5Wt87PjyYt6Iz3EUbw.png" /></figure><p>This article will go through the process of building a chatbot from scratch using Amazon Lex for language processing, Loopback for creating a REST API and serving up the front end, and React for building the front end. The aim of this example is to be as reduced as possible in terms of how much goes into each step in order to get a full stack bot framework up and running. Of course, you could reduce the process much further with different tools entirely, but I’ve chosen these because they will probably scale very well.</p><p>The following steps are subdivided into three basic parts, corresponding to those larger phases of the project.</p><h4>1. Amazon Lex</h4><p>To get started, you’ll need an AWS account. Once that is setup, navigate to <a href="https://console.aws.amazon.com/lex/home">Lex</a> and click “Create”. Select “Custom Bot”, and give it a name; I’m going to call this one “CatBot”. Choose the rest of the options on that page, and, at the bottom, “Create”.</p><p>You’ll be redirected to your new bot! Before you can test it out, you’ll need at least one intent. I created one called “Meow”. Add one or more utterances with phrases that should trigger this intent. For the Meow intent, I want to trigger it with the phrases “meow” or “prrr”, so those are my two utterances. For now, skip the Slots section[1]; expand the Confirmation Prompt, and fill in the fields with whatever you’d like the bot to say back to the client to confirm (or escape) the intent. I wrote “Oh, are you a cat?” for <strong>Confirm</strong> and “No problem, I must have misheard you.” for <strong>Cancel</strong>. “Save” at the bottom, and select “Build” at the top.</p><p>Once the build process completes, you can type one of the triggering utterances into the test prompt on the right, and you should get the confirmation message(s) you wrote in return. If you respond “yes” to the prompt, you’ll get a new message in return with something like “Intent Meow is ReadyForFulfillment:”. If you respond “no”, you’ll get the cancellation message like “No problem, I must have misheard you.”.</p><p>Click “Services” in the navigation bar at the top of the page, then “Users” from the left menu, then “Add User” at the top. Give this AWS user a name and Programmatic access. In the next step, select “Attach existing policies directly” and select “AmazonLexRunBotsOnly”. Create the user, then you’ll see a success message with the credentials for the new user. Take note of the Access Key ID and Secret Access Key, and we’ll need them when we connect our backend to Lex.</p><p>This is only the very tip of the iceberg with Lex, but in the interest of moving on to the next steps, click “Publish” and give it any alias you’d like (for simplicity you can just make it the same as the name).</p><p>[1] You’ll definitely want to start looking into slots, if nothing else. <a href="https://www.youtube.com/watch?v=5XfhTwVjwgQ&amp;list=PLGyRwGktEFqcgchajEArK5M2WeZ97efxp">Here is an awesome video tutorial series on using Lex</a>; it goes into slots and many other considerations that didn’t make it into this example.</p><h4>2. Loopback</h4><p>To use <a href="http://loopback.io/">Loopback</a>, a Node.js API Framework, you’ll first need to have <a href="https://nodejs.org/">Node</a> installed. Then install the Loopback CLI with npm (npm comes with Node by default):</p><pre>$ npm i -g loopback-cli</pre><p>Next, navigate in the console to a directory where you want to install your project, and go through the loopback setup procedure as follows:</p><pre>$ lb<br><strong>? What&#39;s the name of your application?</strong> catbot<br><strong>? Enter name of the directory to contain the project:</strong> catbot<br><strong>? Which version of LoopBack would you like to use?</strong> 3.x (current)<br><strong>? What kind of application do you have in mind?</strong> empty-server (An empty LoopBack API, without any configured models or datasources)</pre><p>Once Loopback finishes its part, it should prompt you to cd into the new project directory and create a model.</p><pre>$ cd catbot<br>$ lb model</pre><p>This brings up a prompt to configure a model; since we created an empty API, it didn’t come preconfigured with any datasources, so you’ll see a warning about this which you can just ignore.</p><pre>$ lb model<br><strong><em>Warning: Found no data sources to attach model. There will be no data-access methods available until datasources are attached.</em></strong><br><strong>? Enter the model name:</strong> utterance<br><strong>? Select model&#39;s base class</strong> Model<br><strong>? Expose utterance via the REST API?</strong> Yes<br><strong>? Custom plural form (used to build REST URL):</strong><br><strong>? Common model or server only?</strong> common<br><strong>Let&#39;s add some utterance properties now.</strong></pre><pre><strong>Enter an empty property name when done.</strong><br><strong>? Property name:</strong> message<br>   <strong>invoke   loopback:property</strong><br><strong>? Property type:</strong> string<br><strong>? Required?</strong> No<br><strong>? Default value[leave blank for none]:</strong></pre><pre><strong>Let&#39;s add another utterance property.<br>Enter an empty property name when done.</strong><br><strong>? Property name:</strong> sessionid<br>   <strong>invoke   loopback:property</strong><br><strong>? Property type:</strong> string<br><strong>? Required?</strong> No<br><strong>? Default value[leave blank for none]:</strong></pre><pre><strong>Let&#39;s add another utterance property.<br>Enter an empty property name when done.</strong><br><strong>? Property name:</strong> author<br>   <strong>invoke   loopback:property<br>? Property type:</strong> string<br><strong>? Required?</strong> No<br><strong>? Default value[leave blank for none]:</strong></pre><pre><strong>Let&#39;s add another utterance property.<br>Enter an empty property name when done.<br>? Property name:<br></strong>$</pre><p>We’ll come back to that model, but while you’re still at the command line do:</p><pre>$ mkdir client/dist &amp;&amp; touch client/dist/index.html</pre><p>That is going to be the entry point for our front end. Open your project in your preferred editor, and delete or comment everything out in server/boot/root.js. Then, in server/middleware.json, edit the “files” node to this:</p><pre>&quot;files&quot;: {<br>  &quot;loopback#static&quot;: {<br>    &quot;params&quot;: &quot;$!../client/dist&quot;<br>  }<br>},</pre><p>Now when we run node ., the root route at localhost:3000 will serve the contents of client/dist/index.html. You can put whatever you want in there for now to test it, but later we’ll set it up so that it’ll load our bundled React app.</p><p>When we created the Utterance model earlier, it generated two files in common/models. You can see or update the current schema for the model in the .json file; open utterance.js to add some custom methods to the model.</p><p>After doing npm i --save aws-sdk, update the file to look like this:</p><pre>&quot;use strict&quot;;</pre><pre>// use something like dotenv to load environment variables at<br>// runtime. otherwise you can hardcode the following variables<br>// for quick testing<br>const access_key_id = process.env.AWS_access_key_id;<br>const secret_access_key = process.env.AWS_secret_access_key;</pre><pre>const AWS = require(&quot;aws-sdk&quot;);<br>const awsRegion = &quot;us-east-1&quot;;</pre><pre>AWS.config.update({<br>  accessKeyId: access_key_id,<br>  secretAccessKey: secret_access_key,<br>  region: awsRegion<br>});</pre><pre>const lexruntime = new AWS.LexRuntime();<br>const crypto = require(&quot;crypto&quot;);</pre><pre>const params = {<br>  botAlias: &quot;CatBot&quot; /* required */,<br>  botName: &quot;CatBot&quot; /* required */<br>};</pre><pre>module.exports = Utterance =&gt; {<br>  // methods...<br>}</pre><p>Where you see “methods…” above, we’ll add some custom methods, which will be routed to specific endpoints to be used by our application.</p><p>When a chatbot is first loaded, we might want to greet the user with a welcome message. Create an instance method called <em>firstOpen</em>, which will accept one argument, a callback function.</p><pre>Utterance.firstOpen = cb =&gt; {<br>  // create a unique sessionid to keep track of the session<br>  let sessionid = crypto.randomBytes(20).toString(&quot;hex&quot;);</pre><pre>  let response = { message: &quot;Hi there. Say something a cat might say!&quot; }</pre><pre>  cb(null, sessionid, response)<br>};</pre><p>We generate a new sessionid in order to keep track of the session as the conversation progresses. We’ll send this back and forth with the client until they stop responding or begin a new session. The nice part about this id is that it doesn’t get associated with the user (or doesn’t have to be), so their sessions are entirely anonymous by default.</p><p>Next, connect that to a <em>remoteMethod</em> like so:</p><pre>Utterance.remoteMethod(&quot;firstOpen&quot;, {<br>  returns: [<br>    {<br>      arg: &quot;SessionKey&quot;,<br>      type: &quot;string&quot;<br>    },<br>    {<br>      arg: &quot;Response&quot;,<br>      type: &quot;string&quot;<br>    }<br>  ]<br>});</pre><p>Now we need another method that will accept an incoming message from the user, send that to Lex, and then send the response from Lex back to the user. Call this method “message”:</p><pre>Utterance.message = function (sessionkey, message, cb) {<br>  let req_params = Object.assign(params, {<br>    userId: sessionkey,<br>    inputText: message<br>  });</pre><pre>  lexruntime.postText(req_params, (err, data) =&gt; {<br>    cb(null, sessionkey, data);<br>  });<br>};</pre><p>I took out the error handling to condense that excerpt, but you should definitely refactor those into the methods in order to streamline any debugging processes later.</p><pre>Utterance.remoteMethod(&quot;message&quot;, {<br>  accepts: [<br>    {<br>      arg: &quot;SessionKey&quot;,<br>      type: &quot;string&quot;<br>    },<br>    {<br>      arg: &quot;Message&quot;,<br>      type: &quot;string&quot;<br>    }<br>  ],<br>  returns: [<br>    {<br>      arg: &quot;SessionKey&quot;,<br>      type: &quot;string&quot;<br>    },<br>    {<br>      arg: &quot;Response&quot;,<br>      type: &quot;string&quot;<br>    }<br>  ]<br>});</pre><p>You can try out the REST endpoints by going to localhost:3000/explorer. If the app is running already, restart it, then proceed with our changes now in place.</p><p>In the API explorer, expand “POST /utterances/firstOpen”, and click “Try it out!”. This should generate a Response Body a few sections below that with the “SessionKey” and “Response”. If you copy the SessionKey and paste it into the so-named parameter field at “POST /utterances/message”, along with a Message that matches one of the intent triggers we setup in Lex. The “Response” here should include some other attributes sent to us from Lex. Most importantly at the moment, the “message” should be our confirmation prompt for the intent we triggered; that intend name should appear in this object as well.</p><p>Everything you see in the Response here will be super useful later on, but for now this is enough to justify moving on to build a front end so that we can display / interact with this stuff in a nice user interface.</p><h4>3. React</h4><p>The front end can be done without React, but just for fun I’m going to use it anyway. Using it will allow us to create a component that can be inserted into any project without changing any of the existing code. If you haven’t read my article on creating a React app using Webpack and Express, that’ll explain how I setup some of this part of the project. The general summary is that you’ll need to create a webpack.config.js file in the root of your project directory that looks like <a href="https://github.com/jefferyshivers/catbot/blob/master/webpack.config.js">this</a>, and your React source code in client/src. <a href="https://webpack.js.org/">Webpack</a> will bundle everything into a generated file in client/dist.</p><pre>$ npm i --save-dev react react-dom webpack babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-2 style-loader css-loader sass-loader node-sass<br>$ touch webpack.config.js<br>$ mkdir client/src &amp;&amp; mkdir $_/styles &amp;&amp; mkdir $_/../containers<br>$ touch client/src/index.js &amp;&amp; touch client/src/styles/App.scss</pre><p>Write the following in client/src/index.js:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;</pre><pre>import &quot;./styles/App.scss&quot;;<br>import Bot from &quot;./containers/Bot&quot;;</pre><pre>ReactDOM.render(<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;Bot /&gt;<br>  &lt;/div&gt;,<br>  document.getElementById(&quot;root&quot;));</pre><p>And the styles you want to scope to the app in <a href="https://github.com/jefferyshivers/catbot/blob/master/client/src/styles/App.scss">client/src/styles/App.scss</a>.</p><p>Now let’s make our Bot component:</p><pre>$ touch client/src/containers/Bot.js &amp;&amp; touch client/src/styles/Bot.scss</pre><p>Here are the main goals we have going into this component:</p><ul><li>when the bot is first loaded, get the welcome message from our backend</li><li>have an input field where the user will type, and from which we’ll submit their messages to the bot</li><li>keep track of all the messages that have been sent or received</li><li>display all of the messages in the view, and update it automatically as the dialog progresses</li></ul><p>Start the component out with an initial state. <em>sessionkey</em> will hold the session key, <em>input</em> will hold the user’s message input, and <em>messages</em> will hold all of the messages from the conversation.</p><pre>import React, { Component } from &quot;react&quot;;</pre><pre>import &quot;../styles/Bot.scss&quot;;</pre><pre>class Bot extends Component {<br>  state = {<br>    sessionkey: null,<br>    input: &quot;&quot;,<br>    messages: []<br>  };</pre><pre>  componentDidMount = () =&gt; {<br>  }</pre><pre>  render() {<br>    return(<br>      &lt;div className=&quot;Bot&quot;&gt;&lt;/div&gt;<br>    )<br>  }<br>}</pre><p>Add some logic to <em>componentDidMount</em> to make a request to our backend when the Bot is mounted in the application.</p><pre>componentDidMount = () =&gt; {<br>  fetch(&#39;/api/utterances/firstOpen&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    }<br>  }).then(res =&gt; res.json())<br>    .then(body =&gt; {<br>      this.recordMessage(&#39;BOT&#39;, body.Response.message)<br>      this.setState({ sessionkey: body.SessionKey })<br>    })<br>}</pre><p>The block above factors out a function called <em>recordMessage</em> to persist our messages:</p><pre>recordMessage = (sender, message) =&gt; {<br>  this.setState({<br>    messages: this.state.messages.concat({<br>      SENDER: sender,<br>      MESSAGE: message<br>    })<br>  })<br>}</pre><p>Add a script to ./package.json to build what we have so far with Webpack and test it out:</p><pre>&quot;scripts&quot;: {<br>  ...<br>  &quot;build&quot;: &quot;./node_modules/.bin/webpack&quot;<br>},</pre><p>Now you can run npm run build to generate the bundled code into the client/dist directory. You can add the --watch flag to that command to have it automatically rebundle when changes are saved. Make client/dist/index.html so that it will load the generated bundle.js:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;lex + loopback bot demo&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;/&gt;<br>    &lt;script src=&quot;./bundle.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now when you go to localhost:3000, you should see nothing in the DOM yet. Open developer tools in Chrome and make sure the console is clear with no errors. If you have React Dev Tools installed, go to that tab and select the Bot component. On the right, you should be able to expand the State object and see that the initial message from the Bot was saved into state.</p><p>Back to the code, inside your <em>Render</em> method in the Bot component, add an input element.</p><pre>const input = (<br>  &lt;div className=&quot;input-container&quot;&gt;<br>    &lt;input<br>      value={this.state.input}<br>      onChange={this.changeInput}<br>      onKeyPress={this.handleKeyPress} /&gt;<br>  &lt;/div&gt;<br>);</pre><pre>return (<br>  &lt;div className=&quot;Bot&quot;&gt;<br>    {input}<br>  &lt;/div&gt;<br>);</pre><p>This element uses two new functions called <em>changeInput</em> (updates the state and inherently the DOM when the user changes the input text) and <em>handleKeyPress</em> which will trigger submission of the message upon hitting the Return key.</p><pre>changeInput = e =&gt; {<br>  let input = e.target.value;<br>  this.setState({ input: input });<br>};</pre><pre>handleKeyPress = e =&gt; {<br>  (e.key === &#39;Enter&#39;) &amp;&amp;<br>  (this.state.input !== &quot;&quot;) &amp;&amp;<br>  this.submitMessage();<br>}</pre><p>With the project rebundled, you should see this input field in the browser now. Before testing it out further, add the <em>submitMessage</em> function which is called above when the user submits a non-empty message, and a function to persist those messages in state:</p><pre>recordMessage = (sender, message) =&gt; {<br>  this.setState({<br>    messages: this.state.messages.concat({<br>      SENDER: sender,<br>      MESSAGE: message<br>    })<br>  })<br>}</pre><pre>submitMessage = () =&gt; {<br>  let message = this.state.input;<br>  this.setState({ input: &quot;&quot; })<br>  this.recordMessage(&#39;USER&#39;, message)</pre><pre>  fetch(&#39;/api/utterances/message&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify({<br>      Message: message,<br>      SessionKey: this.state.sessionkey<br>    })<br>  }).then(res =&gt; res.json())<br>    .then(body =&gt; {<br>      this.recordMessage(&#39;BOT&#39;, body.Response.message)<br>  })<br>}</pre><p>Now we should be fully communicating with Lex from our front end! Check the browser console again to make sure no errors are showing up (and it’s always a good idea to keep an eye on the backend as well). You should see an updated list of messages in State (if you’re using React Dev Tools) as you submit new ones. Make sure the MESSAGE and SENDER values are what you’d expect.</p><p>Add an element to show the messages in the DOM like so:</p><pre>const messages = (<br>  &lt;div className=&quot;messages&quot;&gt;<br>    &lt;div className=&quot;messages-inner&quot;&gt;<br>      {<br>        this.state.messages.map((message, index) =&gt; {<br>          return (<br>            &lt;div <br>              key={message.SENDER + index} <br>              className={`message ${message.SENDER}`}&gt;<br>              {message.MESSAGE}<br>            &lt;/div&gt;<br>          )<br>        })<br>      }<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>)</pre><pre>// const input = ...</pre><pre>return (<br>  &lt;div className=&quot;Bot&quot;&gt;<br>    {messages}<br>    {input}<br>  &lt;/div&gt;<br>);</pre><p>You can add some <a href="https://github.com/jefferyshivers/catbot/blob/master/client/src/styles/Bot.scss">styles</a><strong> </strong>to make the view a little less dry; I also added some functionality to scroll the chat to the bottom every time the conversation is updated, which you can see <a href="https://github.com/jefferyshivers/catbot/blob/master/client/src/containers/Bot.js">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*18QA_cQQcA1yzIs0ddl3Vw.png" /></figure><p>And that’s it!</p><h4>Conclusion</h4><p>Now your chatbot is alive and ready to grow / change with any new features you might come up with. Consider looking deeper into Lex to see how you can really expand the logic that goes into your chat conversations. You can think about persisting chats with Loopback (read about <a href="https://apidocs.strongloop.com/loopback/#persistedmodel">PersistedModels</a>, which you can connect to many different kinds of datasources). On the front end, maybe you’ll want to do something more interactive like have a certain response (or input) affect the DOM, or perhaps cache the conversation and session key so that the chat can be persisted locally on the client side and perhaps picked back up later.</p><p>I’d love to hear how else others might tackle parts of this project, and otherwise hope that this has been a helpful run-through for those who are just getting into some of these tools like myself.</p><p>If you want to clone the finished project (minus the stuff that happens in Lex), view my repository on Github <a href="https://github.com/jefferyshivers/catbot">here</a>, and please star it if you find it a useful resource!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d034792b8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting a Project With React, Express and Webpack]]></title>
            <link>https://medium.com/@jefferyshivers/starting-a-project-with-react-express-and-webpack-the-super-verbose-edition-8e98d17135d6?source=rss-4445984ee3ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e98d17135d6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jeffery Shivers]]></dc:creator>
            <pubDate>Wed, 03 Jan 2018 05:27:52 GMT</pubDate>
            <atom:updated>2018-03-05T14:58:20.078Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a good number of tutorials and boilerplate / template repositories out there for developers just getting started with React <em>or</em> Express <em>or</em> Webpack. Oftentimes, such projects tend to focus mostly on one particular aspect of the setup and less (or not at all) on the rest. This makes it hard to fit the pieces together sometimes, and especially challenging to become competent enough to start a full-stack project on your own without the assistance of several uncoordinated guides / documentations.</p><p>In an attempt to ease the process of learning some of the new tools I’m particularly interested in, I thought it might be useful to someone out there (including future me, to be honest) to put together a little tutorial on how I would setup a new React+Express+Webpack project. I’m going to be a little redundant sometimes in this one because I remember what it was like to be at a stage where most of this was way over my head, and I certainly would have appreciated having a guide like this to follow.</p><p>Without further ado, let’s jump right into it! To follow this tutorial, you’ll need to have <a href="https://nodejs.org/en/">Node</a> and <a href="https://www.npmjs.com/">npm</a> installed, and a command line interface and text editor open.</p><p>tl;dr A super simple and verbose guide to creating a web app using React, Express and Webpack.</p><h3>Project Structure</h3><p>Using the command line, create a new project directory and the necessary files and subdirectories we’ll need. Note that this is a relatively arbitrary setup; you can adapt the structure however you need to fit your project, but this is typically how I’d arrange things for a new or minimal app.</p><pre>mkdir myproject &amp;&amp; cd $_<br><br># the Express server file:<br>touch index.js<br><br># Webpack configuration:<br>touch webpack.config.js<br><br># React source directory and file<br>mkdir src &amp;&amp; touch src/index.js<br><br># Static files<br>mkdir dist &amp;&amp; touch dist/index.html</pre><p>We should have things setup now like so:</p><pre>.<br>├── dist<br>│   └── index.html<br>├── index.js<br>├── src<br>│   └── index.js<br>└── webpack.config.js</pre><p>We will eventually serve our project from the dist folder; src contains the React source code that Webpack will transpile (using <a href="https://babeljs.io/">Babel</a>) so that it can be loaded in index.html and understood by any modern browser.</p><h3>Setting Up React</h3><p>To create the React part of the project, first install react using npm:</p><pre>npm i -D react react-dom</pre><p>A more verbose version of the above would be:</p><pre>npm install --save-dev react react-dom</pre><p>I’ll use the previous abbreviations for the rest of the tutorial, but if this is your first experience using npm, I recommend reading the docs to learn about all the flags / options available.</p><p>We should now have a package.json file in our root directory with those two packages listed under <em>devDependencies</em>.</p><p>Next, code a simple React component in src/index.js:</p><pre>import React, { Component } from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br><br>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        Hello world.<br>      &lt;/div&gt;<br>    )<br>  }<br>}<br><br>ReactDOM.render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;));</pre><p>If you’re not already super comfortable with React and the rest of these tools, I recommend moving forward and not trying to extend any of the above code quite yet. Get everything up and running first, <em>then</em> go crazy. Always.</p><h3>Setting Up Webpack</h3><p>We are going to use the Babel transpiler to morph our React project into code that is browser-ready, so install a few packages for that:</p><pre>npm i -D babel-core babel-loader babel-preset-env babel-preset-react</pre><p>Note the inclusion of babel-preset-env and the exclusion of babel-preset-es2015 which most tutorials out there still use. The latter is now <a href="https://babeljs.io/docs/plugins/preset-env/">deprecated</a>.</p><p>We’ll use Webpack to actually coordinate the use of Babel here, so install it next:</p><pre>npm i -D webpack webpack-dev-server</pre><p>Next, configure Webpack in webpack.config.js:</p><pre>const path = require(&#39;path&#39;);</pre><pre>module.exports = {<br>  entry: &#39;./src/index.js&#39;,<br>  output: {<br>    filename: &#39;bundle.js&#39;,<br>    publicPath: &#39;/&#39;,<br>    path: path.resolve(__dirname, &#39;dist&#39;)<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.js$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;,<br>          options: {<br>            &quot;presets&quot; : [&quot;env&quot;, &quot;react&quot;]<br>          }<br>        }<br>      }<br>    ]<br>  }<br>};</pre><p>This is a minimal Webpack configuration, specifying an entry point for our source code, the output destination, and the packages we are running against code that matches the test patterns and their loaders and presets.</p><h3>Bundling the Project</h3><p>In the package.json file in the root of project directory, add scripts so that we can run webpack and webpack-dev-server:</p><pre>  // ...<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;,<br>    &quot;start-dev&quot;: &quot;./node_modules/.bin/webpack-dev-server --content-base dist/&quot;,<br>    &quot;build&quot;: &quot;./node_modules/.bin/webpack&quot;<br>  },<br>  // ...</pre><p>Now running npm run build should render dist/bundle.js. No need to open that new file; it’s rather big, and full of code that you and I will never need to really know about. The important thing is that we can now load this bundled code in our html (dist/index.html), and that can simply be set up like so:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;React Express Boilerplate&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;./bundle.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The empty div with the id of “root” will be replaced by our React component. That happens because of the last three lines in src/index.js. “Root” is of course an arbitrary name; you can use whatever name you’d like, and this is also a good moment to understand, if you’re new to React, that you can render more than one top-level component in a project. In other words, you could have another div with the id of “Root-2”, and copy the render method in the React code to render the same component (or perhaps another) into that element. We won’t do that here, but it’s good to keep in mind how flexible / extendable many of these tools really are at the end of the day!</p><h3>Setting Up Express</h3><p>Finally, install Express, which we’ll use to serve the project:</p><pre>npm i -S express webpack-dev-middleware</pre><p>And write the Express server in ./index.js:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const path = require(&#39;path&#39;);</pre><pre>const webpack = require(&#39;webpack&#39;);<br>const config = require(&#39;./webpack.config&#39;);<br>const compiler = webpack(config);</pre><pre>app.use(require(&#39;webpack-dev-middleware&#39;)(compiler, {<br>  publicPath: config.output.publicPath<br>}));</pre><pre>app.get(&#39;*&#39;, (req, res) =&gt; {<br>  res.sendFile(&#39;dist/index.html&#39;, { root: __dirname });<br>});</pre><pre>app.listen(3000);</pre><p>You can now serve your project with npm run start! Open localhost:3000 in a browser to view the project as is.</p><p>With the start-dev script that we wrote earlier, we use webpack-dev-server to hot-reload the project in the browser as assets are updated. To also automatically rebundle the project anytime a change is made to the React source code, add --watch to the build command (note: you&#39;ll need two tabs open to have this running in one while the Express server is running in another).</p><h3>Conclusion</h3><p>And that’s it! Or, that’s the beginning of it. There is so much more you can do with React, Express, Webpack and any other tools that might fit into your project. But hopefully this is a solid starting point, or at least a resource that you can cherrypick something relevant to factor into a different setup that you’re developing.</p><h4>P.S.</h4><p>I usually add another babel preset <a href="https://babeljs.io/docs/plugins/preset-stage-2/">babel-preset-stage-2</a> so that I can use class properties within my React components. You can use that or <a href="https://babeljs.io/docs/plugins/transform-class-properties/">babel-transform-class-properties</a> to handle this (npm install whichever, then add it to the Babel presets object in your Webpack config, like: &quot;presets”: [&quot;env&quot;, &quot;react&quot;, &quot;stage-2&quot;]).</p><h4>P.S.S.</h4><p>I’ve uploaded the result of this tutorial to a repository on Github <a href="https://github.com/jefferyshivers/React-Express-Boilerplate">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e98d17135d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>