<?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 Jonathan Turnock on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Turnock on Medium]]></description>
        <link>https://medium.com/@jonathan.turnock?source=rss-323399d91362------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vhQdQa4JHRcA3ghhMKSJDw.jpeg</url>
            <title>Stories by Jonathan Turnock on Medium</title>
            <link>https://medium.com/@jonathan.turnock?source=rss-323399d91362------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathan.turnock/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[The “Unit” Lie: Why Testing in Isolation is Breaking Your Code]]></title>
            <link>https://medium.com/@jonathan.turnock/the-unit-lie-why-testing-in-isolation-is-breaking-your-code-b82a35327858?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82a35327858</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 14:25:09 GMT</pubDate>
            <atom:updated>2026-01-03T14:27:51.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SYMWJtSHQJgWOQsZJvFYA.png" /></figure><p>If your unit tests map 1:1 to your classes, you are likely writing “change detectors,” not tests. A “unit” isn’t a single function or class, it’s a behaviour. By redefining your testing boundaries around subsystems rather than implementation details, you can write tests that survive refactoring.</p><h4>The Trap of “Pure” Isolation</h4><p>We have all been there. You write a new feature, and you want to be a “good citizen,” so you write a unit test. You have a UserService that depends on a UserRepository and an EmailNotifier.</p><p>Following the “isolation” rule, you mock the repository. You mock the notifier. You assert that repository.save() was called exactly once with specific arguments.</p><h4>The Result?</h4><p>You haven’t tested that the user was created. You’ve tested that the implementation of the user creation specifically calls save().</p><p>If you later decide to split save() into saveProfile() and saveSettings(), your code works, but your test fails. This is crystallisation: your tests have hardened around your implementation details, making refactoring painful.</p><blockquote>The Better Definition: A Unit is a Behaviour</blockquote><p>Let’s flip the script. Instead of asking “Does this class do its job in a vacuum?”, ask: “Does this subsystem provide the correct API response?”</p><p>A unit is not a class; a unit is a collection of collaborators that work together to deliver a result.</p><h4>The Comparison</h4><p>The (Isolated/Mockist): Focuses on plumbing and logic.</p><pre>// ❌ Testing the implementation<br>it(&#39;should call repository.save&#39;, () =&gt; {<br> const mockRepo = new MockRepo();<br> const service = new UserService(mockRepo);<br> <br> service.register(&quot;john@example.com&quot;);<br> <br> // If we change the internal logic of how we save, this breaks.<br> expect(mockRepo.save).toHaveBeenCalledWith(&quot;john@example.com&quot;); <br>});</pre><p>The (Sociable/Behavioural): Focuses on the orchestration and outcome.</p><pre>// ✅ Testing the behavior<br>it(&#39;should allow a registered user to be retrieved&#39;, () =&gt; {<br> // Use a real (in-memory) adapter, not a mock function<br> const repo = new InMemoryUserRepository(); <br> const service = new UserService(repo);<br> <br> const userId = service.register(&quot;john@example.com&quot;);<br> <br> // We don&#39;t care HOW it saved, only that the data is there.<br> const user = service.getUser(userId);<br> expect(user.email).toBe(&quot;john@example.com&quot;);<br>});</pre><p>In the second example, you can completely rewrite the internals of UserService or the UserRepository interface. As long as the public API remains the same, the test passes.</p><p>Its important to understand when to employ each approach to testing. Both can be valuable in different scenarios.</p><h4>Enabling the Strategy: Hexagonal Architecture</h4><p>You might be thinking, “But I can’t use a real database in a unit test! It’s too slow!”</p><p>This is where Hexagonal Architecture (or Ports and Adapters) becomes your testing superpower. It allows you to treat your storage not as a hard dependency, but as a plugin.</p><ol><li>Define the Port.<br>The “Port” is the interface. It defines what needs to happen, not how.</li><li>Build the Adapters<br>You build two versions of the “Adapter”:<br>- The Real Adapter: Uses PostgreSQL/MySQL (used in Production).<br>- The Test Adapter: Uses a HashMap/Array (used in Testing).</li><li>The Test Boundary</li></ol><p>Your unit test now wraps the entire hexagon (the domain logic and the service layer). You inject the in-memory adapter into the subsystem.</p><p>This setup runs in milliseconds (like a unit test) but gives you the confidence of an integration test. You are testing the “Application Core” in isolation from the “Infrastructure,” rather than testing the “Class” in isolation from the “Class.”</p><h4>Deep Dive: “Solitary” vs. “Sociable” Tests</h4><p>If you want the academic terms for this shift, you are moving from Solitary Unit Tests to Sociable Unit Tests.</p><ul><li>Solitary (The “Mockist” or <strong>London</strong> School): <br>Every dependency is mocked. Great for enforcing strict architectural boundaries, but leads to the crystallization problem mentioned earlier.</li><li>Sociable (The “Classicist” or <strong>Detroit</strong> School): <br>Dependencies are used directly unless they are “expensive” (like DBs or APIs).</li></ul><h4>Summary</h4><ul><li>Stop mocking internal collaborators. If Class A calls Class B, test them together.</li><li>Mock only the I/O. Database, Network, File System.</li><li>Use In-Memory Adapters. They bridge the gap between speed and behavior verification.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82a35327858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Created the Open Domain Specification]]></title>
            <link>https://medium.com/@jonathan.turnock/why-i-created-the-open-domain-specification-73bd488032c0?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bd488032c0</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 14:34:38 GMT</pubDate>
            <atom:updated>2025-08-20T14:34:38.380Z</atom:updated>
            <content:encoded><![CDATA[<p>As a principal engineer, one of my biggest responsibilities has always been ensuring that teams don’t just <em>build</em>, but build in a way that moves us collectively toward a shared vision. On paper, that sounds straightforward. In practice, it’s anything but.</p><p>Teams face challenges like miscommunication, misaligned vocabulary, and a lack of shared understanding. Even the most skilled developers can head off in different directions if we don’t establish a common foundation for <em>what</em> we’re building and <em>why</em>.</p><p>This is where <strong>Domain-Driven Design (DDD)</strong> has long been a powerful tool. DDD isn’t just about coding patterns, it’s about tackling complexity through a shared language, clear boundaries, and alignment between business needs and software architecture. It gives us a framework to reason about systems in terms of the problem domain itself, not just implementation details.</p><h3>From Human Teams to Autonomous Agents</h3><p>But we’re now in an era where the landscape is shifting dramatically. Generative AI and autonomous coding agents are entering the scene. These agents, in many ways, resemble a headless engineering team: highly capable, fast, and tireless , but equally susceptible to the very same pitfalls we’ve seen in human teams.</p><p>Without a clear shared vocabulary, without an aligned domain vision, AI coding agents risk producing in-cohesive scripts and fragmented solutions, outputs that may be impressive in isolation but don’t converge on the intended product.</p><p>And so the same lessons we’ve learned in leading teams apply here too. Just as humans need a blueprint, so do our agents.</p><h3>Introducing the Open Domain Specification</h3><p>That’s why I created the <a href="https://docs.open-ds.io/docs/llm-context"><strong>Open Domain Specification (OpenDS)</strong></a>.</p><p>OpenDS is more than a script definition. It’s a <strong>blueprint</strong>, a way of laying the foundations for coherent, aligned development, whether the builders are people or AI agents. It enables us to express domain models, bounded contexts, and the relationships between them in a way that guides autonomous development toward outcomes that match the forecasted vision.</p><p>In other words, it helps ensure that the product you get at the end of a development cycle, be it from a human team, an AI agent, or a combination of both, <em>actually aligns</em> with the strategic intent you set at the beginning.</p><h3>Why This Matters in the Age of AI</h3><p>Satya Nadella, Microsoft’s CEO, recently put it this way:</p><blockquote><strong><em>“The path to being that software architect gets speeded up. All of us are going to be more software architects.”</em></strong></blockquote><p>He’s pointing to a real shift, AI accelerates the move from just writing code to shaping the structure and intent behind systems. But being an architect has never been about elegance alone. It’s about forethought, domain clarity, and creating the conditions for teams, or agents, to build something cohesive and lasting.</p><p>That’s exactly why I created the <strong>Open Domain Specification</strong>. It’s a way to capture that clarity up front, to establish a shared vocabulary and structure so the outcome, whether built by humans, AI agents, or both, matches the vision.</p><p>As we enter this new era of autonomous development, Nadella’s words ring true: we’re all becoming architects. And architecture, at its core, is still about turning foresight and domain design into durable, aligned products. OpenDS is my contribution to making that possible.</p><p>If you’d like to explore more, check out the <a href="https://docs.open-ds.io/docs/llm-context">OpenDS documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bd488032c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session Sharing in Node.js & Express]]></title>
            <link>https://medium.com/@jonathan.turnock/seamless-session-sharing-in-node-js-express-1d1807ff4836?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d1807ff4836</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[express-session]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 23:35:48 GMT</pubDate>
            <atom:updated>2025-08-20T14:36:14.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web applications often split their architecture into microfrontends (MFE) for the user interface and separate services for backend APIs. While this modular approach has its advantages in scalability and maintainability, it presents unique challenges. One such challenge is managing user sessions across these decoupled systems. This tutorial will guide you through the process of sharing sessions between a microfrontend and an API in a Node.js environment.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#understanding-the-architecture">Understanding the Architecture</a></h3><p>Let’s start by exploring the architecture of our sample application. We have two main components:</p><ul><li>Web Server (app.js): This is our frontend server that serves the HTML pages and deals with user sessions.</li><li>API Server (api.js): This is our backend server that the frontend consumes. It relies on a valid session initiated by the web server.</li></ul><p>Both servers are Express.js applications, and we use MongoDB as our session store for its flexibility and ease of use in distributed systems.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#session-management-with-express-session">Session Management with express-session</a></h3><p>The express-session middleware is instrumental in handling session data. Let’s see how we’ve configured it for both servers.</p><p>On the Web Server (app.js):</p><pre>app.use(<br>  session({<br>    name: config.sessionCookieName,<br>    secret: config.sessionCookieSecret,<br>    store: config.sessionStore,<br>    resave: true,<br>    saveUninitialized: true,<br>  })<br>);</pre><p>In the snippet above, we initialize the session middleware. We specify a cookie name and a secret for signing the session ID. store is set to use MongoDB through connect-mongo, allowing our sessions to be stored in a centralized database.</p><p>On the API Server (api.js):</p><pre>app.use(<br>  session({<br>    name: config.sessionCookieName,<br>    secret: config.sessionCookieSecret,<br>    store: config.sessionStore,<br>    saveUninitialized: false,<br>    resave: false,<br>  })<br>);</pre><p>For the API server, the configuration is similar, but saveUninitialized is set to false to prevent creating sessions for unauthenticated requests.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#signing-cookies-for-secure-transmission">Signing Cookies for Secure Transmission</a></h3><p>When a session is initiated on the web server, a cookie is created and needs to be transmitted securely to the API server. Here’s how we sign the cookie using cookie-signature:</p><p>In utils.js:</p><pre>const signedSessionId = `s:${sign(req.sessionID, config.sessionCookieSecret)}`;</pre><p>This code signs the session ID from the request with our secret, creating a secure token that the client can use to authenticate with the API.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#middleware-for-session-validation">Middleware for Session Validation</a></h3><p>Before the API processes any request, we must ensure that a valid session exists. We’ve created a middleware called withSession for this purpose.</p><pre>const withSession = (req, res, next) =&gt; {<br>  if (req.session.username) {<br>    next();<br>  } else {<br>    res.status(401).send(&quot;Unauthorized&quot;);<br>  }<br>};java</pre><p>This middleware checks if the username exists in the session. If not, it sends a 401 Unauthorized response.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#the-user-flow">The User Flow</a></h3><p>Now let’s look at the user flow with a bit more detail:</p><p><strong>User Visits Web Server</strong>: When a user accesses the web server, a session is initiated and stored in MongoDB.</p><pre>app.use((req, res, next) =&gt; {<br>  if (!req.session.username) {<br>    req.session.username = crypto.randomUUID();<br>  }<br>  next();<br>});</pre><p><strong>Fetching Data from API Server</strong>: The web server makes a request to the API, passing along the signed session cookie in the headers.</p><pre>axios.get(&quot;http://localhost:3001/api&quot;, {<br>  headers: getSessionHeaders(req)<br>});</pre><p><strong>API Server Validates Session</strong>: The API server receives the request, validates the session using the middleware, and responds with data.</p><pre>app.use(&quot;/api&quot;, withSession, (req, res) =&gt; {<br>  res.send({ status: &quot;OK&quot;, views: req.session.views });<br>});</pre><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#dockerizing-the-environment">Dockerizing the Environment</a></h3><p>For convenience, we’ve dockerized our MongoDB setup. Here’s a snippet of the docker-compose.yml configuration:</p><pre>services:<br>  mongo:<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br>    volumes:<br>      - mongodb_data_container:/data/db</pre><p>With Docker, starting the database is as simple as running docker-compose up -d.</p><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#running-the-example">Running the Example</a></h3><p>To run our example, clone the repository and install the dependencies. Then, use Docker to spin up the MongoDB container, and start the servers:</p><pre>npm start # starts the web server on port 3000<br>npm run start:api # starts the API server on port 3001</pre><h3><a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store/blob/main/BLOG.md#wrapping-up">Wrapping Up</a></h3><p>Through this tutorial, you’ve seen how to configure a Node.js application to share session data between a microfrontend and an API server using MongoDB.</p><p>By following the steps outlined here, you can ensure that your modular application components maintain a cohesive session state, providing a seamless user experience across your entire platform.</p><p>Implementing a shared session store within a partitioned monolith architecture, as highlighted in our Node.js application, offers a strategic benefit, particularly when compared to a microservices architecture that might opt for a stateless token approach.</p><p>This method allows session management within the partitions of a monolith without having to adopt and maintain complex architecture, allowing for a seamless user experience and simplified server-side handling. While bearer tokens are well-suited to fully decoupled microservices, a shared session store is more similar for systems where the various components are more tightly integrated but still need to maintain a level of independence, such as in a partitioned monolith.</p><p>It provides a balanced solution that supports both isolated service development and unified session management.</p><p>Needless to say careful control should be maintained of data within the session store to ensure each application is not reaching and relying on loosely coupled contracts.</p><p>the full example is accessible on github @ <a href="https://github.com/JonathanTurnock/mfe-api-shared-session-store">https://github.com/JonathanTurnock/mfe-api-shared-session-store</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d1807ff4836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging PartiQL with AWS DynamoDB in JavaScript]]></title>
            <link>https://medium.com/@jonathan.turnock/leveraging-partiql-with-aws-dynamodb-in-javascript-3d74ff81096c?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d74ff81096c</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 11:49:05 GMT</pubDate>
            <atom:updated>2023-07-26T11:49:26.844Z</atom:updated>
            <content:encoded><![CDATA[<p>In this short, we walk through an example of using the AWS SDK to interact with DynamoDB in a JavaScript project. Specifically, this code allows us to create a DynamoDB table, populate it with data, and then perform a query to retrieve data using PartiQL.</p><p>DynamoDB, Amazon’s NoSQL database service, is known for its low-latency and flexibility. However, for developers transitioning from SQL-based databases, it could initially feel challenging to interact with DynamoDB because it doesn’t natively use SQL syntax. Amazon has tackled this by introducing PartiQL, a SQL-compatible query language, which can be used to execute commands against DynamoDB.</p><p>Our code example begins by setting up a DynamoDB instance with a specific localstack endpoint and region config. We also define a function, executeSql, which is a generic function to execute SQL-like statements using PartiQL against DynamoDB. This function sends the provided statement and parameters to DynamoDB, converts the DynamoDB items back to regular JavaScript objects, and returns them.</p><p>In our main function, we create a DynamoDB table with a primary key of “id” and a global secondary index on “uuid”. The creation of this table allows for quicker lookups and querying of data based on either the ‘id’ or ‘uuid’. After creating the table, we generate five unique items and insert them into the table using the putItem function.</p><p>Finally, we use our executeSql function to retrieve and log one of the items we just inserted. We leverage PartiQL’s SQL-like syntax to write a SELECT statement that gets an item from the table based on its ‘uuid’.</p><p>This example demonstrates the power of PartiQL when working with DynamoDB in a JavaScript project. Developers familiar with SQL can now apply their knowledge to DynamoDB, opening the door to greater flexibility and efficiency in querying and managing data in DynamoDB.</p><p><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html">https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.html</a></p><pre>// AWS SDK package for DynamoDB<br>import { DynamoDB } from &quot;aws-sdk&quot;;<br>// Importing the &#39;times&#39; function from lodash library<br>import { times } from &quot;lodash&quot;;<br>// Importing crypto library for generating unique id<br>import * as crypto from &quot;crypto&quot;;<br><br>// Creating a DynamoDB instance with specific endpoint and region<br>const dynamo = new DynamoDB({<br>	endpoint: &quot;http://localhost:4566&quot;,<br>	region: &quot;eu-west-2&quot;,<br>});<br><br>// Defining the name of the table we&#39;ll be working with<br>const TableName = &quot;MyTestTable&quot;;<br><br>// Function to execute SQL-like statements against a DynamoDB instance<br>async function executeSql&lt;T = any&gt;(Statement: string, Parameters: (number | string)[]): Promise&lt;T[]&gt; {<br>	// Sending the Statement with Parameters to the DynamoDB instance<br>	const { Items } = await dynamo<br>		.executeStatement({ Statement, Parameters: Parameters.map((it) =&gt; DynamoDB.Converter.input(it)) })<br>		.promise();<br><br>	// If no rows are returned, return an empty array<br>	if (!Items) return [];<br><br>	// Converting the DynamoDB items back to regular JavaScript objects and returning<br>	return Items.map((it) =&gt; DynamoDB.Converter.unmarshall(it)) as T[];<br>}<br><br>// Main async function<br>const main = async () =&gt; {<br>	// Create a table in DynamoDB<br>	await dynamo<br>		.createTable({<br>			TableName,<br>			AttributeDefinitions: [<br>				{ AttributeName: &quot;id&quot;, AttributeType: &quot;N&quot; },<br>				{ AttributeName: &quot;uuid&quot;, AttributeType: &quot;S&quot; },<br>			],<br>			KeySchema: [{ AttributeName: &quot;id&quot;, KeyType: &quot;HASH&quot; }],<br>			BillingMode: &quot;PAY_PER_REQUEST&quot;,<br>			GlobalSecondaryIndexes: [<br>				{<br>					IndexName: &quot;gsi_uuid&quot;,<br>					KeySchema: [{ AttributeName: &quot;uuid&quot;, KeyType: &quot;HASH&quot; }],<br>					Projection: {<br>						ProjectionType: &quot;ALL&quot;,<br>					},<br>				},<br>			],<br>		})<br>		.promise()<br>		// Log success message if table creation is successful<br>		.then(() =&gt; console.log(`Successfully Created ${TableName}`))<br>		// Log error message if table creation fails<br>		.catch((error) =&gt; console.error(error.message));<br><br>	// Creating 5 objects with id and uuid<br>	const Items = times(5, (idx) =&gt; ({ id: idx + 1, uuid: crypto.randomUUID() }));<br>	// Add these 5 objects to the DynamoDB table<br>	await Promise.all(<br>		Items.map((Item) =&gt; dynamo.putItem({ TableName, Item: DynamoDB.Converter.marshall(Item) }).promise())<br>	);<br><br>	const [Item1] = Items;<br><br>	// Select and log a single item from the DynamoDB table based on uuid<br>	await executeSql(`select * from &quot;${TableName}&quot; where uuid = ?`, [Item1.uuid])<br>		.then((data) =&gt; console.log(data))<br>		.catch((error) =&gt; console.log(error));<br>};<br><br>// Call the main function<br>main();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d74ff81096c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top library picks for J/TS Web Development in 2023]]></title>
            <link>https://medium.com/@jonathan.turnock/top-library-picks-for-j-ts-web-development-in-2023-227653cb9c76?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/227653cb9c76</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 13:43:29 GMT</pubDate>
            <atom:updated>2023-01-03T13:57:46.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AH0HTxRpSmAOMIiqOmxBMQ.jpeg" /></figure><p>This is a short and sweet collection of some of my favourite libraries after half a decade of web development.</p><p>Going to skip the big frameworks here, this is the small stuff that you write yourself until someone tells you that’s been done.</p><h3>React Use</h3><p>Awesome collection of react hooks I wish I knew about this sooner.</p><p><a href="https://www.npmjs.com/package/react-use">react-use</a></p><h3>RXJS</h3><p>Events can get quite unwieldy. Combining the react-use useObservable and Rxjs can clean things up nicely.</p><p><a href="https://www.npmjs.com/package/rxjs">rxjs</a></p><h4>Lodash</h4><p>Controversial for some because of the size, but for me it’s essential and tree shaking really makes it a non-issue.</p><p><a href="https://www.npmjs.com/package/lodash">lodash</a></p><h3>Aigle</h3><p>When you need to deal with a lot of async loops etc this is a real time saver. It’s like Lodash for promises.</p><p><a href="https://www.npmjs.com/package/aigle">aigle</a></p><h3>Formik</h3><p>If you&#39;re dealing with forms this is the way!</p><p><a href="https://www.npmjs.com/package/formik">formik</a></p><h3>Zod</h3><p>For easy runtime validation try Zod. Another favourite is Ajv but that’s more specific for api gateways where performance is key.</p><p>https://www.npmjs.com/package/zod</p><h3>Ow</h3><p>Sometimes you just need to assert arguments are valid. Protect your boundaries.</p><p><a href="https://www.npmjs.com/package/ow">ow</a></p><h3>Pupa</h3><p>For quick and simple string templating</p><p><a href="https://www.npmjs.com/package/pupa">pupa</a></p><h3>RXDB</h3><p>A bit of a random addition for this list but I think it’s a great tool for creating offline first apps.</p><p><a href="https://www.npmjs.com/package/rxdb">rxdb</a></p><p>That’s it from me, it’s not exhaustive but these are my go-to libraries for a bunch of common problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227653cb9c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging Express Request & Response Content]]></title>
            <link>https://medium.com/@jonathan.turnock/logging-express-request-response-content-ead42620d4e5?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead42620d4e5</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Mon, 26 Oct 2020 23:23:47 GMT</pubDate>
            <atom:updated>2020-10-27T22:34:50.887Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://jonathanturnock.github.io/blog/express-request-and-response-logging">Express Request &amp; Response Logging | Jonathan Turnock</a></p><p>While Logging the Request object in Express is amazingly easy, doing so with the response is not quite as straight forwards.</p><p>We need to utilize a couple of tricks and some patching to get things working smoothly and get all the information we are sending back to the client.</p><p>We can also use this technique to perform some other manipulation rather than just logging, some use cases might be:</p><ol><li>To Observe the response (Logging, Tracing)</li><li>To Amend the response (Redacting information by origin for example or modify response for target audience)</li></ol><h3>The Middleware</h3><h4>Logging the Request</h4><p>Firstly we need to create a basic middleware which can log our req, nothing new here other than our middleware is a higher order function which takes a logger making it more re-usable.</p><pre>const requestLoggerMiddleware = ({ logger }) =&gt; (req, res, next) =&gt; {<br>  logger(&quot;RECV &lt;&lt;&lt;&quot;, req.method, req.url, req.hostname);<br>  ...<br>  next();<br>};</pre><h4>Logging the Response</h4><p>Next we need to log our response. As we can see we have access to the response under the reference res. However, this does not have the information we need yet.</p><p>Our middleware runs BEFORE our router, so if we call for any information on our res now it will not be reflective of the res state after the router has done its thing.</p><p>We need to add an event hook to be invoked after the finish event, more info on this event can be found in the docs: <a href="https://nodejs.org/api/http.html#http_event_finish">https://nodejs.org/api/http.html#http_event_finish</a></p><p>Crucially however we need to be aware of the purpose of the event</p><blockquote><em>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.</em></blockquote><pre>const requestLoggerMiddleware = ({ logger }) =&gt; (req, res, next) =&gt; {<br>   ...<br>   res.on(&quot;finish&quot;, () =&gt; {<br>     logger(&quot;SEND &gt;&gt;&gt;&quot;, res.statusCode);<br>   });<br>   next();<br>};</pre><p>This gives us the basic ability to observe information about the response after handoff, good for observability but bad for interception, and the res is also missing the crucial content sent to res.send</p><h4>Intercepting res.send</h4><p>For this last piece we need to monkey patch the res.send method. This means when we call it in our router, for example:</p><pre>app.get([&quot;/&quot;, &quot;/api/health&quot;], (req, res) =&gt; {<br>   res.send({ message: &quot;OK&quot;, uptime: process.uptime() });<br>});</pre><p>We are actually going to be calling our patched res.send, doing something, then calling the original res.send. We call this the interceptor because it&#39;s intercepting the call , performing some actions and handing back off.</p><p>This is going to give us a critical point to interject and do whatever we need. For observability , we will simply bind the content passed to res.send to the res under res.contentBody giving us access later, but you could just as easily perform some mutation and intercept the content for redacting, modifying, adapting etc.</p><p>Let’s add the interceptor and explain it’s signature.</p><pre>const requestLoggerMiddleware = ({ logger }) =&gt; (req, res, next) =&gt; {<br>   ...  <br>   res.send = resDotSendInterceptor(res, res.send);<br>   ...<br>   next();<br>};</pre><p>We can see how the interceptor replaces the default res.send, as this middleware runs <em>BEFORE</em> our router. We know that this patch is now in place and any subsequent calls to res.send will go via our interceptor.</p><h4>Designing the interceptor</h4><p>Our interceptor needs two things:</p><ol><li>To be a function that can take the content sent to res.send normally</li><li>To be a function which ultimately calls the original res.send so the request/response chain can complete naturally.</li></ol><p>Therefore, we write our interceptor as a Higher Order Function taking the res, and the original unmodified send. Finally, that returns a function which takes the content passed to res.send in the router.</p><pre>const resDotSendInterceptor = (res, send) =&gt; (content) =&gt; {<br> res.contentBody = content;<br> res.send = send;<br> res.send(content);<br>};</pre><p>By the time the rouer has called res.send and the request finish event is broadcast, our interceptor has put the content passed to res.send in the router onto our res under the field contentBody making this now accessible in the finish callback.</p><pre>const requestLoggerMiddleware = ({ logger }) =&gt; (req, res, next) =&gt; {<br> ...<br> res.on(&quot;finish&quot;, () =&gt; {<br>   logger(&quot;SEND &gt;&gt;&gt;&quot;, res.contentBody);<br> });<br> next();<br>};</pre><h3>Conclusion</h3><p>While the topic at first can seem quite confusing I highly recommend taking a look at the middleware and app discussed above.</p><p>Checkout the project on <a href="https://github.com/JonathanTurnock/ReqResLoggingExample">Github</a> to see things running.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead42620d4e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express & GraphQL with Typescript in 3 steps]]></title>
            <link>https://medium.com/@jonathan.turnock/express-graphql-with-typescript-in-3-steps-3a50aa42cf5e?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a50aa42cf5e</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 22:06:21 GMT</pubDate>
            <atom:updated>2020-10-27T23:28:42.345Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post were going to bootstrap an Express application, bung on typescript and get GraphQL up and running in no time at all. 🚀</p><p>All the code discussed and given as examples is available in the repo and I encourage you to checkout the article tag for a nice snapshot.</p><p><a href="https://github.com/JonathanTurnock/express-ts-graphql-template/tree/article-v1.0.0">https://github.com/JonathanTurnock/express-ts-graphql-template/tree/article-v1.0.0</a></p><p>We will be using <strong>ts-node</strong> in this example, it allows us to run typescript directly without any additional boilerplate 🤯. Feel free to add in transpiling if necessary 😒.</p><h3>What we’ll get?</h3><ul><li>Typescript at the core</li><li>Tests run with Jest</li><li>Standard familiar Express app</li><li>GraphQL <strong>Query</strong>, <strong>Mutation </strong>and <strong>Subscriptions </strong>via Websockets</li><li>GraphQL Playground</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRjiG5aK2q4vwZrZxeXpjg.png" /><figcaption>GraphQL Playground</figcaption></figure><h3>Step 1: Generating a boilerplate Express App</h3><p>First up we generate a boilerplate Express application, I’ve used the Jetbrains Webstorm IDE, but you can just as easily run the command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikWEUGr_qzXxZsfKYA84Vw.png" /></figure><pre>npx --package express-generator express</pre><p>Checkout this <a href="https://github.com/JonathanTurnock/express-ts-graphql-template/commit/b8f52b2026b0c45243418e2d63c5ebcd75f1d60f">Commit </a>to see changes involved in this step</p><p>I also switch to using yarn over npm but that’s just preference.</p><pre>npm install -g yarn</pre><h3>Step 2: Converting the Express App to use ts-node</h3><p>Next up we switch from using <strong>js </strong>to <strong>ts </strong>and add ts-node you could leave the files as they are, they don’t need to be switched but I prefer to keep things consistent.</p><p>First, install typescript, ts-node and for good measure get prettier added. If your IDE supports it run prettier on save. <a href="https://prettier.io/docs/en/editors.html">🔗 Prettier | Editor Integration</a></p><pre>yarn add typescript ts-node prettier</pre><p>Move the generated file for the server from bin/www to server.ts and change imports to use ES6 syntax replacing <strong>require </strong>statements for <strong>imports </strong>and the <strong>var</strong> for <strong>let</strong>/<strong>const</strong></p><p>Update the <strong>package.json</strong> to start the application with ts-node rather than node</p><pre>&quot;scripts&quot;: {<br>    - &quot;start&quot;: &quot;node ./bin/www&quot;<br>    + &quot;start&quot;: &quot;ts-node ./server.ts&quot;<br>},</pre><p>Add a tsconfig.json in the project root file with some minimal bits</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;module&quot;: &quot;CommonJS&quot;,<br>    &quot;target&quot;: &quot;ES6&quot;,<br>    &quot;sourceMap&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;allowJs&quot;: true<br>  },<br>  &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><p>You should now have a project that’s almost ready with:</p><ul><li><strong>bin/www</strong> now in the root as <strong>server.ts</strong></li><li><strong>app.js</strong> as <strong>app.ts</strong></li><li>new <strong>tsconfig.json</strong></li><li>Optionally converted the routes to <strong>.ts</strong> files</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSA-7kVG2JzEvWIbnB1IUg.png" /></figure><p>If you’re having issues or want to see the internals/changes it’s in this <a href="https://github.com/JonathanTurnock/express-ts-graphql-template/commit/88fa2e818a2f1249e245cb97177763982bb0273d?branch=88fa2e818a2f1249e245cb97177763982bb0273d">Commit</a></p><p>Were going to make 2 more minor changes to make things ready for pulling in GraphQL</p><ol><li>Move the application Source Code under <strong>src</strong></li><li>Add a <strong>dev </strong>mode for the application to run with HMR</li></ol><p>First, add some useful dev mode items</p><pre>yarn add -D cross-env ts-node-dev</pre><p>cross-env let’s us declare environment variables across <strong>windows</strong>/<strong>osx </strong>&amp; <strong>unix</strong>, ts-node-dev will give us <strong>Hot Reloading</strong>.</p><p>With them in place update the <strong>package.json</strong> scripts adding a <strong>dev </strong>script</p><pre>&quot;dev&quot;: &quot;cross-env DEBUG=* ts-node-dev ./server.ts&quot;</pre><p>Fire the app up with yarn dev, we now have additional logging and hot reloading on changes.</p><p>Take a look at this set of changes in this <a href="https://github.com/JonathanTurnock/express-ts-graphql-template/commit/2438064a94039d74de7b340227a7d8f094e46cda">Commit</a></p><p>Secondly, move the <strong>routes </strong>folder, <strong>app.ts</strong> and <strong>server.ts</strong> into a new folder called <strong>src.</strong></p><p>Update the <strong>app.ts</strong> to point at the correct public folder now one folder above our <strong>src/app.ts</strong> in<strong> /public</strong></p><pre>- app.use(express.static(path.join(__dirname, &quot;public&quot;)));<br>+ app.use(express.static(path.join(__dirname, &quot;../public&quot;)));</pre><p>These changes are included in this <a href="https://github.com/JonathanTurnock/express-ts-graphql-template/commit/565b465155fc8bc1587abf07a0a6c4ca6f363121">Commit</a></p><h3>Step 3: Add GraphQL Endpoints</h3><p>Now for the big prize 🏆</p><p>We’re going to kick things off by adding apollo-server-express</p><pre>yarn add apollo-server-express </pre><p>We are going to use <strong>apollo-server</strong> to power our GraphQL server. More information on it can be found at <a href="https://www.apollographql.com/docs/apollo-server/#:~:text=Apollo%20Server%20is%20an%20open-source,%20spec-compliant%20GraphQL%20server,stand-alone%20GraphQL%20server,%20including%20in%20a%20serverless%20environment">🔗 apollographql.com</a></p><p>We also add jest in the commit to give us some confidence in the action handlers. Add it as necessary but I’ve removed the reference here as its out of scope.</p><p>In essence we are going to be creating a <strong>Subscription </strong>example, A <strong>Query </strong>example and a <strong>Mutation </strong>Example which actually causes an event to be published which our <strong>Subscription </strong>example can inform us of.</p><p>In terms of functionality we will implement:</p><ul><li><strong>Get </strong>the number of <em>likes </em>via a <strong>Query</strong></li><li><strong>Add </strong>a chosen number of <em>likes </em>via a <strong>Mutation</strong></li><li>Be notified any time the <em>likes </em>change via a <strong>Subscription</strong>.</li></ul><p>Pop these functions in your project under <strong>/src/actions/index.ts</strong> they will handle the <em>likes</em></p><pre>let likes: number = 0;</pre><pre>export const addLikes = (number: number): number =&gt; (likes = likes + number);</pre><pre>export const getLikes = (): number =&gt; likes;</pre><p>To bind this to GraphQL we will need 2 things, Firstly a <strong>Schema</strong>, Secondly <strong>Resolvers</strong>.</p><p>The <strong>Schema </strong>describes what is provided by our R<strong>esolvers</strong>, it describes our API, the <strong>Resolvers </strong>dispatch requests to our application code.</p><p>Under <strong>src/graphql</strong> add the <strong>resolvers.ts</strong></p><pre><em>import </em>{ PubSub } <em>from </em>&quot;apollo-server-express&quot;;<br><em>import </em>{ addLikes, getLikes } <em>from </em>&quot;../actions&quot;;<br><br><em>const </em>likes = <em>new </em>PubSub();<br><br><em>export const </em>resolvers = {<br>  RootQuery: {<br>    getLikes: () =&gt; getLikes(),<br>  },<br>  RootMutation: {<br>    addLikes: <em>async </em>(_, { count }) =&gt; {<br>      <em>const </em>newLikeCount = addLikes(count);<br>      <em>await </em>likes.publish(&quot;NEW_LIKE&quot;, { likes: newLikeCount });<br>      <em>return </em>newLikeCount;<br>    },<br>  },<br>  RootSubscription: {<br>    likes: {<br>      subscribe: () =&gt; likes.asyncIterator([&quot;NEW_LIKE&quot;]),<br>    },<br>  },<br>};</pre><p>Under <strong>src/graphql </strong>add the <strong>schema.ts</strong></p><pre><em>import </em>{ gql } <em>from </em>&quot;apollo-server-express&quot;;<br><br><em>export const </em>typeDefs = gql`<br>  schema {<br>    query: RootQuery<br>    mutation: RootMutation<br>    subscription: RootSubscription<br>  }<br><br>  type RootQuery {<br>    &quot;&quot;&quot;<br>    Get the current number of likes<br>    &quot;&quot;&quot;<br>    getLikes: Int<br>  }<br><br>  type RootMutation {<br>    &quot;&quot;&quot;<br>    Add a new like<br>    &quot;&quot;&quot;<br>    addLikes(count: Int): Int<br>  }<br><br>  type RootSubscription {<br>    &quot;&quot;&quot;<br>    Subscribe to new Like events as they occur<br>    &quot;&quot;&quot;<br>    likes: Int<br>  }<br>`;</pre><p><em>You&#39;ll notice there is a 1–2–1 relationship between the </em><strong><em>Schema </em></strong><em>and the </em><strong><em>Resolvers, </em></strong><em>this is necessary otherwise the application will fail to load.</em></p><p><em>When visiting </em><a href="http://localhost:3000/graphql"><em>http://localhost:3000/graphql</em></a><em> you’ll get the GraphQL playground, from here you can browse the schema and write queries/mutations and subscriptions.</em></p><p><em>Each time you run an action it gets sent to our server and GraphQL will see it, and hand off to the associated </em><strong><em>Resolver </em></strong><em>matching by name and signature.</em></p><p><strong><em>Queries </em></strong><em>are very simple and self explanatory.</em></p><p><strong><em>Mutations</em></strong><em> need to be async and inside function we deconstruct the second parameter matching names as we described in our schema. We can see in our example while calling our internal code to increment the likes we also call </em><em>likes.publish(&quot;NEW_LIKE&quot;, {likes: newLikeCount}) in this block we effectively push to the likes PubSub instance a new event. This is what our </em><strong><em>Subscription </em></strong><em>then watches and informs anyone subscribed that there is a new message.</em></p><p><strong><em>Subscriptions</em></strong><em> are also relatively self explanatory when you know that the schema defined name, in our case </em><strong><em>likes </em></strong><em>actually returns an object with a subscribe field which needs to be a function returning the </em><em>.asyncIterator([&quot;NEW_LIKE&quot;]) response. </em><a href="https://www.apollographql.com/docs/graphql-subscriptions/setup/#subscription-resolver"><em>🔗 Check the docs for additional information</em></a></p><p>Finally in our <strong>server.ts </strong>we need to wire GraphQL to our express app, add the imports and setup the server as below just under the http.createServer:</p><pre>...<br>import { ApolloServer } from &quot;apollo-server-express&quot;;<br>import { resolvers, typeDefs } from &quot;./graphql&quot;;<br>...<br><em>/**<br> * Create HTTP server.<br> */<br>const </em>server = http.createServer(app);<br><br><em>/**<br> * Setup the GraphQL Server<br> */<br>const </em>apolloServer = <em>new </em>ApolloServer({ typeDefs, resolvers });<br>apolloServer.applyMiddleware({ app });<br>apolloServer.installSubscriptionHandlers(server);</pre><p>Take a look at the full layout and tests in this <a href="https://github.com/JonathanTurnock/express-ts-graphql-template/commit/bf44d9338c2d99dff4f84205031cba608a228763">Commit</a></p><p>The working example of what we covered here is available in the Github repo and is a template that can be used as a base.</p><p><a href="https://github.com/JonathanTurnock/express-ts-graphql-template/tree/article-v1.0.0">https://github.com/JonathanTurnock/express-ts-graphql-template/tree/article-v1.0.0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a50aa42cf5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Linux GUI Apps in Windows WSL]]></title>
            <link>https://medium.com/@jonathan.turnock/using-linux-gui-apps-in-windows-wsl-e86203eafd5c?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86203eafd5c</guid>
            <category><![CDATA[kali]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[windows-10]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 21:26:10 GMT</pubDate>
            <atom:updated>2020-03-19T21:26:10.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrOcNx_AGaHDnsU-jqm-JQ.png" /></figure><p>I recently came across a little known feature of Windows WSL. The ability to launch GUI apps!</p><p>I’ve started doing much more of my environment management in WSL rather than Windows recently, excellent tools from Jetbrains and VSCode make coding in this environment a doddle.</p><p>While installing some packages I noticed that I accidentally installed a desktop environment, this got me thinking, would it be possible to run some GUI tools.</p><p><em>Turns out it is and its incredibly easy!</em></p><h3>Install XMing</h3><p>You will need an X11 display server for windows.</p><p>I personally used <a href="https://en.wikipedia.org/wiki/Xming">https://en.wikipedia.org/wiki/Xming</a>.</p><p>This allows the apps to be rendered on the screen.</p><p>You will need it running otherwise you’ll get errors like below:</p><pre>Error: Can&#39;t open display: :0</pre><p><strong>Ensure its up and running before proceeding.</strong></p><h3>Export Display Mapping</h3><p>Next you need to export your display mapping, add the following to your shell rc file.</p><p>i.e. if you use bash its <em>~/.bashrc</em> or if your running zShell its <em>~/.zshrc</em></p><pre>export DISPLAY=:0</pre><h3>Install some GUI tools</h3><p>Now we’ll install some GUI apps to see how things are looking!</p><pre>sudo apt-get install x11-apps</pre><p>Then we run:</p><pre>xeyes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1siELgaQte-lFgl8wvJihA.png" /><figcaption>Success!</figcaption></figure><p>From here on out go ahead an install whatever you could need! Below I will go over some examples of what I have found handy.</p><h3>Nautilus (File Explorer) &amp; GEdit (Text Editor)</h3><p>While you can just browse to the files on your windows machine, sometimes its nice to just open up an editor.</p><p>Install nautilus and gedit, then run it to see how well this works.</p><pre>sudo apt-get install -y nautilus gedit</pre><p>Then run nautilus on your current</p><pre>nautilus .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGbfdrkPN6Juo9w9jFn9CQ.png" /><figcaption>GEdit opened from Nautilus</figcaption></figure><h3>KDiff3 (GUI Diff Tool)</h3><p>KDiff3 is a handy little tool for visualizing differences, I sometimes use it to inspect commits, or to check for local changes</p><pre>git difftool --tool=kdiff3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ecRBfuvviI7uMPB-JGDLA.png" /><figcaption>KDiff3 showing previous commit</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86203eafd5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot & Docker for Busy Developers]]></title>
            <link>https://medium.com/@jonathan.turnock/spring-boot-docker-for-busy-developers-57ca7863a311?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/57ca7863a311</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 00:57:04 GMT</pubDate>
            <atom:updated>2020-02-01T00:57:04.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj0KRJNbU5aAYD7sZPE_YQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nooryounis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">noor Younis</a> on <a href="https://unsplash.com/s/photos/time?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>It’s entirely possible to get your Spring Boot application up and running in docker in less than 10 minutes.</p><p>Let’s run through this process first in theory, then in practice. We will start by covering what we are trying to achieve, followed by installing some dependencies and making sure everything is in place to hit the ground running.</p><p>By the end we will have a fully working Spring boot application deployed to your local docker installation and we will have it running with health checks.</p><h3>Theory</h3><p>To run our application we are going to need:</p><ol><li>Webserver &amp; Application</li><li>Host &amp; Execution environment</li></ol><p>Below we can see a Standard 4 tier deployment of a Java app. The biggest issue with this setup is that of tight coupling between our app and the host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*KDDZELWKzWRvCNN77yLd_Q.png" /></figure><p>We generally end up being tied to whatever Java version the Operating System is running, this limits the version of Tomcat which can be deployed and also the version of Java we can use in our code.</p><p>In the above example we have a Hello World &amp; Goodbye World app deployed to the one Tomcat installation. This creates a costly migration challenge as we need to migrate both apps and potentially have to coordinate with operations teams around Java versions, Tomcat versions and even OS limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*yMJsizZCesmbqgR1IoVOFw.png" /></figure><p>Contrast this with our new setup where we have installed Docker to sit between the Operating System and the App environment.</p><p>Now we can support multiple variants of Java, Tomcat and deploy/restart independently of the other app. We also get the added benefit that should one app break, the other is isolated in its own app environment.</p><h4>Creating an App</h4><p>First thing we need to perform to get started is to install <a href="https://docs.docker.com/install/">Docker</a>. With that complete you will need to create a new Spring Boot App using the Initializr either through your IDE of choice or the <a href="https://start.spring.io/">App</a>.</p><p>The only items to select when creating the Spring Boot app are Spring Web and Actuator (for health endpoint)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-M8GgAwe-ICW1lPvx9joA.png" /></figure><p>Go ahead and start the application and ensure it runs as expected, navigate to <a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/health</a> and ensure the response shows the app as “UP”</p><pre><strong>{<br>    </strong>&quot;status&quot;: &quot;UP&quot;<br><strong>}</strong></pre><h4>Creating Docker Image</h4><p>Now we have a healthy and building application we are going to create the docker image from the Application.</p><p>Create a new file called Dockerfile in the root of the project and paste in the following</p><pre>FROM openjdk:8-jre<br><br>EXPOSE 8080<br><br>COPY /build/libs/docker-app-*.jar /opt/fxqlabs-oss/docker-app/docker-app.jar<br><br>HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:8080/actuator/health || exit 1<br><br>ENTRYPOINT [\<br>    &quot;java&quot;,\<br>    &quot;-jar&quot;,\<br>    &quot;/opt/fxqlabs-oss/docker-app/docker-app.jar&quot;\<br>    ]</pre><p>Lets quickly step through the Dockerfile to understand it further:</p><p>Firstly we use the <strong>FROM </strong>directive to define which base image we use, in this case its a simple <a href="https://hub.docker.com/_/openjdk">OpenJDK docker image</a>.</p><p>We use the <strong>EXPOSE </strong>directive to define that Tomcat will be available on port 8080</p><p>We use the <strong>COPY </strong>directive to copy the file from our local folder <strong><em>/build/libs/…jar</em></strong> (The build output artifact) and we put it into the docker images <strong><em>/opt/fxqlabs-oss/docker-app/</em></strong> folder. This bakes the file into the image and will be run on image start.</p><p>We use the <strong>HEALTHCHECK </strong>directive to define a simple CheckHealth activity, simply we are going to use curl to poll the actuator/health endpoint to ensure it responds. Note we don’t check if its up or down here, just that curl exits without error.</p><p>Finally we use the <strong>ENTRYPOINT </strong>directive to define what command we should run when the container starts. In this example we simply send:</p><pre>java -jar /opt/fxqlabs-oss/docker-app/docker-app.jar</pre><p>This starts the Java application and runs it, exposing the app on 8080.</p><h4>Building and Running</h4><p>Let’s build the image, open up a terminal/cmd window and run</p><pre>docker image build -t docker-app:snapshot .</pre><p>Finally lets start a container from the image with the following command</p><ul><li>-p (Declares which port to map our image port we map local port 8081 to 8080 in the container which is tomcat)</li><li>-d (Run the container detached from the console)</li><li>--name (What we should call the container once run</li></ul><pre>docker container run -p 8081:8080 -d --name docker-app docker-app:snapshot</pre><p>Finally you can now load the application and it should be up!</p><p><a href="http://localhost:8081/actuator/health">http://localhost:8081/actuator/health</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWqYkKKB32RvKRSZ2Yqstg.png" /></figure><h3>Conclusion</h3><p>During this article we covered how quickly you can setup a new application in docker. Once completed we can now develop our new application and be ready to deploy to any docker host.</p><ul><li>We simply created a new Spring Boot App using the Initializr either through your IDE of choice or the <a href="https://start.spring.io/">App</a>.</li><li>We added Actuator to it for health checking</li><li>We added a Dockerfile to define our image and copy our built artifact into the image.</li><li>We ran the image as a container on our local machine.</li></ul><p>All code and the sample application is available in the <a href="https://bitbucket.org/fxqlabs-oss/spring-boot-docker-for-busy-developers">Git repo</a></p><p>The repo also includes a bitbucket pipeline template showing how to build and deploy your app to Docker-Hub, along with a docker-compose template to run it.</p><p>Simply checkout the project and run docker-compose up -d to see it in action!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57ca7863a311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selenium Recipes with Python - Automate Web scraping to testing]]></title>
            <link>https://medium.com/@jonathan.turnock/selenium-recipes-with-python-automate-web-scraping-to-testing-d5ccda1a2403?source=rss-323399d91362------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ccda1a2403</guid>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Jonathan Turnock]]></dc:creator>
            <pubDate>Sun, 22 Dec 2019 21:57:31 GMT</pubDate>
            <atom:updated>2019-12-22T22:17:39.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automate Web Scraping and Testing with Python | Selenium Recipies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oneAF1ru_QWnIb775r0wmw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Franck V.</a> on <a href="https://unsplash.com/s/photos/automation?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Many automation libraries exist for python which help scrape sites and perform testing. Projects like Roboform, BeautifulSoup and requests all provide excellent features.</p><p>One slightly lesser known name to Python projects is Selenium. It’s an industry accepted automation and testing framework for UI’s. Unlike other web browsing/scraping libraries it actually plays out inside a browser as though the system was being interacted with.</p><p>This approach gives test teams the ability to automate a whole suite of regression tests for a site. It also helps to overcome some challenges with regards to JavaScript in sites.</p><p>A major hurdle in web scraping can be how JS causes the site to change after loading. We might find that a request response being parsed in something like BeautifulSoup is missing lots of parts. This is because sites that use JS need a browser such as chrome to actually run the JS code.</p><p>This is where Selenium comes into its own as it actually runs a browser window and sends our commands to it.</p><p>Here is a visual example of Selenium running through the JsonPlacerholder UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbepoApBVAIWK_8sbNFoxg.gif" /><figcaption>Selenium Tests running on JsonPlacerholder (Try It Option)</figcaption></figure><p>An entire ecosystem exists for Selenium and its possible to make a career out of being good at this kind of automation and testing. There are UI toolkits, a bespoke IDE and even a custom language which can be used to write tests.</p><p>However, we are going to completely skip all this and get straight into the Python API.</p><h3>2. Install Chrome and the Chrome Driver</h3><p>The first step in automating our Python UI testing is getting a supported browser and its associated driver.</p><p>For our examples we will be using chrome so get chrome installed first.</p><p>Once in chrome we need to get the version by visiting <strong><em>chrome://settings/help</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imBVoVq5bW3fH9ym5glcHQ.png" /><figcaption>Chrome Version 79</figcaption></figure><p>Now head over to Chrome Driver and get the latest driver for our OS:</p><p><a href="https://sites.google.com/a/chromium.org/chromedriver/downloads">Downloads - ChromeDriver - WebDriver for Chrome</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKu9pHZs4GY41BV31xU7iw.png" /></figure><p>As the installation instructions vary by OS we wont go into detail on individual process but download the driver, unzip the contents and add it to the system path.</p><p>For Windows it will involve unzipping into something like:</p><p>C:\Program Files (x86)\ChromeDriver</p><p>Then adding to the path via the <strong><em>System Properties &gt; Environment Variables </em></strong>window.</p><p>For OSX and other Unix based operating systems simply copy the binary from the download to the <strong><em>/usr/local/bin</em></strong> folder.</p><p>For a more comprehensive guide on Selenium and the installation process the see the docs:</p><ul><li><a href="https://selenium-python.readthedocs.io/">Selenium with Python - Selenium Python Bindings 2 documentation</a></li><li><a href="https://selenium-python.readthedocs.io/installation.html">1. Installation - Selenium Python Bindings 2 documentation</a></li></ul><h3>3. Hello World of Selenium</h3><p>In the following recipe we see how to perform simple interactions with a basic site <a href="https://jsonplaceholder.typicode.com/">https://jsonplaceholder.typicode.com/</a></p><p>The below recipe illustrates how to perform the actions from the GIF in the intro. We see how along the way we capture screenshots to create the GIF using the driver.save_screenshot(…) method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1e85ec697d03b098805b08a0cf30328/href">https://medium.com/media/f1e85ec697d03b098805b08a0cf30328/href</a></iframe><ol><li>We first setup the Options for Chrome. This is just a way of passing arguments.</li><li>We create the Chrome driver, this will give us our Chrome window.</li><li>We head over to <a href="https://jsonplaceholder.typicode.com/">https://jsonplaceholder.typicode.com/</a></li><li>We scroll down the page so the element with ID <strong>run-message</strong> is in the window. This isn’t necessary for automation or testing but it is for the screenshot to actually show changes.</li><li>We click on the element with ID <strong>run-button </strong>this triggers the demo for the page, we then wait 1 second for the ajax request to fire and come back before testing the result.</li><li>Next we see how we can access whats displayed in the browser in our Python, we grab the text from the element with ID <strong>run-message</strong> and test it against a known text, this causes <strong>True</strong> to be printed to the console if there is a match, otherwise it will print <strong>False</strong>.</li></ol><blockquote><strong><em>This page will be updated with additional recipes.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ccda1a2403" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>