<?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 Craig Cartmell on Medium]]></title>
        <description><![CDATA[Stories by Craig Cartmell on Medium]]></description>
        <link>https://medium.com/@craigcartmell?source=rss-fffe40b2d4d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c6SOVhJu7ElnlEMc.jpg</url>
            <title>Stories by Craig Cartmell on Medium</title>
            <link>https://medium.com/@craigcartmell?source=rss-fffe40b2d4d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:45:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@craigcartmell/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[Full Stack JavaScript and how I finally built an API I’m proud of]]></title>
            <link>https://medium.com/@craigcartmell/full-stack-javascript-and-how-i-finally-built-an-api-im-proud-of-53006ae152dc?source=rss-fffe40b2d4d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/53006ae152dc</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Craig Cartmell]]></dc:creator>
            <pubDate>Sun, 01 Jul 2018 14:19:21 GMT</pubDate>
            <atom:updated>2018-07-01T14:19:21.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part One</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZ9aPvQvx8CgZTMR" /><figcaption>Photo by <a href="https://unsplash.com/@arifrw?utm_source=medium&amp;utm_medium=referral">Arif Wahid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently started a greenfield (sorry not sorry for the recruiter speak) project where I was given the opportunity of choosing the technology from the ground up. Not too common as a contractor and something I was very excited about because I’m a massive nerd.</p><p>I thought I’d do a little write up on the approach we took, some of the tools we used and the general structure of our application.</p><h4>Give it a REST</h4><p>Building APIs is hard. Building APIs that remain consistent during growing project complexity and client demands is even harder.</p><p>How do you structure your endpoints? How do you deal with relationships (in APIs and real life for that matter)? How do you manage pagination? Do you allow sparse field sets? Is this the real life? Is this just fantasy?</p><p>The questions are endless.</p><p>Help arrived back in 2013 when <a href="http://jsonapi.org/">JSON API</a> spec was drafted (giving special thanks to <a href="https://www.emberjs.com/">Ember</a>). It provides opinionated (but not opinionated enough for my liking) definitions of things like how to format responses, what parameters to accept and when to return a 418 I’m a teapot.</p><p>As is often the case with well adopted approaches in the tech community, a nice ecosystem sprung up around it and gave us some tools to help us on our way. If you search for <a href="https://github.com/search?q=jsonapi">JSON API</a> on Github, you’ll find a gluttony of packages ranging from serialising/deserialising responses to generating documentation.</p><p>Back to it not being opinionated enough then. Creating and updating relationships must be done in multiple requests. If, for example, you wanted to create a batch of 3 users, you would have to send 3 separate HTTP POST requests to https://your-funky-website.com/api/users. Not particularly performant.</p><p>As you delve deeper and your needs become more complex, you’ll find many little niggles like this which require lots of thought and head scratching, and nobody wants that.</p><h4>Starting Afresh</h4><p>The only stipulation with the new application was the API had to be built in Node.JS, which was fine by me. JavaScript everything, I say. More about the benefits of a full stack JavaScript approach coming up below.</p><p>The project requires us to build an API which is predominately used to query and return results from <a href="https://www.elastic.co/products/elasticsearch">Elasticsearch</a>. The API is then consumed by a web application built in React.</p><p>Below, I’m going to run down the approach we took and some extremely helpful tools we found along the way.</p><h4>Taking a Monorepo approach</h4><p>Granted, I’m a bit late to the party when it comes to <a href="https://medium.com/@maoberlehner/monorepos-in-the-wild-33c6eb246cb9">Monorepos</a> but for this project it made perfect sense. We essentially have three JavaScript “packages”. An api, a web and a shared package, which are all pretty self-explanatory.</p><p>The shared package contains shared logic, methods, constants and flow types (more about that later) which can be used by the api and web.</p><p>Here’s how the structure looks at the root of the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*ueow8yMOSPTtPVkD1z_PRQ.png" /></figure><p>We use <a href="https://yarnpkg.com/lang/en/docs/workspaces/">Yarn Workspaces</a> to manage this monstrosity, with the beauty being any changes made in the shared/src directory are immediately reflected in api and web. No more pushing changes up to a private git repository and then pulling them back down.</p><p>All you need to do is add the shared package as a dependency in your api and web packages.</p><p>Here’s how our ./shared/package.json looks:</p><pre>{  <br>  &quot;name&quot;: &quot;our-app-shared&quot;, <br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;src/index.js&quot;,<br>  ...<br>}</pre><p>And here’s our ./api/package.json and ./web/package.json files:</p><pre>&quot;dependencies&quot;: {<br>  &quot;our-app-shared&quot;: &quot;1.0.0&quot;,<br>...<br>}</pre><p>Finally, here’s our root ./package.json file:</p><pre>{ <br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: {<br>    &quot;packages&quot;: [&quot;web&quot;, &quot;api&quot;, &quot;shared&quot;]<br>  },<br>  ...<br>}</pre><p>Now simply running yarn in the root of the application will install dependencies in all 3 packages.</p><p>We then import the shared module in our api and web packages like so:</p><pre>import {someSharedMethod, constants} from &#39;our-app-shared&#39;</pre><p>Neato.</p><h4>Apollo GraphQL</h4><p>Now if you’ve read this far and you haven’t already at least heard about or played around with <a href="https://www.apollographql.com/">Apollo</a>, you absolutely should. Since seeing the light a year or so ago, I can definitively say I’ll never build another RESTful API again, and nor should you if you have the choice.</p><p>Apollo is split up into three main products. It has a client, server and engine.</p><p><a href="https://www.apollographql.com/client">Apollo Client</a> is a great way to build GraphQL applications and provides libraries for many modern JS frameworks such as React and Vue. It can also be used with Vanilla JS if that’s your bag. It comes with out-of-the box, zero config caching as well as many other cool features, one of my favourites being the <a href="https://www.apollographql.com/docs/react/essentials/queries.html#basic">Query Component</a>.</p><p>Forget creating masses of repetitive boilerplate with Redux, just create a query component and have it handle fetching, caching, loading and error states.</p><p><a href="https://www.apollographql.com/server/">Apollo Server</a> is used to create abstractions over your data layers. You can build a single API which connects to multiple backend data sources, be it a PostgreSQL database, Elasticsearch or something else.</p><p>If you want to add even more abstraction like we’ve done, you can use the <a href="https://github.com/apollographql/graphql-tools/blob/master/designs/connectors.md">Model/Connectors</a> approach.</p><p>Again, Apollo provide a set of libraries to hook it up to any popular Node.js framework such as <a href="https://expressjs.com/">Express</a> or <a href="https://koajs.com/">Koa</a>.</p><h4>Modularising our schema</h4><p>In Apollo GraphQL, you build a schema which defines a set of queries followed by matching resolvers which are used to actually execute the queries.</p><p>I was quite naive when I built my first app in Apollo GraphQL and so ended up with a single schema file and a single resolver. Both files spanned many, many lines which can quickly get out of control.</p><p>Helpfully there are tools for dealing with this such as the creatively named <a href="https://github.com/okgrow/merge-graphql-schemas">Merge GraphQL Schemas</a>. This allows us to split up our type and resolver files and then stitch them back together when we generate the schema.</p><h4>Documentation is king</h4><p>It’s all well and good building a nice API but a user needs to know how to consume it. They need to know what queries they can send, what parameters are accepted and what the response will look like.</p><p>Step up, <a href="https://github.com/2fd/graphdoc">GraphDoc</a>. It generates a beautiful static website from your GraphQL schemas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu6r1jqVyDfWgE-EoCLl9A.png" /><figcaption>Github.com GraphQL Schema</figcaption></figure><p>You can generate the output manually by executing the graphdoc client and passing the required params or if you want to be even more efficient, you can setup an npm script to automatically regenerate the docs when the schema changes, assuming you’re using something like <a href="https://github.com/remy/nodemon">Nodemon</a> to watch for file changes and restart your server.</p><p>./api/package.json</p><pre>{  <br>  &quot;scripts&quot;: {   <br>    &quot;doc&quot;: &quot;./node_modules/babel-cli/bin/babel-node.js ./scripts/doc.js&quot;<br>}</pre><p>./api/scripts/doc.json</p><pre><br>import childProcess from &#39;child_process&#39;<br>import env from &#39;../src/lib/env&#39;<br><br>const { PORT, GRAPHQL_ENDPOINT } = env()<br>const { exec } = childProcess<br>const url = `http://localhost:${PORT}${GRAPHQL_ENDPOINT}`<br><br>exec(<br>  `./node_modules/.bin/graphdoc -e ${url} -o ./public/doc/schema --force`,<br>  (error, stdout, stderr) =&gt; {<br>    // eslint-disable-next-line no-console<br>    console.log(stdout)<br>    // eslint-disable-next-line no-console<br>    console.log(stderr)<br>    if (error !== null) {<br>      // eslint-disable-next-line no-console<br>      console.log(`exec error: ${error}`)<br>    }<br>  },<br>)</pre><p>./api/src/index.js</p><pre>// @flow<br><br>import childProcess from &#39;child_process&#39;<br>import Koa from &#39;koa&#39;<br>import KoaRouter from &#39;koa-router&#39;<br>import koaBody from &#39;koa-bodyparser&#39;<br>import { graphqlKoa, graphiqlKoa } from &#39;apollo-server-koa&#39;<br>import serve from &#39;koa-static&#39;<br>import cors from &#39;@koa/cors&#39;<br>import helmet from &#39;koa-helmet&#39;<br>import env from &#39;./lib/env&#39;<br>import schema from &#39;./graphql/schema&#39;<br>import connectors from &#39;./graphql/connectors&#39;<br><br>const app = new Koa()<br>const router = new KoaRouter()<br><br>// koaBody is needed just for POST.<br>app.use(koaBody())<br>app.use(cors())<br>app.use(helmet())<br><br>// Serve all static files from the public directory, such as GraphQL docs<br>app.use(serve(`${__dirname}/../public`))<br><br>const {<br>  PORT = 8080, GRAPHQL_ENDPOINT = &#39;/graphql&#39;, GRAPHIQL_ENDPOINT = &#39;/graphiql&#39;, GRAPHIQL_ENABLED,<br>} = env()<br><br>const graphqlOptions = {<br>  schema,<br>  context: {<br>    connectors,<br>  },<br>}<br><br>router.post(GRAPHQL_ENDPOINT, graphqlKoa(graphqlOptions))<br>router.get(GRAPHQL_ENDPOINT, graphqlKoa(graphqlOptions))<br><br>if (GRAPHIQL_ENABLED) {<br>  router.get(<br>    GRAPHIQL_ENDPOINT,<br>    graphiqlKoa({ endpointURL: GRAPHQL_ENDPOINT }),<br>  )<br>}<br><br>app.use(router.routes())<br>app.use(router.allowedMethods())<br><br>app.listen(PORT, () =&gt; {<br> console.log(`localhost:${String(PORT)}${String(GRAPHQL_ENDPOINT)}`)<br> console.log(`localhost:${String(PORT)}${String(GRAPHIQL_ENDPOINT)})<br> console.log(&#39;Regenerating API docs.&#39;)<br><br>  childProcess.exec(<br>    &#39;yarn doc&#39;,<br>    (error, stdout, stderr) =&gt; {<br>      console.log(stdout)<br>      console.log(stderr)<br>      if (error !== null) {<br>        console.log(`exec error: ${error}`)<br>      }<br>    },<br>  )<br>})</pre><h4>Go with the flow</h4><p>I still have a bit of a love/hate relationship with <a href="https://flow.org/en/">Flow</a>. I love it for things we’ll get into shortly, but I really dislike the error output. It feels horribly unintuitive. You have to spend a few minutes dissecting what the actual error is telling you before even getting to the code.</p><p>Anyway, Flow really shines when building both the client and api in JavaScript. We’re currently building out the API alongside our web application in short sprints and it’s incredibly useful to be able to map out the data structures before actually implementing them.</p><p>Imagine the front-end developers working on your web app want to know exactly what properties a user model has but you’re yet to implement it. You can quickly create the flow type in your shared module and bingo, now they know. If the structure changes as is often the case, the flow check command will fail.</p><p>It reduces the bottleneck between backend and frontend and avoids a horrible integration piece at the end.</p><p>A little word of warning. You may get some strange behaviour when using Flow with Yarn Workspaces because of the use of symlinks. There’s a nice package called <a href="https://github.com/ImmoweltGroup/flow-mono-cli">Flow Mono Cli</a> which can help with this.</p><h4>TL;DR</h4><ul><li>Don’t be scared of monorepos</li><li>Use GraphQL over REST</li><li>Modularise your schema</li><li>Use a tool to auto-generate your API docs</li><li>Use Flow (or go the whole hog and use TypeScript) for type checking</li></ul><h4>Some other useful tools</h4><p>Here’s a “best of the rest” list of tools we found whilst building our application.</p><p><a href="https://github.com/json-schema-faker/json-schema-faker">json-schema-faker/json-schema-faker</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53006ae152dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex React Apps and the Many Pitfalls — Part 1 of Infinity]]></title>
            <link>https://medium.com/@craigcartmell/complex-react-apps-and-the-many-pitfalls-part-1-of-infinity-fab2b2ccba57?source=rss-fffe40b2d4d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab2b2ccba57</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Craig Cartmell]]></dc:creator>
            <pubDate>Tue, 24 Jan 2017 07:30:27 GMT</pubDate>
            <atom:updated>2017-01-25T07:19:39.321Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago I was tasked with creating a Content Management System for an Out Of Home advertising startup. I’d built a handful of Single Page Apps using React and other tools before but nothing of this magnitude.</p><h3>Mistakes were made</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2F1n2Zu66.mp4&amp;src_secure=1&amp;url=https%3A%2F%2Fi.imgur.com%2F1n2Zu66.gifv&amp;image=https%3A%2F%2Fi.imgur.com%2F1n2Zu66h.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=video%2Fmp4&amp;schema=imgur" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ea23fe0e576ff8419af24539b88bba2/href">https://medium.com/media/6ea23fe0e576ff8419af24539b88bba2/href</a></iframe><p>You know when you look at a piece of code you’ve written a few months ago and wonder if you were slightly pissed at the time or maybe sleep-coding? I get that a lot when looking back at this app.</p><p>Part of it was to do with the steep learning curve of the tool stack I’d chosen and part of it was down to time constraints, something every developer can sympathise with (please).</p><p>Below are some tips to avoid these clangers. They’re in order of importance in case you get bored half way through reading.</p><h3>Use Cancellable Requests</h3><p>Imagine your user is on a super slow internet connection, like any Internet Service Provider in London.</p><p>They’ve clicked on something and the request gets fired off in the background. The request is still going, still going, still going. Now eventually they get pissed off and click the back button or another action.</p><p><strong>The original request is still going </strong>and<strong> </strong>eventually it’s going to come back with a response.</p><p>So while your user is blissfully unaware doing something else in the application, the request comes back, the state gets changed and causes a re-render. Maybe it causes a side-drawer to open because the component now has some data. Maybe it redirects them to another page when they no longer want to perform that action. There could be a mountain of side-effects.</p><p><strong>Cancellable Requests to the rescue</strong>.</p><p>Although official support for Cancellable Promises has now been <a href="https://github.com/tc39/proposal-cancelable-promises">withdrawn</a>, many request libraries, such as <a href="https://github.com/mzabriskie/axios">Axios</a>, provide the feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-i3bxbtJzoCHcilrIIEDQ.png" /><figcaption><a href="https://github.com/mzabriskie/axios">https://github.com/mzabriskie/axios</a></figcaption></figure><p>If you’re using Redux like myself, I’d recommend <a href="https://redux-saga.github.io/redux-saga/">Redux Saga</a> to deal with data fetching. It provides a framework for managing concurrent requests using <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*">Generator Functions</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBlzHee_M-gY_hE4OFoD8A.png" /><figcaption><a href="https://redux-saga.github.io/redux-saga/">https://redux-saga.github.io/redux-saga/</a></figcaption></figure><p>Nifty ay?</p><p>It does mean you’ll have to brush up on Generator Functions but it’s knowledge well worth knowing.</p><h3>Componentise EVERYTHING</h3><p>Is Componentise even a word? My browser is telling me not, but I’m sticking with it.</p><p>My current project involves creating a stripped back version of the main app for a smaller user group. A lite version, if you like.</p><p>The first thing I did was look at how to re-use as much of the main application as possible. Easy, I thought. I’ll just take the header component and drop it into my new lite parent component and add some props to hide the search and drop-down menus. Done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZQvibpC39QY9CSlRTbcEA.png" /></figure><p>I’ll do the same with the side navigation and pass in a prop to hide the links. Simple.</p><p>Unfortunately not every component is as easy to drop-in as this. What I hadn’t planned for are the container components. A container component (or “Smart” component) is something which knows of and manages state. The alternative is a “dumb” component which works solely off the props passed in like a simple button, for example.</p><p>So imagine you’ve got this lovely grid container component which renders an array of items as twitter style cards. Now the way I’d built it was tied to the state of the main app. So when the component mounted, it went away and fetched the data from an API and rendered the response.</p><p>But what if I want to re-use the presentational side of the component but I want to pass in my own data? Time for a big refactor.</p><p>I’ve made that mistake a lot.</p><p>My advice would be to think ahead when building these monolithic containers. Is there a small chance this bit could be re-used elsewhere? If yes, simply extract it out into it’s own presentational component.</p><h3>Just use a Boilerplate</h3><p>I’m trademarking that.</p><p>Don’t try to re-invent the wheel. Don’t spend hours/days/weeks bundling together your build tools. Just pick one of the many already available based on your needs.</p><p>A simple “React Boilerplate” google will return hundreds of results. Check out a few on Github, see if one fits your needs and see how many people are using it. Don’t forget to check out the <strong>Issues</strong> tab. Always check out the Issues tab. That advice goes for any library you’re thinking of using.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab2b2ccba57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>