<?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 Alex Pelletier on Medium]]></title>
        <description><![CDATA[Stories by Alex Pelletier on Medium]]></description>
        <link>https://medium.com/@alex.pelletier_73051?source=rss-3b473537523f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jQmZ1DCONs1C0u3d</url>
            <title>Stories by Alex Pelletier on Medium</title>
            <link>https://medium.com/@alex.pelletier_73051?source=rss-3b473537523f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:43:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex.pelletier_73051/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[Creating A Generic List For Complex Collection Views]]></title>
            <link>https://medium.com/building-ibotta/creating-a-generic-list-for-complex-collection-views-fde932e8be92?source=rss-3b473537523f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde932e8be92</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[Alex Pelletier]]></dc:creator>
            <pubDate>Mon, 18 May 2020 18:43:45 GMT</pubDate>
            <atom:updated>2020-05-18T18:43:45.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89dkRnoTSC0p8ux9w7j_6g.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@camille-staehler-1205367">Camille Staehler</a> on <a href="https://www.pexels.com/">Pexels.com</a></figcaption></figure><p>UITableViews and UICollectionViews are great for showing reusable scrolling content, but their delegate based IndexPath api can make them hard to deal with for more complicated screens. You end up spreading presentation logic for a single section across a number of functions making it hard to get a clear picture of how a section will behave by just look at the code. Ideally all logic for a section would live together, and for bonus points we could not have to deal with IndexPath s.</p><p>At ibotta we have large collection views with a lot of different types of cells / sections. On top of the rendering complexity that brings we also needed to support skeleton load and incremental loading. To accommodate these requirements while keeping our code clean, we created a new generalized List that could be configured and used on all of our screens.</p><p>Along with showing the right content we also need to correctly handle cell selection, cell updates (diffing), impression tracking, and prefetching. As the number of sections in a collection view grows, it becomes clear that a new layer (or two) of abstraction is needed to handle all of this complexity.</p><blockquote>⚠️ This article assumes you are comfortable with Swift and generics.</blockquote><h3>Composable Sections</h3><p>We are going to think of a collection view as a number of small autonomous sections. We might have a section for a header, and then a horizontal section for retailers, and then a section representing a grid of offers. We will represent each of these sections as a SectionPresenter, but because we want to use this on a number of screens we will keep our SectionPresenter s abstract and configurable; handling things like index paths under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tO9JiL7c7hIRZVebC_1pHA.png" /></figure><p>SectionPresenters are going to be generic classes that hold all of the logic needed to render cells and handle actions, but they will be independent of their data source. We are going to employ an MVVM-like architecture where a larger Properties struct is passed to a SectionPresenter and converted to a single cell&#39;s ViewProperties; SectionPresenter will be generic over the Properties and ViewProperties. To keep tracking of the loading state of our data we will use a LoadableProperty enum. All together this will look something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a46f53f55e5d47cdcf119615f22806c/href">https://medium.com/media/1a46f53f55e5d47cdcf119615f22806c/href</a></iframe><p>Notice how SectionPresenter encapsulates the lookup logic to convert Properties to each section&#39;s appropriate ViewProperties. Because ViewProperties are a loadable array we can infer a lot of information about loading state, and use the array indexes as collection view indexes. This separation of section logic from our live data is key. We can use our SectionPresenter like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80141060b753e090e6d0b4b1b67c758f/href">https://medium.com/media/80141060b753e090e6d0b4b1b67c758f/href</a></iframe><p>Now that we have this configurable foundation in place we can start to build out SectionPresenter. We can add simple rendering methods like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1639a390621318013da1a24dc9c0f984/href">https://medium.com/media/1639a390621318013da1a24dc9c0f984/href</a></iframe><p>We’ve just given our SectionPresenter several closures that can be configured by consumers. We will use this same pattern to add all functionality to our SectionPresenter. Notice how some things like cell count are automatically handled, and the logic to show the loading cell or the data cell is consolidated to one class that will be reused everywhere. We will go over cell reuse later in this article. We can create and configure our a SectionPresenter like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f138a424cf952205980f28c0ac73641/href">https://medium.com/media/9f138a424cf952205980f28c0ac73641/href</a></iframe><p>We would like to represent collection view sections with SectionPresenters, but because each section presenter will have different generic types for Property a type erasure is needed. To do this we will need to put SectionPresenter&lt;Properties, Property&gt; behind a protocol and create an AnySectionPresenter&lt;Properties&gt; class. There are a lot of ways to create type erasures in swift; we are going to use a simple closure based erasure. John Sundell has a great <a href="https://www.swiftbysundell.com/articles/different-flavors-of-type-erasure-in-swift/">article</a> on type erasures if you want to learn more. This can be done pretty easily like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36e7060249e7eaac05e4455525ba2a3d/href">https://medium.com/media/36e7060249e7eaac05e4455525ba2a3d/href</a></iframe><p>Now we can represent all of our sections as [AnySectionPresenter&lt;Properties&gt;]. Each SectionPresenter can be generic over a specialized subset of properties, but we only need to worry about the larger Properties struct in our List.</p><h3>List</h3><p>We now have an array of sections, but we still need to build out the logic to render content. This becomes relatively straightforward; we are going to treat each SectionPresenter as a single section in our collection view. We are going to use a UICollectionView as the underlying mechanism to show our content. Apple has done a lot of the heavy lifting with UICollectionView and there is no need to reinvent the wheel. However our List api will be mostly UICollectionView agnostic, so switching to a new underlying view type (or even swiftUI) would be simple enough.</p><p>To get started our List class will need to maintain an array of AnySectionPresenter and the current state of Properties. Any time properties or sections change we will want to update our List.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e3313b714612e5f8f45aeceaed77cfc/href">https://medium.com/media/5e3313b714612e5f8f45aeceaed77cfc/href</a></iframe><p>Notice how List is generic over Properties, this will allow everything to work in a nice type safe manner without any dangerous implicitly unwrapped optionals.</p><p>Now we only need to write general rendering code in List because all the complex use case specific logic lives inside our SectionPresenter s. We can enable cell rendering like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6da66d5363a5a69ca72029b56e3a44d4/href">https://medium.com/media/6da66d5363a5a69ca72029b56e3a44d4/href</a></iframe><p>Because we’ve separated out rendering logic from live data while still keeping everything generic our cell rendering methods get type safe ViewProperties. We&#39;ve also consolidated the IndexPath logic to our List and SectionPresenter in a way that no public consumers will have to know about it. And we&#39;ve enabled complexities like incremental loading with minimal effort by treating each section as an autonomous unit.</p><p>The final usage of our List will now looks something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/093a02e8a763c079bbcfedc24ef6dc09/href">https://medium.com/media/093a02e8a763c079bbcfedc24ef6dc09/href</a></iframe><h3>Cell Reuse</h3><p>For UICollectionViews to work properly we have to register reusable cells, and then dequeue cells by identifier. To do this we are going to create a new AnyCellProvider class to allow type safe cell registration and rendering from view properties. This will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/972e6abfd8d1874d1d7f5367f35520d2/href">https://medium.com/media/972e6abfd8d1874d1d7f5367f35520d2/href</a></iframe><p>You can see the initializer takes a cell type and a render method, then it builds closures to be consumed by the SectionPresenter. This has the effect of type erasing the cell type. The render method can be used by public consumers to decorate and configure the cell. The Property of our AnyCellProvider will match the Property of our SectionPresenter allowing cells to be creating and rendered using type safe properties.</p><p>We can now adjust our SectionPresenter&#39;s configurable cell closures to use an AnyCellProvider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea84d45eed27520e0f6b2690a43bdc2/href">https://medium.com/media/bea84d45eed27520e0f6b2690a43bdc2/href</a></iframe><p>We also need to adjust our AnySectionPresenter to use the new signatures for cell and loadingCell, but that should be straight forward so we aren&#39;t going to get into it.</p><p>Using a SectionPresenter with an AnyCellProvider looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10de35190399fec00ea971ad4f840adc/href">https://medium.com/media/10de35190399fec00ea971ad4f840adc/href</a></iframe><p>Because SectionPresenter.cell is expecting a variable of type AnyCellProvider&lt;Property&gt;, xcode is able to infer the Property type for AnyCellProvider. While this example only supports sections with a single cell type, we could expand our AnyCellProvider implementation to handle multiple cell types per SectionPresenter. This rendering pattern provides a clean and extensible interface for complex rendering requirements.</p><h3>Conclusion</h3><p>So far we’ve created a simple List class that can be used to show lots of heterogeneous content, but this is only the beginning of what can be done with this pattern. We can add all sorts of additional functionality to our SectionPresenter and List like: selection callbacks, prefetch logic, impression tracking, and smarter updating using item level diffing.</p><p>As an added bonus all of the functions inside a SectionPresenter should be pure functions, so you can easily test a SectionPresenter&#39;s presentation logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde932e8be92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/creating-a-generic-list-for-complex-collection-views-fde932e8be92">Creating A Generic List For Complex Collection Views</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic GraphQL Query Generation In Swift]]></title>
            <link>https://medium.com/building-ibotta/dynamic-graphql-query-generation-in-swift-4782ebdab991?source=rss-3b473537523f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4782ebdab991</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Alex Pelletier]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 19:09:46 GMT</pubDate>
            <atom:updated>2020-03-20T19:09:46.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfeiQL6RcAlQ5MpnAJA3Vg.png" /></figure><p>This article is going to assume you are familiar with <a href="https://graphql.org/">GraphQL</a>.</p><p>Historically it has been best practice to use static GraphQL queries using either .graphql files or in-code string literals. One of the most popular mobile GraphQL clients, Apollo, uses static GraphQL files to generate models. We used Apollo in this manner for a year, but ran into performance issues with decoding speed and cache read speed. At Ibotta we&#39;ve recently fully migrated from Apollo to a custom GraphQL framework where we generate queries based on data models. We are now able to performantly (&lt; 10ms) generate queries while supporting partial cache hits.</p><p>To move away from generated models we will need to declare our own Decodable structs to decode the returned JSON. But it would be hard to keep custom Decodable structs in sync with our static GraphQL queries. In GraphQL we have to ask for every field we want returned, so what if we use our response structs as the source of truth to generate queries? Doing this creates a sort of declarative GraphQL interface. Consider if we could do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ecb7989aab03c34e3838c2317aa3b5a/href">https://medium.com/media/3ecb7989aab03c34e3838c2317aa3b5a/href</a></iframe><p>And convert Query.self to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/391428415b06e3d49e7b996b5b2e2d5b/href">https://medium.com/media/391428415b06e3d49e7b996b5b2e2d5b/href</a></iframe><p>This strategy creates a single source of truth for queries in code, and keeps the queries close to the code that uses it.</p><h3>Implementation</h3><p>This article is going to go over a simple implementation to generate GraphQL queries from struct. We aren’t going to get into every nuance, but the underlying code will be open sourced soon if you want to really dig in. The implementation is going to get fairly intense so feel free to pause here, and grab a fresh cup of ☕️.</p><h3>Query Generation</h3><p>We don’t want to use reflection to generate query from our models; one of the main reasons is we want to deliberately decouple our coding keys from our model property names. Another reason is that by not using reflection we can enable much more complex operations of our models.</p><p>So how do we go from a struct to a query? We are first going to map our query model into a tree and use that tree structure to generate a query. This is easier said than done. The underlying concept that is going to power this is creating injectable decoders. Generally when working with Decodable models we use the standard JSONDecoder, but there is no reason we couldn&#39;t use a custom decoder. We are going to use a custom decoder to create a dummy model and keep track of what fields are requested.</p><p>In order to do this, we are going to create a new Decodable protocol called DataDecodable. We could use the standard Decodable protocol, but GraphQL has some special requirements that we are going to want to support as first class citizens. This protocol is super simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db846231e92ef04578cbc5e26d04b96e/href">https://medium.com/media/db846231e92ef04578cbc5e26d04b96e/href</a></iframe><p>If you look closely you can see we also defined a custom decoder called DynamicDecoder. This will be the base class we use to subclass all of our decoders. We opted to subclass our decoders over a decoder protocol because working with a generic protocol requires extra overhead (think associated type requirement issues). The DynamicDecoder will be generic over CodingKeys; very similar to the standard lib&#39;s Decoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afeda92b36e6b9f96323b905f2ed730e/href">https://medium.com/media/afeda92b36e6b9f96323b905f2ed730e/href</a></iframe><p>Our decoder has only three simple methods, this is all that is needed to decode almost any GraphQL payload. All primitives can use the .from(:ofType:) decoding method, but the type must conform to EmptyInitializable. This will allow us to create a dummy model while creating an object map. Each of these three decoding methods has an ofType parameter used to specify the expected return type, but generally type T can be inferred.</p><p>The syntax for DataDecodable models ends up being very similar to the standard library&#39;s Decodable. We can create a DataDecodable struct like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f5d38268a260efbd2412b1e25647c7/href">https://medium.com/media/79f5d38268a260efbd2412b1e25647c7/href</a></iframe><p>To keep a global list of available GraphQL fields we can define a protocol for each GraphQL type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d926a6dba054570756cfeb95dc094ec8/href">https://medium.com/media/d926a6dba054570756cfeb95dc094ec8/href</a></iframe><h3>Query Representation as a Tree</h3><p>We want to convert our DataDecodables to an intermediate tree, and then convert that tree to a query. But what should that tree structure look like? We will want to maintain certain information like field name, children, and type. Type should be represented in a way that GraphQL types can also be converted to. Lets start with a tree structure like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9026296c8a4b7ac6d99ac1c38a868d69/href">https://medium.com/media/9026296c8a4b7ac6d99ac1c38a868d69/href</a></iframe><p>Using an indirect enum for ObjectType allows us to represent [User] as .list(.object(&quot;User&quot;)). We don&#39;t need this granularity of type information to generate our queries, but while debugging we might want to validate the query against the schema. At Ibotta we validate all queries against the schema while debugging. This helps us be confident we are shipping accurate queries that won&#39;t break.</p><p>With this object map approach the above Query would be represented as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed37a90b0af32a413e7bff907732b68/href">https://medium.com/media/6ed37a90b0af32a413e7bff907732b68/href</a></iframe><p>But we still need some way to actually generating these ObjectMap s that can then be turned into queries.</p><h3>MappingDecoder</h3><p>We are going to create a new DynamicDecoder called a MappingDecoder that is going to create a dummy struct, and map the fields that are requested. Each time a field is requested we are going to append that field to a children array, and if an object is requested we are going to recursivly map all children of that object. Because all primitives need to conform to EmptyInitializable we can create and decode a dummy struct while mapping. This can be done like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6fc4fff03fca7f1cc82273568dacb5e/href">https://medium.com/media/d6fc4fff03fca7f1cc82273568dacb5e/href</a></iframe><p>Notice how child objects are recursively mapped to create a full ObjectMap of the entire struct. This is just one example of the powerful and extensible interface into our models DynamicDecoders + DataDecodables provided.</p><p>Because Query is a DataDecodable we can generate an full object map like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c0e4fe56715fedc0fecda4003c7194/href">https://medium.com/media/b0c0e4fe56715fedc0fecda4003c7194/href</a></iframe><p>Just like that we have converted our strongly typed struct into a tree without reflection. Now that our query is in an easy to use format we can work on generating a query.</p><h3>Query Generation</h3><p>We are now going to convert our users ObjectMap to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf549e6fb969c72a1bac874dc8ae8c16/href">https://medium.com/media/cf549e6fb969c72a1bac874dc8ae8c16/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d34b69b9c708e27c6a40b10844069aef/href">https://medium.com/media/d34b69b9c708e27c6a40b10844069aef/href</a></iframe><p>To keep things performant the query generation will directly convert an ObjectMap into a string query.</p><p>We are going to need a helper function to recursively convert an ObjectMap to a query string. This helper function will build the query from the bottom up, as a depth first search. This will allow us to merge like fragments and reduce upload size. To know if we can use a previously seen fragment we will compare fragment bodies and fragment types.</p><p>As we convert an ObjectMap to a query, and if the ObjectMap represents a primitive, we will return the field name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dc66b09658637659b669c9623a4fcba/href">https://medium.com/media/6dc66b09658637659b669c9623a4fcba/href</a></iframe><p>Now all that is left to generate our query is finishing building out the query(from:) method. We will need to merge all of our fragments into the string query. A GraphQL fragment has a format of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca60740916a04b6233c9a27b687c57cd/href">https://medium.com/media/ca60740916a04b6233c9a27b687c57cd/href</a></iframe><p>Our Fragment struct has each of these three fields so we can just map our fragments to a string and then join them. We can adjust our query(from:) like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cc00210c1ed15f5162e7ffd5765ede5/href">https://medium.com/media/0cc00210c1ed15f5162e7ffd5765ede5/href</a></iframe><p>Just like that we’ve converted our query struct to a tree and then to a GraphQL query. All of this is done in two passes, making the whole generation a linear time operation. We can now use our QueryBuilder like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3515bf3c15c1b9dd4717314123233f95/href">https://medium.com/media/3515bf3c15c1b9dd4717314123233f95/href</a></iframe><p>One thing we didn’t go over is how to embed query parameters. Query parameters can be injected into the QueryBuilder and merged in during query generation.</p><h3>Dictionary Decoder</h3><p>So we’ve converted our query struct into a string query; now what? Ultimately, we want to hit our servers and return an instance of Query. Assuming we are able to send the string query to our server successfully and get back JSON, we need some way of creating an instance of Query from the JSON. We are going to need to create another DynamicDecoder to decode a DataDecodable using JSON.</p><p>Similar to our MappingDecoder, we are going to recursively decode a DataDecodable. However, our new DictionaryDecoder will be initialized with a JSON payload. If a JSON key is missing we will want to throw an error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7329dcb01b7a8ca071ef308447b39d4c/href">https://medium.com/media/7329dcb01b7a8ca071ef308447b39d4c/href</a></iframe><h3>Conclusion</h3><p>Ibotta uses this query generation strategy in our product to deliver a lightning fast experience to millions of users. When used in conjunction with a <a href="https://medium.com/building-ibotta/normalized-graphql-caching-in-swift-f98f99a555cf">normalized cache</a> we are able to get high rates of full / partial cache hits. We also saw big decoding speed improvements using this strategy because we are decoding into simple struct.</p><p>Ibotta hopes to soon open source our full query generation networking library named Koios.</p><h3>We’re Hiring!</h3><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4782ebdab991" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/dynamic-graphql-query-generation-in-swift-4782ebdab991">Dynamic GraphQL Query Generation In Swift</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normalized GraphQL Caching in Swift]]></title>
            <link>https://medium.com/building-ibotta/normalized-graphql-caching-in-swift-f98f99a555cf?source=rss-3b473537523f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f98f99a555cf</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Alex Pelletier]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 15:16:11 GMT</pubDate>
            <atom:updated>2020-03-16T15:16:11.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr_2rwxyR7rta_BXbQOATw.png" /></figure><p>At <a href="https://home.ibotta.com/">Ibotta</a>, we’ve spent the last year fully rewriting our graphQL networking code to transition from <a href="https://www.apollographql.com/docs/ios/">Apollo</a> to a custom solution. We’ve moved away from Apollo’s prebuilt query system to dynamically generated queries with our own normalized cached. Normalized caching enables very precise cache updates and allows cache lookups based solely on object type and id. This allows us to get cache hits on previously unseen requests.</p><h3><strong>Caching</strong></h3><p>Caching, and more specifically cache invalidation, is a really hard problem. There are all sorts of external events that could make a cache invalid. Even if you know what changed, it can be hard to mutate or purge specific elements of a cache. This article will go over a normalized caching strategy for graphQL that has helped us maintain reliable and accurate cache hits.</p><p>Let’s say we make a request for several offers and they are returned as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1c842270c9216016e38c8cb4b9fa161/href">https://medium.com/media/f1c842270c9216016e38c8cb4b9fa161/href</a></iframe><p>We can cache the entire response to disk keyed by the request. This is a very common and simple caching strategy, but it is fragile and requires constant purging on mutations.</p><p>Let’s say the user later unlocks Offer.1. Our cache is now incorrect and needs to be purged. We would need to purge all cache entries that contain Offer.1 or maintain a separate data source to correct our models on cache reads. Neither of these options are ideal. The ideal solution would be to mutate our cache so subsequent cache pulls would return correct information.</p><p>What if we could actually mutate our local cache? Introducing normalized graphQL caching. All graphQL types have a __typename field and most types have an id field. We can use this information to create deterministic object keys.</p><p>We can then store the above response as normalized data where child objects are extracted and replaced with references. This looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44eced05b26bad01d6a02cb757a06620/href">https://medium.com/media/44eced05b26bad01d6a02cb757a06620/href</a></iframe><p>With this approach, if a user were to later unlock Offer.1 we could perform the graphQL mutation on our local cache. All we would need to do is create a cache key (~&gt;Offer.1) and merge the updated properties ([&quot;unlocked&quot;: true]) into our cache.</p><h3><strong>Implementation</strong></h3><p>To store JSON payloads, we will need to separate out child objects; we will call this decomposition. And then when retrieving cached payloads we need to recompose the objects. The code in this article is going to be kept relatively simple and focused on recomposition and decomposition.</p><p>The interface for our cache is going to be very light weight: JSON in/out, cache clear, and object update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd2284975016228f5b446d109a3abca4/href">https://medium.com/media/fd2284975016228f5b446d109a3abca4/href</a></iframe><p>The underlying storage for our cache will be an in-memory dictionary. However, in production, we use a thread safe <a href="https://www.geeksforgeeks.org/lru-cache-implementation/">LRUCache</a>. We are going to start with a GraphQLCache implementation like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a4ca9d408a8829125f0fae460fea2ae/href">https://medium.com/media/7a4ca9d408a8829125f0fae460fea2ae/href</a></iframe><h3><strong>Decomposition</strong></h3><p>To decompose the JSON into child objects, we are going to recursively parse the JSON and extract child objects when found. But first we are going to need a couple of helper functions. We need to be able to determine if an object has a normalizable key. If an object doesn’t have a __typename and id we can&#39;t extract it. We are going to prefix all our object references with &quot;~&gt;&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b44e338ee8df1d8deccd11ae31487a1/href">https://medium.com/media/2b44e338ee8df1d8deccd11ae31487a1/href</a></iframe><p>When storing normalized objects we might already have some fields of an object stored. So we need to be able to merge new entries into existing ones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/940c319b8eef5575e47f236cf6cbab52/href">https://medium.com/media/940c319b8eef5575e47f236cf6cbab52/href</a></iframe><p>JSON can be categorized into three types: [Any], [String: Any], and Any where the last Any is for primitives. An [Any] could be an array of primitives or an array of dictionaries. With this in mind, normalizing the JSON is relatively straightforward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cb181992d1e9ad30f921b0f8bad8e5f/href">https://medium.com/media/4cb181992d1e9ad30f921b0f8bad8e5f/href</a></iframe><p>To cache the top level request object, we will wrap our decomposeAndCache(object:).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1450cdadb41859a41058af825ba9223e/href">https://medium.com/media/1450cdadb41859a41058af825ba9223e/href</a></iframe><p>And just like that, we have JSON responses being stored as normalized objects. But now how do we get our JSON back?</p><h3><strong>Recomposition</strong></h3><p>Recomposition is very similar to decomposition. We recursively parse the object and look for reference keys. Then we pull the objects the reference keys point to and recursively recompose those objects.</p><p>However, if an extracted child object was removed from the cache, we need to fail recomposition. If we have an array of references like [&quot;~&gt;Offer.1&quot;, &quot;~&gt;Offer.2&quot;] and ~&gt;Offer.2 is missing from the cache, we need to throw and fail recomposition.</p><p>Recomposition should take an input like [&quot;offers&quot;: [&quot;~&gt;Offer.1&quot;, &quot;~&gt;Offer.2&quot;]] and return:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d4654460b5cc4e62649d0fcf272c72/href">https://medium.com/media/83d4654460b5cc4e62649d0fcf272c72/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b048012bdc249c1f708124f7beebe63/href">https://medium.com/media/8b048012bdc249c1f708124f7beebe63/href</a></iframe><p>To use our recomposeCached(object:) function, we can provide a clean public function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc771c9ee4a4d56cfa40e201aacb740d/href">https://medium.com/media/cc771c9ee4a4d56cfa40e201aacb740d/href</a></iframe><p>There is a risk of cyclical cycles occurring during recomposition, but in practice we do not see this very often. There are a few options to get around it; the naive approach is to specify a max depth for recomposition. Or you can keep track of recomposed object keys and stop recomposing when a cycle occurs.</p><h3><strong>Cache Times</strong></h3><p>In the real world, cache records have to expire. One of the nice things we can do with a normalized cache is vary the cache times based on object type. We can cache an Offer for one hour and a Retailer for several hours. What&#39;s more, we can normalize the cache time on a per field basis. Let&#39;s store cached entries with timestamps, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46bdb2a88ac55e11ce1b0047f429fff6/href">https://medium.com/media/46bdb2a88ac55e11ce1b0047f429fff6/href</a></iframe><p>This incurs some extra storage costs, but in graphQL we often fetch the same object with various fields so we’ve found it was worth it. To create field times, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c0f5aae4708889e04774214fa63c73e/href">https://medium.com/media/9c0f5aae4708889e04774214fa63c73e/href</a></iframe><p>Next, we can update our decomposition function like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3cc7d30a8d15bbc2fb1861eefb3be5/href">https://medium.com/media/7d3cc7d30a8d15bbc2fb1861eefb3be5/href</a></iframe><p>Then, when using the cached JSON, we can evaluate that the cache time hasn’t passed. We can either evaluate cache times on a per field basis during decoding or build in the evaluation into recomposition by finding the oldest cache time and using that as the object’s cache time. We aren’t going to get into the nitty-gritty of how to edit the recomposition code to support cache times, but it should be pretty straightforward. At Ibotta we evaluate cache times on a per field basis during decoding.</p><h3><strong>Cache Updates</strong></h3><p>Now that we have this powerful normalized cache, it’s time to actually utilize it. One of the key reasons to use a normalized cache is to allow easy updates. We can retrieve cached objects based on typename + id, and then we can manipulate any of the properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f11e71bb90307a3f0d0213e391b500/href">https://medium.com/media/c6f11e71bb90307a3f0d0213e391b500/href</a></iframe><p>On updates we aren’t going to update our field timestamps because we want to treat the timestamps as when we were last guaranteed accurate data from the server. Assuming we had hooked the cache into our networking code, if we wanted to unlock Offer.1 from the first example, we could do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b7e2d8c06f9e011e5170a5542f97b20/href">https://medium.com/media/6b7e2d8c06f9e011e5170a5542f97b20/href</a></iframe><p>You could also delete particular elements and not have to wipe huge chunks of your cache.</p><h3><strong>Conclusion</strong></h3><p>The code presented in this article is a great starting point for building a robust and powerful normalized cache. When making a request for objects for ids, we can check our normalized cache for those objects and potentially get a cache hit for unseen requests. Additionally, because we are merging in duplicate objects, stale objects could potentially get updated by unrelated requests.</p><p>At Ibotta, we use this normalization strategy in production with great success. By being able to mutate our local cache, we see almost a 60% cache hit rate, resulting in decreased server usage and increased performance for our users.</p><h3>We’re Hiring!</h3><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f98f99a555cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/normalized-graphql-caching-in-swift-f98f99a555cf">Normalized GraphQL Caching in Swift</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Networking In Swift]]></title>
            <link>https://medium.com/building-ibotta/modular-networking-in-swift-c59cc590da3e?source=rss-3b473537523f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59cc590da3e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <dc:creator><![CDATA[Alex Pelletier]]></dc:creator>
            <pubDate>Fri, 28 Feb 2020 21:08:44 GMT</pubDate>
            <atom:updated>2020-02-28T22:55:22.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Networking has always been a complex problem in mobile development. You want your application to be fast, have up to date information, and be maintainable. Over the years as server technology has gotten more complex, so have our requirements for mobile networking. A simple URLSession abstraction no longer scales to meet modern business needs.</p><p>These days it is common to create a networking abstraction that accepts a generic request object with return type information, and then returns either a typed object or an error. But how do you handle all of the other baggage that is involved in making a network call? Some common problems include adding required headers, token refresh, request accumulation, caching, etc. At Ibotta, we’ve implemented a lightweight middleware and postware system to maximize reusability and testability.</p><p>The idea is to create a series of small utility classes that mutate requests in a chain to enable business logic. We call these small classes middlewares and postwares. Middlewares run before a request hits the network and can either pass the request along to the next middleware, or abort the operation. Postwares run after a request hits the network.</p><h3>Implementation</h3><p>I am going to go over the high level implementation, but in order to stay focused on the meat of modular networking, some boiler plate code will be excluded. However, it should be pretty clear how to connect the missing dots to use this in your own app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*JrFudMhnnPJQtM6wme0nSg.png" /></figure><p>We are going to create two key classes to handle our logic: an HttpManager and an HttpClient. The manager will be responsible for processing a request through the middlewares, and later processing the response through the postwares. The client will be in charge of sending the request to the network. Their public interfaces look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c48b99a055c3a6a26d724e487d216e/href">https://medium.com/media/81c48b99a055c3a6a26d724e487d216e/href</a></iframe><p>An HttpRequest contains all of the information needed to send a request to the network. But it does <strong>not</strong> contain type information about the expected return type; towards the end of this article we will add that capability on top of the HttpManager.</p><p>Next we need to define what middlewares and postwares look like. They will end up housing most of our networking logic. For convenience, we sometimes call middleware and postwares HttpWare. Their protocols look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b4ce3bc772a763f6e390bba6c05802/href">https://medium.com/media/73b4ce3bc772a763f6e390bba6c05802/href</a></iframe><p>Notice how a middleware can abort a request. This can be used for things like early exiting when a cache hit occurs, or aborting if we know the device is offline. To help keep HttpWares in an ordered chain, we allow them to specify a sort order.</p><p>If we wanted to add authentication headers to all requests we could create a super simple middleware like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ce70ca4fea2ee547f03875fd29c224/href">https://medium.com/media/a7ce70ca4fea2ee547f03875fd29c224/href</a></iframe><p>Assuming we can mock the TokenService, this tiny class is super easy to test. One of the big benefits to this approach is testability. We can build out complex HttpWares and write pretty simple unit tests directly against them. Then all of these well-tested classes can be injected into our HttpManager, and we can be confident everything works.</p><p>Middlewares and postwares can act as a bridge between services and our networking requests. In the above example, the AuthMiddleWare acts as a bridge between the TokenService and our networking layer.</p><p>So now that we’ve added an auth token to all our requests, what happens if we need to refresh the auth token? We could have several incoming requests when we notice we need to refresh our token, so we will want to collect all incoming requests while we refresh our token. This can be done with another middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46d1e01cacf0687d1f4fbd20e129429d/href">https://medium.com/media/46d1e01cacf0687d1f4fbd20e129429d/href</a></iframe><p>Notice how this middleware defines an order of .middle and the AuthMiddlWare defined an order of .last . Ordering a lot of HttpWares can be tricky, but we’ve found that in practice a lot of wares don’t require a predefined order.</p><p>Now let’s say we made a network call and we received a 401 letting the app know to log the user out. This is a great opportunity to use a postware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb17e7aed62963ba37fdf4ac308d134/href">https://medium.com/media/bbb17e7aed62963ba37fdf4ac308d134/href</a></iframe><p>We’ve just enabled complex auth token logic without touching our core networking code. Pretty cool!</p><p>We’ve only looked at classes that are either a middleware or a postware, but a class could be both a middleware and postware. A 304 cache for instance would want to save response data as a postware and adjust requests with a timestamp as a middleware.</p><p>To implement the facilitation of these HttpWares, we define a function to process a request through the middlewares, and a function to process a request + a response through the postwares. This would look something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3fde33e9015466717d9d3da94292d58/href">https://medium.com/media/a3fde33e9015466717d9d3da94292d58/href</a></iframe><h3>Polishing Up Our Implementation</h3><p>At this point our HttpManager accepts an HttpRequest, but an HttpRequest does not contain type information. To polish up our HttpManager, we will implement a new request type that contains type information so we can return type safe results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096c2992e21d8aeb7238ee7031c80e2a/href">https://medium.com/media/096c2992e21d8aeb7238ee7031c80e2a/href</a></iframe><p>Then inside our HttpManager we will convert a Request to an HttpRequest, and then process that request through our HttpWares.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4ae97399cdd0c2d731ac28b0f5c9ea7/href">https://medium.com/media/f4ae97399cdd0c2d731ac28b0f5c9ea7/href</a></iframe><p>Another optimization we can make is to define a ServiceDefinition for each service we send networking requests to. A ServiceDefinition contains information like base url and default encoding strategies. Then when creating an HttpManager, a ServiceDefinition can be injected at initialization.</p><h3>Conclusion</h3><p>Using middlewares and postwares to encapsulate networking logic is a great way of maintaining separation of concern while enabling complex networking logic. There is no limit to what you can build into your networking layer using this modular approach. This is a great bottom layer to build additional layers of abstraction on top of.</p><p>Some useful wares we use include request accumulators, http cache, 304 cache, time logging, token refresh, token validation, and various middlewares for different required headers. At Ibotta we have 19 middlewares and postwares that our services use. Some are used for almost every request, and some are only used in rare cases.</p><h3>We’re Hiring!</h3><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59cc590da3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/modular-networking-in-swift-c59cc590da3e">Modular Networking In Swift</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>