<?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 Piotr Żmudziński on Medium]]></title>
        <description><![CDATA[Stories by Piotr Żmudziński on Medium]]></description>
        <link>https://medium.com/@ptr.zmudzinski?source=rss-cf24ba1a23dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PBptK7J1YBT9noT97YnTdg.jpeg</url>
            <title>Stories by Piotr Żmudziński on Medium</title>
            <link>https://medium.com/@ptr.zmudzinski?source=rss-cf24ba1a23dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:09:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ptr.zmudzinski/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[Crafting enriched link previews in Swift by reading OpenGraph metadata]]></title>
            <link>https://medium.com/@ptr.zmudzinski/crafting-enriched-link-previews-in-swift-by-reading-opengraph-metadata-b1139bf2ef9a?source=rss-cf24ba1a23dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1139bf2ef9a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-graph]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Piotr Żmudziński]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 11:36:10 GMT</pubDate>
            <atom:updated>2023-08-09T11:36:10.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s digital landscape, content sharing has become a ubiquitous part of our online interactions. Whether it’s sharing articles, videos, or even products, we often encounter snippets of content that we want to preview before diving in. This is where <a href="https://ogp.me/">OpenGraph</a> comes into play — a set of metatags inside website’sheadsection that allows you to create rich link previews that provide a sneak peek into the content behind a URL. We will read it by hitting given URL and extract things like site’s title, image and description, just like iOS Messages when you sent someone link to your favorite movie:</p><figure><img alt="Link preview from movie “Heat” on IMDB" src="https://cdn-images-1.medium.com/max/616/1*V_YfG1OIl4oU3tWiJ8RL8A.png" /></figure><h3>OpenGraph basics</h3><p>Specification mentions couple of basic meta tags we will start with:</p><blockquote>og:title - The title of your object as it should appear within the graph, e.g., &quot;The Rock&quot;.</blockquote><blockquote>og:type - The <a href="https://ogp.me/#types">type</a> of your object, e.g., &quot;video.movie&quot;. Depending on the type you specify, other properties may also be required.</blockquote><blockquote>og:image - An image URL which should represent your object within the graph.</blockquote><blockquote>og:url - The canonical URL of your object that will be used as its permanent ID in the graph, e.g., &quot;https://www.imdb.com/title/tt0117500/&quot;.</blockquote><p>This is all we need to display preview of a link. Our plan is to:</p><ol><li>Get an instance of URL as input of our tool,</li><li>Fetch it using URLSession and extract head section,</li><li>Collect all meta tags inside it,</li><li>Return those in easy-to-use response struct</li></ol><p>For point #2 we are going to use excellent HTML parsing library — <a href="https://github.com/scinfu/SwiftSoup">SwiftSoup</a>.</p><p>One crucial point to mention — OG specification allows to have multiple tags with the same name and different values which indicate that’s actually an array:</p><pre>&lt;meta property=&quot;og:actor&quot; content=&quot;Actor 1&quot; /&gt;<br>&lt;meta property=&quot;og:actor&quot; content=&quot;Actor 2&quot; /&gt;<br>&lt;!-- .. and so on... --&gt;</pre><p>That’s the reason we gonna internally store results in form of dictionary with key set to String and value to [String] . If there is only one value we can use <a href="https://developer.apple.com/documentation/swift/array/first">first</a> method to get it.</p><h3>Jumping into code</h3><p>Let’s start by declaring return type together with helper variables to get basic OpenGraph types such as title:</p><pre>/// Represents the response containing OpenGraph data extracted from a source.<br>public struct OpenGraphResponse {<br>    private let source: [String: [String]]<br>    <br>    public init(source: [String: [String]]) {<br>        self.source = source<br>    }<br>}<br><br>// MARK: - Properties and Extensions<br><br>public extension OpenGraphResponse {<br>    /// The title of the OpenGraph content.<br>    var title: String? {<br>        source.stringValue(&quot;og:title&quot;)<br>    }<br>    <br>    /// The type of the OpenGraph content.<br>    var type: String? {<br>        source.stringValue(&quot;og:type&quot;)<br>    }<br>    <br>    /// The description of the OpenGraph content.<br>    var description: String? {<br>        source.stringValue(&quot;og:description&quot;)<br>    }<br>    <br>    /// The URL of the OpenGraph content.<br>    var url: URL? {<br>        source.urlValue(&quot;og:url&quot;)<br>    }<br>    <br>    /// The URL of the main image associated with the OpenGraph content.<br>    var imageURL: URL? {<br>        source.urlValue(&quot;og:image&quot;)<br>    }<br>}<br><br><br>private extension Dictionary where Element == (key: String, value: [String]) {<br>    func stringValue(_ key: String) -&gt; String? {<br>        self[key]?.first<br>    }<br>    <br>    func urlValue(_ key: String) -&gt; URL? {<br>        guard let string = self[key]?.first else {<br>            return nil<br>        }<br>        return URL(string: string)<br>    }<br>}</pre><p>Now we can declare main part of our tool which is reader itself. Its responsibility is to take URL or URLRequest and start the process:</p><pre>public class OpenGraphReader {<br>    private let urlSession: URLSession<br><br>    public init(sessionConfiguration: URLSessionConfiguration = .default) {<br>        urlSession = URLSession(configuration: sessionConfiguration)<br>    }<br><br>    public func fetch(url: URL) async throws -&gt; OpenGraphResponse {<br>        try await fetch(request: .init(url: url))<br>    }<br>    <br>    public func fetch(request: URLRequest) async throws -&gt; OpenGraphResponse {<br>        let (data, response) = try await urlSession.data(for: request)<br>        <br>        guard let html = String(data: data, encoding: .utf8) else {<br>            throw OpenGraphError.invalidResponse<br>        }<br>        <br>        return try parse(html: html)<br>    }<br>}</pre><p>Inside parse function, we initiate a process of traversing through the &lt;meta&gt; tags within the HTML using doc.select(&quot;meta&quot;). Each meta tag is scrutinized, extracting both the property name and content attributes. If the property name is absent, a fallback to the name attribute is attempted, if available:</p><pre>    public func parse(html: String) throws -&gt; OpenGraphResponse {<br>        do {<br>            let doc = try SwiftSoup.parse(html)<br><br>            let metas = try doc.select(&quot;meta&quot;)<br>            var result: [String: [String]] = [:]<br>            <br>            metas.forEach { meta in<br>                guard var propertyName = try? meta.attr(&quot;property&quot;), let content = try? meta.attr(&quot;content&quot;) else { return }<br>                if propertyName.isEmpty, let metaName = try? meta.attr(&quot;name&quot;) {<br>                    propertyName = metaName<br>                }<br>                <br>                var currentValues = result[propertyName, default: []]<br>                currentValues.append(content)<br>                result.updateValue(currentValues, forKey: propertyName)<br>            }<br>            <br>            return OpenGraphResponse(source: result)<br>        } catch {<br>            throw OpenGraphError.parsingError(error)<br>        }<br>    }</pre><p>In a conventional loop, we accumulate the extracted properties and their respective content into a dictionary called result. The dictionary maintains the format of String: [String], providing a structured storage for the OpenGraph metadata.</p><h3>Usage</h3><figure><img alt="Stand back ,we’re trying this in production" src="https://cdn-images-1.medium.com/max/500/1*_FVq_c4Jq96m_ZuLi8VQIQ.jpeg" /></figure><p>No we are ready to use it! Let’s create sample request and print the results:</p><pre>do {<br>    let reader = OpenGraphReader()<br>    let parsed = try await reader.fetch(url: .init(string: &quot;https://www.imdb.com/title/tt15398776/?ref_=ext_shr_lnk&quot;)!)<br>                        <br>    print(&quot;title \(parsed.title)&quot;)<br>    print(&quot;description \(parsed.description)&quot;)<br>  } catch {<br>    print(&quot;error \(error)&quot;)<br>  }</pre><h3>Conclusion</h3><p>We were able to implement given functionality using async and await Swift API and with help of SwiftSoup library. If you need similar functionality without re-implementing everything you can use <a href="https://github.com/pzmudzinski/OpenGraphReader">OpenGraphReader</a> SPM package which brings more features out of the box.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1139bf2ef9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Shopping Cart with Swift and Combine]]></title>
            <link>https://medium.com/@ptr.zmudzinski/reactive-shopping-cart-with-swift-and-combine-151f401093d0?source=rss-cf24ba1a23dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/151f401093d0</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Piotr Żmudziński]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 10:08:23 GMT</pubDate>
            <atom:updated>2020-08-15T10:08:23.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Reactive programming was quite popular among <em>iOS</em>/<em>OSX</em> developers in recent years, although there was no “official” API. Community created wonderful <a href="https://github.com/ReactiveX/RxSwift">RxSwit</a> project, being one of most popular 3rd party tools used in Apple ecosystem. Things has changed little bit once Apple released their own Combine framework which introduced similar API and Rx-ish thinking.</p><p>Today, we are going to try it out via practical example of shopping cart functionality. We will be discussing how to model internal and external events happening in our buying process and thinking about posssible future extensions. Article assumes you have basic knowledge about <em>swift</em> and RxSwift or Combine.</p><h3>Basics</h3><p>Let’s imagine hypotethical UI for our online shop and think about required functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*Q7vUbqqzyhNM33il" /></figure><p>As we can see we provide easy API for:</p><ul><li>Getting list of current orders</li><li>Adding new products to a cart</li><li>Incrementing or decrementing number of ordered products</li><li>Providing total price of a cart and for each order</li><li>Getting total number of products</li></ul><p>That brings two basic entities in our project, Product and ProductOrder:</p><pre>struct Product {<br>    var id: Int<br>    var name: String<br>    var price: Double<br>}</pre><pre>struct ProductOrder {<br>    var product: Product<br>    var quantity: UInt<br>}</pre><p>Now, let’s define possible events happening on our UI:</p><ul><li>Adding new product to an existing cart</li><li>Incrementing or decrementing order quantity</li><li>Clearing content of a cart (e.g. after succesful payment process)</li></ul><p>We can cover that by implementing CartAction enum:</p><pre>enum CartAction {<br>    case add(product: Product)<br>    case incrementOrder(withProductId: Int)<br>    case decrementOrder(withProductId: Int)<br>    case clear<br>}</pre><p>Our ShoppingCart will take CartAction events as an input and publish array of ProductOrder as an output.<br>For simplicity, we will skip error cases like incrementing order which was not present in a cart.</p><pre>class ShoppingCart {<br>    let orders: AnyPublisher&lt;[ProductOrder], Never&gt;<br>    // UI events might be mapped to instances to CartAction and streamed here<br>    let input: AnySubscriber&lt;CartAction, Never&gt;</pre><pre>    init() {<br>        let actionInput = PassthroughSubject&lt;CartAction, Never&gt;()<br>        // it does not do much right now<br>        self.orders = Just([]).eraseToAnyPublisher()<br>        self.input = AnySubscriber(actionInput)<br>    }<br>}</pre><p>We have basic interface with our input and output declared. We also declared our subject which will be used for listening for CartAction events and transforming them into current orders. Let&#39;s move to...</p><h3>Implementation</h3><p>Although clients of our API will use orders as an array (which is simplest solution for UITableView or UICollectionView) we need to find products by theirs IDs as quickly as possible.<br>That indicates using <a href="https://developer.apple.com/documentation/swift/dictionary">Dictionary</a> which will fetch items by ID faster than regular array. Nevertheless, we will expose it as an array to clients using Dictionary.values property.</p><p>In addition, we will implement our shopping experience in <em>TDD</em> spirit — by writing failing test cases:</p><pre>func testAddingProduct() {<br>    let expectation = XCTestExpectation(description: &quot;Adding new product&quot;)</pre><pre>    let cancellable = cart.orders<br>        .sink(receiveValue: { (orders) in<br>            // after calling add we are expecting cart to publish new array of orders with one element<br>            XCTAssertEqual([ProductOrder(product: .apple, quantity: 1)], orders)<br>            expectation.fulfill()<br>    })</pre><pre>    triggerCartActions(.add(product: .apple))</pre><pre>    wait(for: [expectation], timeout: 5.0)<br>}</pre><p>Content of a cart is a function of a CartAction and previous state of a cart. As an example if user clicks on a increment Apple order cart becomes [otherOrders, appleOrder + 1].</p><p>In order to achieve this notion of previous state we will reach for <a href="https://developer.apple.com/documentation/combine/publishers/combinelatest/3229133-scan">scan</a> operator:</p><pre>// 1<br>self.orders = actionInput.scan([Int:ProductOrder]()) { (currentOrders, action) -&gt; [Int:ProductOrder] in<br>// 2<br>    var newOrders = currentOrders<br>    switch (action) {<br>    case .add(let product):<br>        // 3<br>        newOrders.updateValue(ProductOrder(product: product), forKey: product.id)<br>    }</pre><pre>    return newOrders<br>}</pre><p>Explanations for each lines in snippet above:</p><ol><li>We are passing default value of empty Dictionary into scan operator (user does not have any items by default)</li><li>We are creating mutable variable in order to modify our accumulator</li><li>We are inserting new ProductOrder with default value of quantity 1 into accumulator</li></ol><p>We are almost there, although we need to do final thing — map result of a scan operator ([Int:ProductOrder]) to <em>Front-End-friendly</em> structure of an [ProductOrder]:</p><pre>...<br>.map(\.values)<br>.map(Array.init)</pre><p>We can implement incrementing, decrementing orders and clearing cart in similar manner:</p><pre>case .incrementProduct(withId: let productId):<br>    if let order = newOrders[productId] {<br>        newOrders.updateValue(order.incremented, forKey: productId)<br>    }<br>case .decrementProduct(withId: let productId):<br>    if let order = newOrders[productId] {<br>        let decrementedOrder = order.decremented<br>        if (decrementedOrder.quantity == 0) {<br>            // Let&#39;s remove order if quantity reaches 0<br>            newOrders.removeValue(forKey: productId)<br>        } else {<br>            newOrders.updateValue(decrementedOrder, forKey: productId)<br>        }<br>    }<br>case .clear:<br>    return [:]</pre><p>If user decrements order with only one instance of a product we remove it from cart completely. We are going to also add incremented and decremented helpers for our ProductOrder:</p><pre>var incremented: ProductOrder {<br>    return ProductOrder(product: product, quantity: quantity + 1)<br>}</pre><pre>var decremented: ProductOrder {<br>    return ProductOrder(product: product, quantity: quantity - 1)<br>}</pre><p>We also should add a new test case where we add two products and after than increment one of them:</p><pre>let expectation = XCTestExpectation(description: &quot;Incrementing existing product&quot;)</pre><pre>let cancellable = cart<br>    .orders<br>    .sink { (orders) in<br>        if orders.contains(ProductOrder(product: .beer, quantity: 2)) {<br>            expectation.fulfill()<br>        }<br>}</pre><pre>triggerCartActions(<br>    .add(product: .apple),<br>    .add(product: .beer),<br>    .incrementProduct(withId: Product.beer.id)</pre><pre>wait(for: [expectation], timeout: 5.0)</pre><p>Things seem to work!</p><h3>Extra functionality</h3><p>After achieving basic funcionality of modifying cart content we can easily add things like publishing number of products or total price:</p><pre>extension ProductOrder {<br>    var price: Double {<br>        return product.price * Double(quantity)<br>    }<br>}</pre><pre>extension ShoppingCart {<br>    var numberOfProducts: AnyPublisher&lt;Int, Never&gt; {<br>        return orders.map(\.count).eraseToAnyPublisher()<br>    }</pre><pre>    var totalPrice: AnyPublisher&lt;Double, Never&gt; {<br>        return orders.map { $0.reduce(0) { (acc, order) -&gt; Double in<br>                acc + order.price<br>            }<br>        }.eraseToAnyPublisher()<br>    }<br>}</pre><p>In addition we can track events and send them to our Analytics platform by subscribing to cart’s input:</p><pre>let subscriber = PassthroughSubject&lt;CartAction, Never&gt;()<br>subscriber.receive(subscriber: cart.input)<br>subscriber.sink { (action) in<br>    // send it to Google Analytics!<br>    Anaylitcs.track(action)<br>}</pre><p>Lastly, we can decorate current behavior with things like discounts:</p><pre>extension ShoppingCart {<br>    func discountedTotalPrice(discountRate: Double = 0.1) -&gt; AnyPublisher&lt;Double, Never&gt; {<br>        return totalPrice.map { $0 * (1.0 - discountRate) }.eraseToAnyPublisher()<br>    }<br>}</pre><h3>Summary</h3><p>We used Combine API in order to implement simple shopping cart with scan and map operators. This implementation might be expanded to various new functionality without touching original codebase (<em>O</em> in <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">S<em>O</em>LID</a>) and easily covered with test cases as it is not coupled with any sort of <em>UI</em>.</p><p>Full example is available <a href="https://gist.github.com/pzmudzinski/155f998861bdee46ee467e824569dbdb">here</a>, together with <a href="https://gist.github.com/pzmudzinski/52e51946a6108d5a607aac5d658880fc">test cases</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151f401093d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure AWS Lambda with Google email domain check — Part 2]]></title>
            <link>https://medium.com/@ptr.zmudzinski/secure-aws-lambda-with-google-email-domain-check-part-2-97588baaae29?source=rss-cf24ba1a23dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/97588baaae29</guid>
            <category><![CDATA[amazon-api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Piotr Żmudziński]]></dc:creator>
            <pubDate>Mon, 18 May 2020 16:38:42 GMT</pubDate>
            <atom:updated>2020-05-18T16:38:42.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure AWS Lambda with Google email domain check — Part 2</h3><h4>Let’s use our AWS Lambda endpoint + Google authentication in simple React app.</h4><p>In <a href="https://medium.com/p/4a8347194fe6">last part</a> we implemented our serverless back end using AWS Lambda + Google email authentication. Now, we are going to move to front end part. Our tech stack will be React + Typescript, which is perfect combo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*x-anglMKZkXi76DPxWfSsA.jpeg" /></figure><h4>Getting user credentials</h4><p>We need to do couple of things on login page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBtRWi33BZGSsubUKtRkbw.png" /></figure><ol><li>Display Google sign in button</li><li>Take token returned from Google authentication</li><li>Validate token against our /verify endpoint</li><li>If it’s valid move user to dashboard page and fetch our secured data</li></ol><p>We can achieve points #1 and #2 by using <a href="https://github.com/anthonyjgrove/react-google-login">react-google-login</a> library:</p><pre>&lt;main&gt;<br>  &lt;h1&gt;Sign In to our realm&lt;/h1&gt;<br>  &lt;GoogleLogin<br>    clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID!}<br>    onSuccess={signIn}<br>  /&gt;<br>&lt;/main&gt;</pre><p>We will pass the same <em>OAuth</em> client id we used while setting lambdas endpoints.</p><p>Now we can move for implementing our signIn callback:</p><pre>const verifyToken = async (token: string) =&gt; {<br>  const res = await fetch(`${baseUrl}/auth/verify`, {<br>    headers: { [AUTH_HEADER_NAME]: token },<br>  });<br>  return res.ok;<br>};<br><br>const signIn = useCallback(async ({ tokenId }) =&gt; {<br>  const isValidToken = await verifyToken(tokenId);<br>  if (!isValidToken) {<br>    setError(&quot;Invalid token.&quot;);<br>    return;<br>  }<br>  saveAuthToken(tokenId);<br>  history.replace(&quot;/&quot;);<br>});</pre><p>verifyToken simply checks if token is valid or not based on HTTP status code. If it&#39;s invalid we display an error. If it&#39;s valid we redirect user to dashboard. We could skip validation part and simply try to hit our secured endpoint but it would complicate code little bit.<br> In addition we are saving our token in <a href="https://developer.mozilla.org/pl/docs/Web/API/Window/localStorage">LocalStorage</a> so whenever we refresh browser user does not have to login again:</p><pre>export const saveAuthToken = (token: string) =&gt; {<br>  localStorage.setItem(AUTH_TOKEN_KEY, token);<br>};</pre><h4>Crossing the Rubicon</h4><p>Finally, we can get access to our <strong>secrets</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*sucH_SYdYB8ZB7mxTK0tcw.jpeg" /></figure><p>We will do simple fetch by passing token as a Authorization header:</p><pre>const defaultHeaders = () =&gt; {<br>  const authKey = localStorage.getItem(AUTH_TOKEN_KEY);<br>  if (authKey) {<br>    return { [AUTH_HEADER_NAME]: authKey };<br>  }<br>};<br><br>export const getSecretData = async () =&gt; {<br>  const res = await fetch(`${baseUrl}/data`, {<br>    headers: defaultHeaders(),<br>  });<br>  if (res.ok) {<br>    return res.json();<br>  } else {<br>    throw Error(&quot;Failed to fetch secret data&quot;);<br>  }<br>};</pre><p>Last thing left is to show it on our dashboard page:</p><pre>const [data, setData] = useState&lt;string[]&gt;();<br>useEffect(() =&gt; {<br>  const fetchSecrets = async () =&gt; {<br>    const mySecretTexts = await getSecretData();<br>    setData(mySecretTexts);<br>  };<br>  fetchSecrets();<br>}, []);<br><br>return (<br>  &lt;main&gt;<br>    &lt;h1&gt;Hello from dashboard&lt;/h1&gt;<br>    {data &amp;&amp; (<br>      &lt;ul&gt;<br>        {data.map((text) =&gt; (<br>          &lt;li key={text}&gt;{text}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    )}<br>  &lt;/main&gt;<br>);</pre><p>This is it!.<br> We implemented happy path for our authentication flow, now we would have to think about some other edge cases:</p><ul><li><strong>What if user tries to open </strong><strong>/login page if it&#39;s already logged in?</strong></li><li><strong>What if user tries to open </strong><strong>/dashboard without sign in?</strong></li><li><strong>What if user opens website after week of inactivity and saved token is invalid?</strong></li></ul><p>Let’s worry about number <strong>#1</strong> and <strong>#2</strong>.<br>We gonna wrap our Dashboard and Login components with <a href="https://reacttraining.com/react-router/web/api/Route">Route</a> allowing user to visit page only if it has correct authentication state.<br>We are going to add AuthState enum covering all possible cases:</p><pre>export enum AuthState {<br>  LOADING = &quot;loading&quot;,<br>  AUTHENTICATION_SUCCESS = &quot;auth_success&quot;,<br>  AUTHENTICATION_FAILED = &quot;auth_failed&quot;,<br>  NO_PREVIOUS_SIGN_IN = &quot;auth_fresh&quot;,<br>}</pre><p>Both AUTHENTICATION_FAILED and NO_PREVIOUS_SIGN_IN should redirect user to login page, while first one indicates that there was authToken saved in LocalStorage, although it did not pass validation test (e.g. is outdated).</p><p>Now we can use our Route-wrapper which will simply take <strong>predicate function </strong>and allow user to visit a page or redirect in case function returns false:</p><pre>type AuthRouteProps = {<br>  authPredicate: () =&gt; boolean;<br>  redirectPath: string;<br>  children: React.ReactNode;<br>};<br><br>const AuthenticatedRoute = ({<br>  authPredicate,<br>  redirectPath,<br>  children,<br>  ...rest<br>}: AuthRouteProps &amp; RouteProps) =&gt; {<br>  return (<br>    &lt;Route<br>      {...rest}<br>      render={({ location }) =&gt; {<br>        return authPredicate() ? (<br>          children<br>        ) : (<br>          &lt;Redirect<br>            to={{<br>              pathname: redirectPath,<br>              state: { from: location },<br>            }}<br>          /&gt;<br>        );<br>      }}<br>    /&gt;<br>  );<br>};</pre><p>Lastly we have to wrapper our components with matching predicate functions and redirect paths (we skipped useCallback definitions for simplicity):</p><pre>const isAuthenticated = () =&gt; {<br>  return authState === AuthState.AUTHENTICATION_SUCCESS;<br>};<br><br>const isUnauthenticated = () =&gt; {<br>  return [<br>    AuthState.AUTHENTICATION_FAILED,<br>    AuthState.NO_PREVIOUS_SIGN_IN,<br>  ].includes(authState);<br>};<br><br>&lt;Switch&gt;<br>  &lt;AuthenticatedRoute<br>    authPredicate={isUnauthenticated}<br>    path=&quot;/login&quot;<br>    redirectPath=&quot;/&quot;<br>  &gt;<br>    &lt;Login /&gt;<br>  &lt;/AuthenticatedRoute&gt;<br><br>  &lt;AuthenticatedRoute authPredicate={isAuthenticated} redirectPath=&quot;/login&quot;&gt;<br>    &lt;Dashboard /&gt;<br>  &lt;/AuthenticatedRoute&gt;<br>&lt;/Switch&gt;;</pre><p>We should also take care of actually setting correct authState in two cases:</p><ul><li>While app is booting we should validate token saved in LocalStorage</li><li>If user logs in using our page we should set it to AUTHENTICATION_SUCCESS</li></ul><p>App boot seems to be perfect use-case for useEffect hook:</p><pre>useEffect(() =&gt; {<br>  const appBoot = async () =&gt; {<br>    const authToken = getAuthToken();<br>    if (!authToken) {<br>      setBootState(AuthState.NO_PREVIOUS_SIGN_IN);<br>      return;<br>    }<br>    try {<br>      const isValidToken = await verifyToken(authToken);<br>      if (isValidToken) {<br>        setBootState(AuthState.AUTHENTICATION_SUCCESS);<br>      } else {<br>        throw new Error(&quot;Invalid auth token&quot;);<br>      }<br>    } catch (exception) {<br>      setBootState(AuthState.AUTHENTICATION_FAILED);<br>      removeAuthToken();<br>    }<br>  };<br><br>  appBoot();<br>}, []);</pre><p>We also need to add callback to our Login page:</p><pre>&lt;Login onSuccess={() =&gt; {<br>    setAuthState(AuthState.AUTHENTICATION_SUCCESS);<br>    history.replace(&quot;/&quot;);<br>}/&gt;</pre><p>Nice. Try to log in and then open /login path again. You should be redirected back to our dashboard. Similarly, if you open /dashboard you are asked to log in. In case of old authToken being stored in LocalStorage app will reach AUTHENTICATION_FAILED and sign in process would be repeated.</p><p>We are ready to deploy and get some 👏 from your coworkers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*GkozKE8o69LDB_3RqSY4QQ.jpeg" /><figcaption>World is saved, again</figcaption></figure><h4>Summary</h4><p>We created pretty simple solution for secured AWS Lambda + API Gateway endpoint. It&#39;s easy to deploy and valid approach for internal tools which should be accessible for employees / members only. Creating front end can be really quick with help of 3rd party libraries such as react-google-login or react-router.</p><p>Source code is publicly available at my <a href="https://github.com/pzmudzinski/lambda-google-sign-in">github repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97588baaae29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure AWS Lambda with Google email domain check — Part 1]]></title>
            <link>https://medium.com/@ptr.zmudzinski/secure-aws-lambda-with-google-email-domain-check-part-1-4a8347194fe6?source=rss-cf24ba1a23dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8347194fe6</guid>
            <category><![CDATA[amazon-api-gateway]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Piotr Żmudziński]]></dc:creator>
            <pubDate>Mon, 18 May 2020 16:38:15 GMT</pubDate>
            <atom:updated>2020-05-18T16:38:15.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>Secure AWS Lambda with Google email domain check — Part 1</h3><h4>How to secure AWS Lambda endpoint with Google authentication and making sure only specific email domain will have access to it?</h4><p>We need to implement simple web application with couple of requirements:</p><ul><li>Application will have login and dashboard screens. After user succesfully logs in there is redirection to dashboard which will fetch some secret data using our endpoint</li><li>REST endpoints will not be used very often so setting up EC2 machine with server constantly running would be overkill ($$$)</li><li>Client can use our REST API only if user is authenticated with email matching mycompany.com domain</li></ul><p>We will go with AWS Lambda bundled with custom <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html">authorizer</a> for validing token coming from login process. In addition we will use <a href="http://serverless.com/">serverless</a> for bundling and deployment. Our language choose will be <a href="http://typescriptlang.org/">Typescript</a> for both lambda and client.</p><h4>Architecture</h4><p>We need to make sure that client will use Google sign in using email with preferred domain and then call our lambda function using AWS API Gateway passing Authorization header:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOysbMLvcK3e-gWIeVkMPA.png" /></figure><p>Before reaching to any secured data we will use custom authorizer which will check if token is associated with email matching our preferred domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTpN0QzVoMkTTbqEIP2UZQ.png" /></figure><p>Finally we can take a look at complete client and lambdas endpoints flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_6cSX2IuarhqOpymIs16A.png" /></figure><p>Ok, it should be <em>more or less</em> clear, we can…</p><h4>Start coding!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*HbRIf7hZj6xu-pXLkYahaQ.png" /><figcaption>#absolutely</figcaption></figure><p>We will implement two parts of a project — our BE and FE. We will use Typescript on both. Let&#39;s start with our API so we won&#39;t block our FE team.</p><h4>Lambdas</h4><p>We need three main parts on our serverless back end:</p><ul><li>Authorizer for email domain verification</li><li>Secret data endpoint secured with authorizer</li><li>Helper endpoint for validating if token is valid (so after logging in client can check if there is point in moving user to dashboard)</li></ul><h4>Authorizer</h4><p>We will use <a href="https://www.npmjs.com/package/google-auth-library">google-auth-library</a> for email domain verification, let&#39;s start by creating verify helper method:</p><pre>const client = new OAuth2Client(CLIENT_ID);<br>const acceptedDomains = [COMPANY_DOMAIN];<br><br>async function verify(token?: string) {<br>  if (!token) {<br>    throw Error(&quot;Missing auth token&quot;);<br>  }<br><br>  const ticket = await client.verifyIdToken({<br>    idToken: token,<br>    audience: CLIENT_ID,<br>  });<br>  const payload = ticket.getPayload();<br>  if (!payload || !payload.hd) {<br>    throw Error(&quot;Missing payload&quot;);<br>  }<br><br>  if (acceptedDomains.includes(payload.hd)) {<br>    return true;<br>  } else {<br>    throw Error(&quot;Invalid Google Domain&quot;);<br>  }<br>}</pre><p>You might notice we are passing CLIENT_ID for our OAuth2Client.<br> In order to create it you need to log to <a href="http://developers.google.com/">developer console</a> and click through those steps:</p><ol><li>Credentials</li><li>Create Credentials</li><li>OAuth client ID ((might ask you to setup application name first))</li><li>Select <strong>Web application</strong></li><li>Put name of your key</li><li>Set authorized origins for debugging purposes (e.g. <a href="http://localhost:3000)">http://localhost:3000)</a></li></ol><p>We will pass both CLIENT_ID and COMPANY_DOMAIN via env variable.</p><p>You are probably asking yourself what is that weird payload.hd line.</p><p>hd stands for <strong>hosted domain</strong> and it is string containing email domain. Once we get it we simply check if it matches our requirements. In any other case we are throwing an Error.</p><p>Once we have our verify function we can add authorizer and verifyToken endpoint:</p><pre>export const authorizationHandler = async (<br>  event: APIGatewayTokenAuthorizerEvent,<br>  _<br>) =&gt; {<br>  try {<br>    await verify(event.authorizationToken);<br>    return generateAllow(&quot;*&quot;);<br>  } catch (exception) {<br>    console.error(exception, exception.stack);<br>    return generateDeny(event.methodArn);<br>  }<br>};<br><br>export const verifyTokenHandler = async (<br>  event: APIGatewayProxyEvent<br>): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>  const headers = event.headers || {};<br>  try {<br>    await verify(headers[&quot;Authorization&quot;]);<br>    return {<br>      statusCode: 200,<br>      body: &quot;Success&quot;,<br>    };<br>  } catch (exception) {<br>    return {<br>      statusCode: 403,<br>      body: &quot;Failure&quot;,<br>    };<br>  }<br>};</pre><p>authorizationHandler generates allow policy for all (thus &quot;*&quot;) resources, because of the way AWS caches policy response (based on Authorization header). If we used event.methodArn client would be able to execute only on response while getting 403 for all further ones (because of arn mismatch). We could generate something more strict here, but for now let&#39;s keep it simple.</p><p>verifyTokenHandler returns statusCode according to sent token:</p><ul><li>200 if it is valid (domain matches our organization/company)</li><li>403 if it is invalid</li></ul><h4>Secured endpoint</h4><p>Finally, we can implement our dummy <em>secret data</em> endpoint:</p><pre>const secretData = [&quot;Super Secret String 1&quot;, &quot;Super Secret String 2&quot;];<br><br>export const getData = async (<br>  event: APIGatewayEvent<br>): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify(secretData),<br>  };<br>};</pre><h4>Putting all together</h4><p>Now we can add our lambdas declarations to serverless.yml file:</p><pre>functions:<br>  authorizerFunc:<br>    handler: src/auth/controller.authorizationHandler<br><br>  verify-token:<br>    handler: src/auth/controller.verifyTokenHandler<br>    events:<br>      - http:<br>          path: auth/verify<br>          method: get<br>          cors: true<br><br>  get-data:<br>    handler: src/data/controller.getData<br>    events:<br>      - http:<br>          path: data<br>          method: get<br>          cors: true<br>          authorizer: authorizerFunc</pre><p>We expose two endpoints:</p><ul><li>GET /data which points to getData handler, secured by our custom authorizer</li><li>GET /auth/verify which points to verifyTokenHandler</li></ul><p>Let’s run our lambdas locally:</p><pre>serverless offline</pre><p>You should see them running on localhost:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*FTiCbzm8yszd2N8VH8WkLQ.png" /><figcaption>Server ready for action!</figcaption></figure><p>Calling /dev/data should throw 403 status error because of missing authorization header:</p><pre>$ curl http://localhost:3000/dev/data<br>{&quot;statusCode&quot;:403,&quot;error&quot;:&quot;Forbidden&quot;,&quot;message&quot;:&quot;User is not authorized to access this resource&quot;}</pre><p>Huh, that was pretty easy, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*-hk_zKsNN7kZLhgUxT9q_w.jpeg" /></figure><p>We could start playing with our endpoints, but let’s do that by implementing front end part. This is <a href="https://medium.com/p/97588baaae29">part 2 of our article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8347194fe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Editable UITableView With RxSwift]]></title>
            <link>https://medium.com/@ptr.zmudzinski/editable-uitableview-with-rxswift-4ce8ae0aa920?source=rss-cf24ba1a23dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce8ae0aa920</guid>
            <dc:creator><![CDATA[Piotr Żmudziński]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 13:36:11 GMT</pubDate>
            <atom:updated>2018-11-14T22:14:16.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>One of most common tasks which mobile developers have to solve is displaying list of items fetched from some kind of <em>API</em>. In 99% of cases it is done with help of UITableView or UICollectionView classes, which in addition offer &quot;swipe-to-delete&quot; or reordering functionality out of the box.</p><p>We will focus on fetching, displaying and allowing users to delete items from our list by using RxSwift library. We will discuss how to model our observables to match events happening in the system.</p><h3>Sample scenario</h3><p>Imagine we are building app for displaying user favorite books fetched from our back end. In addition they might swipe cell to the left and click on a delete button:</p><figure><img alt="sketch" src="https://cdn-images-1.medium.com/max/486/0*yZTp6bdiv9zAX_56.png" /></figure><p>This is our trivial model class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c029b50089d63ebfd76b40448d065c24/href">https://medium.com/media/c029b50089d63ebfd76b40448d065c24/href</a></iframe><p>Just like in real life, there are no books with the same title so we can be sure there will be no collisions.</p><p>We also need some object representing remote API which we can talk to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a6971d939bd93f06e070ddad9d872e2/href">https://medium.com/media/5a6971d939bd93f06e070ddad9d872e2/href</a></iframe><p>Our Api is able to send real-time updates, meaning every time user&#39;s preferences change Observable returned by getBooks is going to emit new snapshot of books array. On the other hand, deleteBook should send single onNext event containing deleted book after some delay.</p><p>Let’s write some pseudocode for our DummyApi which will simulate this behavior:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5cb5df4f76446e2803267d82c15de79/href">https://medium.com/media/d5cb5df4f76446e2803267d82c15de79/href</a></iframe><h3>Choosing Application Architecture</h3><p>In our example, we are going to use simplified MVVM architecture. We won&#39;t go too deep into details but it basically means controller will send any UI events to ViewModel and transform state coming out from it into UI representation.</p><p>One of the greatest things about this approach is the fact that ViewModel might be presented as a simple function of inputs (in our case: swipe-to-delete event and getBooks observable, but might be expanded to reordering, button clicks etc.) and returning output (in our case: list of Books).</p><p>It allows testing complex scenarios without writing any User Interface tests, as UIViewController is not responsible for core logic of our app.</p><h3>Designing our observables</h3><p>Let’s bring our ViewModel into life:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3b827b1bde2968776b8a8e7fbb80734/href">https://medium.com/media/f3b827b1bde2968776b8a8e7fbb80734/href</a></iframe><p>We declared ViewModel with two inputs:</p><ul><li>api: which represents remote source of user favorite books,</li><li>deleteCommand: bridge between UIViewController and ViewModel which allows controller to &quot;tell&quot; that user swiped UITableViewCell and clicked on delete button.</li></ul><p>Cell is represented by its position in a table — row and section. For simplicity, we are going to assume there&#39;s only one section and use row (index) only.</p><p>Our view controller needs only one thing — list of books which are going to be displayed in UITableView. That&#39;s why we declared items observable.</p><h3>Implementing delete functionality</h3><p>Our first challenge is to determine how to convert cell position on a UI level (IndexPath.row) to actual model (Book) and then pass it to our deleteBook method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa03d57088111338640667741b95076c/href">https://medium.com/media/fa03d57088111338640667741b95076c/href</a></iframe><p>Everyone loves that <em>there must be operator for it</em> feeling while working with RxSwift.<br> Since we have to combine elements of two observables - deleteCommand and items - first thing which comes to our mind is <a href="http://reactivex.io/documentation/operators/combinelatest.html">combineLatest</a>.</p><p>As docs says:</p><blockquote>when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function</blockquote><p>Is it right guy for our case?<br> Let’s think about this scenario:</p><ol><li>We fetch list of 5 books,</li><li>User wants to delete first book,</li><li>combineLatest { rowIndex, currentBooks in } will be called with 0 and books 1-5,</li><li>We can get book1 by calling currentBooks[rowIndex]</li><li>We call our deletion method, which eventually lead to onNext event from items observable with latest version of user&#39;s list - books 2-5</li><li>combineLatest gets called again since there new item coming from one of the observables!</li><li>No profit.</li></ol><p>Only reason to do any work is element emitted by deleteCommand, not either of observables.</p><p>That is why <a href="https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observables/WithLatestFrom.swift">withLatestFrom</a> becomes handy:</p><blockquote>Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.</blockquote><p>Once we got event with indexPath intented for deletion, we can transform it to a book by using latest &quot;version&quot; of items:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/325376a9c4863aead9a3c13154c1b5cc/href">https://medium.com/media/325376a9c4863aead9a3c13154c1b5cc/href</a></iframe><p>Last thing which we have to do is simply pass a book return by withLatestFrom operator into our API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0354228e60156a8fe5724629db2a3aa2/href">https://medium.com/media/0354228e60156a8fe5724629db2a3aa2/href</a></iframe><h3>Hooking up UI</h3><p>We want our UITableView to actively listen to items returned by observable and display them in a default UITableViewCells. In addition, every time item got deleted by it we want to have nice go-away animation. What&#39;s more... we do not want to write too much code to cover this functionality.</p><p>Good news we can use another gem from RxSwift community - <a href="https://github.com/RxSwiftCommunity/RxDataSources">RxDataSources</a>.</p><p>We have to create some helper structs in order to adapt our books collection into world of UITableView and RxTableViewSectionedAnimatedDataSource which will bind Book into UITableViewCell:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a335942d4687b791a303dafa8c0d5b7d/href">https://medium.com/media/a335942d4687b791a303dafa8c0d5b7d/href</a></iframe><p>Now we are ready to create our UIViewController, which will map items returned from view model into single table view section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f3ba6f693f462106337c43542e5e69/href">https://medium.com/media/b0f3ba6f693f462106337c43542e5e69/href</a></iframe><p>After running our app we should feel really proud:</p><figure><img alt="inital state" src="https://cdn-images-1.medium.com/max/1024/0*cQpew36E2Y642R2t.png" /></figure><p>If we swipe cell left and click on delete obviously nothing happens, since we have not connected this event with our view model.</p><p>It is done with help of itemDeleted (which emits IndexPath elements) observable coming from UITableView.rx extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7048824e060cb6f1f1189d31c3294f8/href">https://medium.com/media/a7048824e060cb6f1f1189d31c3294f8/href</a></iframe><p>After running app again and deleting any of the book we should be able to get rid of a whole list. After clicking on a delete, our dummy api.getBooks called, it modifies value coming from getBooks and it eventually updates our UI.</p><h3>Mission Complete?</h3><p>Although app is fully functional, UX designers might say that little delay between clicking on a delete button and table refresh is confusing for users. That’s caused by a fact we are fully relying on our API as a source of items displayed on a list.</p><p>Currently, deletion flow might represented by those steps:</p><figure><img alt="ux_flow" src="https://cdn-images-1.medium.com/max/1024/0*ERbb1V8jQvMEu3zd.png" /></figure><ol><li>We display initial state of a user’s books,</li><li>User swipes cell to the left and clicks on delete. Deletion request is sent to our API,</li><li>UITableView animates cell back to default state and it waits for updates from observable,</li><li>Once request is finished items emits onNext with reduced array and leads to updated UI.</li></ol><p>Step 3 is troublemaker here, we will try to polish UX by displaying array without deleted element right away after user interaction. Nicely, we can work on ViewModel source code without modifying single line from ViewController as it does not contain any kind of business logic.</p><h3>Improving UX</h3><p>We should consider two sources of elements in our list:</p><ul><li>Right after deletion we should emit current books minus unwanted book,</li><li>If our API emits any list of book we should accept it as current state regardless of its content. After deletion it should return the same array as we currently have without causing need to refresh UITableView.</li></ul><p>That brings notion of two possible actions represented by this BookCollectionAction enum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a685e383ad897b4931c3db659d0f1d0/href">https://medium.com/media/8a685e383ad897b4931c3db659d0f1d0/href</a></iframe><p>We also declare observable emitting those actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cf8fe494d4e50c3f628c0a58e922e89/href">https://medium.com/media/6cf8fe494d4e50c3f628c0a58e922e89/href</a></iframe><p>Now, we want to modify elements returned by our Observable&lt;[Book]&gt; by listening to those events with help of scan operator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39cb27f2991a26cf40a32d008792b161/href">https://medium.com/media/39cb27f2991a26cf40a32d008792b161/href</a></iframe><p>Lastly, we need to convert result of API.getBooks request and swipe-to-delete so they are going to emit our BookCollectionAction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bf5066ccec0acc258edfbc0a228a0da/href">https://medium.com/media/5bf5066ccec0acc258edfbc0a228a0da/href</a></iframe><p>Now when user swipes cell out it got deleted immediately and any collection coming from our “back-end” overwrites current state. Perfect.</p><h3>Polishing our code</h3><p>For sake of example we didn’t write any tests before implementing our app, so let’s try with sample one right now.</p><p>We’ll create ViewModel with mock API object, generate dummy IndexPath, push it into deleteCommand input and make sure that collection returned by items output does not include deleted cell.</p><p>First, we need to add RxTest and RxBlocking dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b67bbbb451ee2df4314273058ae9751/href">https://medium.com/media/2b67bbbb451ee2df4314273058ae9751/href</a></iframe><p>And create test case class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a1453a5e1c015ba43702c5bfda8e92/href">https://medium.com/media/64a1453a5e1c015ba43702c5bfda8e92/href</a></iframe><p>Now we are ready to start implementing our scenario, where we want to emit IndexPath pointing into row 0 and make sure it&#39;s reflected in collection elements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a488979b713184daa6f9477c4fb02329/href">https://medium.com/media/a488979b713184daa6f9477c4fb02329/href</a></iframe><p>Although we see green checkmark indicating passed test, we should not be satisfied with one simple happy path and create tests for some edge cases.</p><h3>Conclusion</h3><p>Even such sample scenario brought some UX dilemmas and coding challenges. We represented state of collection (item was swiped out, items were fetched from back end) as an enum which allowed us to put all of logic into ViewModel without referencing any UI elements. That helps a lot with creating short and clean test cases.</p><p>We saved a lot of time for writing boilerplate UITableViewDataSource and UITableViewDelegate code with help of simplified API coming from RxDataSources.</p><p>Code for this example is available <a href="https://github.com/pzmudzinski/RxDelete">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce8ae0aa920" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>