<?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 Joshua Salema on Medium]]></title>
        <description><![CDATA[Stories by Joshua Salema on Medium]]></description>
        <link>https://medium.com/@joshuasalema?source=rss-a363b96ba651------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s5dZXcFuDFe1pTTzBuAg1g.png</url>
            <title>Stories by Joshua Salema on Medium</title>
            <link>https://medium.com/@joshuasalema?source=rss-a363b96ba651------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:07:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshuasalema/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[Stop Doing the Boring Parts: What Claude Code Actually Changes for Developers]]></title>
            <link>https://medium.com/@joshuasalema/stop-doing-the-boring-parts-what-claude-code-actually-changes-for-developers-b9a534671dcf?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a534671dcf</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 13:36:04 GMT</pubDate>
            <atom:updated>2026-06-01T13:36:04.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Software engineering has a dirty secret: most of your day isn’t spent engineering.</p><p>It’s spent <em>navigating </em>through unfamiliar codebases, cryptic error messages, repetitive scaffolding, and the constant cognitive tax of holding ten things in your head at once. The actual thinking , the system design, the architectural trade-offs, the creative problem-solving — gets squeezed into whatever’s left.</p><p>AI coding tools promised to change this. Most delivered glorified autocomplete: useful at the line level, useless at the task level. They’d finish your syntax but couldn’t follow your intent.</p><p>Claude Code is built around a different idea entirely. It’s an agentic coding tool that runs in your terminal and IDE, reads your entire codebase, and executes multi-step tasks on your behalf not just suggesting what to type next, but actually doing the work alongside you. Teams using it are seeing 30–60% faster development cycles. Internally at Anthropic, feature implementation as a share of Claude Code usage nearly tripled over six months as engineers delegated increasingly complex work to it.</p><p>But raw numbers only tell part of the story. The more honest way to show what it does is to show what development looks like <em>without</em> it and then with it. So let’s do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfJe7aPXNSJ34zi840hGeQ.jpeg" /></figure><h3>Scenario 1: Understanding a New Codebase</h3><h3>Without Claude Code</h3><p>You’ve just joined a team or picked up an open-source project. The repo has 80+ files, no single “start here” document, and the last meaningful comment was written in 2021.</p><p>You spend the first two days doing this:</p><ul><li>Cloning and running the project (1–2 hours if you’re lucky, longer if dependencies break)</li><li>Tracing execution flow manually from main.py or index.js, opening file after file</li><li>Searching for where a specific feature lives using grep or your IDE’s half-helpful search</li><li>Asking a senior dev to walk you through the architecture if they have time</li><li>Writing notes in a doc that you’ll probably lose</li></ul><p>By end of day two, you have a rough mental map and about three new questions for every one you answered.</p><h3>With Claude Code</h3><p>You open your terminal and run /init. Claude Code analyzes the entire codebase and auto-generates a CLAUDE.md file an architecture overview that includes key directories, file conventions, command references, and the relationships between modules.</p><p>Then you just ask:</p><blockquote>“What happens when a user submits the checkout form? Walk me through the flow end to end.”</blockquote><p>Claude traces it for you: the frontend handler, the API call, the validation middleware, the database write, the email trigger. In plain English, with file references.</p><p>Onboarding that used to take two days now takes two hours. And the mental energy you saved? It goes into actually building something.</p><h3>Scenario 2: Debugging a Stubborn Bug</h3><h3>Without Claude Code</h3><p>Your CI pipeline is failing. The error message says something vague like TypeError: Cannot read properties of undefined. You:</p><ol><li>Reproduce it locally (15–30 minutes)</li><li>Add console.log statements in five different places</li><li>Run the tests again. Wrong place. Move the logs.</li><li>Eventually narrow it down to a race condition in an async function</li><li>Search Stack Overflow for the specific pattern</li><li>Patch it, run the tests, introduce a new failure</li><li>Repeat</li></ol><p>Total time: 2–4 hours for what turns out to be a three-line fix.</p><h3>With Claude Code</h3><p>You describe the error and paste the stack trace. Claude Code reads the relevant files in context, identifies that the async function is resolving before a dependent value is populated, explains <em>why</em> this is happening, and suggests the fix with the corrected code.</p><p>You review it, apply it, tests pass.</p><p>Total time: 20 minutes. The remaining time goes into writing a test that would have caught this earlier which Claude Code also helps you write.</p><h3>Scenario 3: Writing Boilerplate and Scaffolding</h3><h3>Without Claude Code</h3><p>You need a new REST API endpoint. You know the pattern you’ve written it fifteen times. But you still have to:</p><ul><li>Copy-paste from an existing endpoint</li><li>Rename every variable carefully</li><li>Hook it into the router</li><li>Write the validation schema</li><li>Add the database query</li><li>Write the unit tests</li><li>Update the API docs or OpenAPI spec</li></ul><p>This is the work that every developer knows is necessary and no developer actually enjoys. It takes an hour to do right, longer if you make a small mistake somewhere in the chain.</p><h3>With Claude Code</h3><p>You say:</p><blockquote>“Add a POST /api/v1/orders endpoint. It should accept customer ID, product IDs, and quantities. Validate input, write to the orders table, and return the created order with a 201. Follow the same pattern as the existing /api/v1/products endpoint.”</blockquote><p>Claude Code reads the existing endpoint, matches the style and conventions, generates the route, validation, controller, database call, and a matching test file. It does this in under two minutes.</p><p>You review the output because you should always review and make one small tweak. Done.</p><p>The 60-minute task becomes a 10-minute task. Multiply that across a sprint and you’re looking at a significant reclaiming of time for the work that actually requires your judgment.</p><h3>Scenario 4: Refactoring Legacy Code</h3><h3>Without Claude Code</h3><p>Tech debt is real and painful. You have a 400-line function that does six different things, has no tests, and everyone is afraid to touch it. Refactoring it means:</p><ul><li>Understanding exactly what it does (risky without tests)</li><li>Identifying safe split points</li><li>Extracting functions one at a time</li><li>Writing tests retroactively to verify you didn’t break anything</li><li>Getting a code review from someone who has to understand all of the above before they can approve it</li></ul><p>This is the kind of work that gets pushed to the next quarter indefinitely.</p><h3>With Claude Code</h3><p>You tell Claude Code:</p><blockquote>“Refactor processOrderBatch() in orders/processor.js. It&#39;s doing too much — separate the validation, transformation, and persistence concerns into distinct functions. Write unit tests for each. Keep the external interface the same.&quot;</blockquote><p>Claude reads the function, identifies the logical boundaries, proposes the split, generates the refactored code, and writes tests for each extracted function. It flags two edge cases it found during the process that weren’t being handled.</p><p>You review the diff. It’s clean, well-named, and testable. The review conversation with your teammate is now about design choices, not deciphering what the original code even did.</p><h3>Scenario 5: Working Across Multiple Files and Agents</h3><h3>Without Claude Code</h3><p>Building a new feature often touches many layers: a UI component, an API endpoint, a database migration, updated tests, updated docs. Keeping all of this in sync mentally while switching between files is where bugs and inconsistencies creep in.</p><h3>With Claude Code</h3><p>Claude Code supports multi-agent workflows. You can deploy specialized sub-agents with distinct roles one focused on the backend logic, one doing a security review, one checking for test coverage. Each works with a focused context, which means less noise and more precision.</p><p>The result is parallel execution of tasks that would otherwise be strictly sequential architecture decisions, implementation, and review happening in coordinated waves rather than one slow waterfall.</p><h3>The Bigger Shift: Less Overhead, More Thinking</h3><p>What these scenarios share is a common thread: Claude Code doesn’t replace developer judgment it removes the <em>overhead</em> that keeps developers from exercising it.</p><p>The hours spent reading unfamiliar code, writing boilerplate, tracing bugs through log files, maintaining context across dozens of open tabs these aren’t the hard parts of software engineering. They’re the <em>expensive</em> parts. The parts that drain the mental energy you need for the actually hard parts: system design, product decisions, trade-offs.</p><p>Anthropic’s own internal data tells an interesting story. Over six months of tracking, engineers began delegating increasingly complex tasks to Claude Code and providing less oversight over time not because they became careless, but because the tool proved reliable enough to trust with more. Task complexity went up. Human turns in conversations went down.</p><p>That’s not a tool that’s replacing developers. That’s a tool that’s making developers more like senior engineers focused on the decisions that matter, delegated on everything else.</p><h3>Getting Started</h3><p>Claude Code runs in your terminal and integrates natively with VS Code. Setup takes under five minutes pick the install method that fits your environment:</p><p><strong>macOS / Linux — Native installer (recommended, no Node.js required)</strong></p><pre>curl -fsSL https://claude.ai/install.sh | bash</pre><p><strong>macOS — Homebrew</strong></p><pre>brew install claude-code</pre><p><strong>Windows — PowerShell (native installer)</strong></p><pre>irm https://claude.ai/install.ps1 | iex</pre><p><strong>Windows — WSL or any platform via npm (requires Node.js 18+)</strong></p><pre>npm install -g @anthropic-ai/claude-code</pre><p>Once installed, navigate to your project directory and run:</p><pre>claude</pre><p>The first time you run it, Claude Code will walk you through a quick browser-based authentication with your Anthropic account. After that, the first thing worth doing in any project is running /init it analyzes your codebase and generates a CLAUDE.md file that becomes the foundation for everything else.</p><h3>Final Thought</h3><p>Here’s what I keep coming back to: Claude Code doesn’t make you a better developer by doing the hard parts for you. It makes you better by giving you back the time and headspace to <em>be</em> better to think more carefully, design more deliberately, and care more about the work that actually deserves your attention.</p><p>The developers who get the most out of it aren’t the ones who treat it as a magic box. They’re the ones who bring clear intent, review outputs critically, and know when to push back. In that sense, it’s less like a shortcut and more like a force multiplier it amplifies what you bring to the table.</p><p>If you haven’t tried it yet, the barrier is low. If you have, you already know: there’s no going back to the old way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a534671dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Agentic AI system to Automate Shopify Orders from Email Threads]]></title>
            <link>https://medium.com/@joshuasalema/building-an-agentic-ai-system-to-automate-shopify-orders-from-email-threads-6cc7915bec1d?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cc7915bec1d</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 12:30:18 GMT</pubDate>
            <atom:updated>2025-09-14T16:51:26.490Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Agentic AI Workflow: From Email Quote to Shopify Order with GPT-4</h3><p>How I built an <strong>AI-powered</strong> workflow that receives email orders, sends dynamic quotes, and places Shopify orders — automatically.</p><h3>Problem</h3><p>In many B2B sales workflows, ordering still happens via email. A sales representative receives a message like:</p><blockquote>“I need 5 units of IMPLANT001 and 2 of IMPLANT002.”</blockquote><p>The rep manually:</p><ul><li>Parses the email,</li><li>Generates a quote (PDF),</li><li>Waits for approval, and</li><li>Creates the order in Shopify.</li></ul><p>This manual process is slow, error-prone, and repetitive.</p><h3>Solution</h3><p>I built an <strong>Agentic AI system</strong> that automates this entire flow:</p><ol><li><strong>Listens to emails</strong> for order intents.</li><li><strong>Parses SKUs and quantities</strong> using GPT-4.</li><li><strong>Sends back a quote PDF</strong> dynamically.</li><li><strong>Watches for approval</strong> in the same email thread.</li><li><strong>Places the Shopify order automatically.</strong></li></ol><p>No buttons. No manual work. Just natural email conversations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uCCPIzhJRufV9N4amQ2TA.png" /><figcaption>Agentic AI Order Workflow</figcaption></figure><h3>Tech Stack</h3><ul><li><strong>Node.js</strong> backend</li><li><strong>Google Gmail API</strong> for email polling and sending</li><li><strong>Shopify Admin API</strong> for order and product management</li><li><strong>PDFKit</strong> to generate professional quotes</li><li><strong>OpenAI GPT-4.1 API</strong> for understanding email context</li><li><strong>No frontend</strong> — this is 100% agentic, triggered via email</li></ul><h3>The Email Flow</h3><h3>Step 1: Initial Email from Customer</h3><blockquote><em>Hi,<br> I need the following:</em></blockquote><blockquote><em>IMPLANT001–5 , IMPLANT002–3</em></blockquote><blockquote><em>Thanks,<br> Dr. Smith</em></blockquote><h3>Step 2: AI Replies with Quote + PDF</h3><blockquote><em>Hi,<br> Please find attached the quote based on your request.<br> Reply to this email with </em><strong><em>“approved”</em></strong><em> to proceed.</em></blockquote><blockquote><em>– Sales Bot</em></blockquote><p>🧾 The attached PDF is generated dynamically, with SKU breakdown, price, and totals.</p><h3>Step 3: Customer Replies “Approved”</h3><blockquote><em>Approved. Please proceed.</em></blockquote><p>The AI detects this reply and places the Shopify order directly — sending a confirmation email with order ID and receipt.</p><h3>GPT-4 Prompt Design</h3><p>I used GPT-4 with a prompt like:</p><pre>Given the full email conversation below (latest message last), return JSON:<br>{<br>  &quot;intent&quot;: &quot;quote_request&quot; | &quot;approval&quot; | &quot;other&quot;,<br>  &quot;skus&quot;: [{ &quot;sku&quot;: string, &quot;quantity&quot;: number }]<br>}</pre><p>This helped GPT extract:</p><ul><li>Intent (quote vs approval)</li><li>SKU and quantity (even from fuzzy formats like IMPLANT001 x 3)</li></ul><h3>Sample JSON Output from GPT</h3><pre>{<br>  &quot;intent&quot;: &quot;quote_request&quot;,<br>  &quot;skus&quot;: [<br>    { &quot;sku&quot;: &quot;IMPLANT001&quot;, &quot;quantity&quot;: 5 },<br>    { &quot;sku&quot;: &quot;IMPLANT002&quot;, &quot;quantity&quot;: 3 }<br>  ]<br>}</pre><h3>Product Mapping &amp; Order Creation</h3><ul><li>Fetched all products using Shopify API.</li><li>Built a SKU → Variant ID map.</li><li>Created orders using variant_id, quantity, and customer email.</li><li>Marked orders as <strong>pending</strong> (not paid) and skipped shipping fields for simplicity.</li></ul><h3>Conversation-Aware Email Threading</h3><ul><li>The quote and approval detection both happen inside the same email thread using Gmail thread ID.</li><li>Replies are formatted with In-Reply-To and References headers to keep threading intact.</li></ul><h3>Testing and Simulation</h3><p>To simulate the workflow:</p><ul><li>I used two Gmail accounts: one as the “customer” and another as the “sales bot.”</li><li>Emails with SKUs triggered quotes.</li><li>Replies with “approved” triggered order creation.</li><li>All messages stayed in a single thread for context preservation.</li></ul><h3>Code Files</h3><pre>agentic-auto-ordering/<br>├── src/<br>│   ├── auth/<br>│   │   └── gmailAuth.js<br>│   ├── email/<br>│   │   ├── emailUtils.js<br>│   │   └── sendReply.js<br>│   ├── shopify/<br>│   │   ├── shopifyClient.js<br>│   │   └── productMap.js<br>│   ├── ai/<br>│   │   └── analyzeEmail.js<br>│   ├── utils/<br>│   │   └── generateQuote.js<br>│   └── index.js<br>├── .env<br>├── token.json<br>├── credentials.json<br>├── package.json</pre><ol><li>Install the below mentioned node modules</li></ol><pre>npm install googleapis shopify-api-node dotenv pdfkit openai</pre><p>2. src/auth/gmailAuth.js</p><pre>import fs from &#39;fs&#39;;<br>import readline from &#39;readline&#39;;<br>import { google } from &#39;googleapis&#39;;<br><br>const SCOPES = [&#39;https://www.googleapis.com/auth/gmail.modify&#39;, &#39;https://www.googleapis.com/auth/gmail.send&#39;];<br>const TOKEN_PATH = &#39;token.json&#39;;<br><br>export function authorize(credentials, callback) {<br>  const { client_secret, client_id, redirect_uris } = credentials.installed;<br>  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);<br><br>  fs.readFile(TOKEN_PATH, (err, token) =&gt; {<br>    if (err) return getNewToken(oAuth2Client, callback);<br>    oAuth2Client.setCredentials(JSON.parse(token));<br>    callback(oAuth2Client);<br>  });<br>}<br><br>function getNewToken(oAuth2Client, callback) {<br>  const authUrl = oAuth2Client.generateAuthUrl({ access_type: &#39;offline&#39;, scope: SCOPES });<br>  console.log(&#39;Authorize this app by visiting this url:&#39;, authUrl);<br>  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });<br>  rl.question(&#39;Enter the code from that page here: &#39;, (code) =&gt; {<br>    rl.close();<br>    oAuth2Client.getToken(code, (err, token) =&gt; {<br>      if (err) return console.error(&#39;Error retrieving access token&#39;, err);<br>      oAuth2Client.setCredentials(token);<br>      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) =&gt; {<br>        if (err) return console.error(err);<br>        console.log(&#39;Token stored to&#39;, TOKEN_PATH);<br>      });<br>      callback(oAuth2Client);<br>    });<br>  });<br>}</pre><p>3. src/email/emailUtils.js</p><pre>export function extractFullEmailText(payload) {<br>  const parts = [];<br>  function recurse(part) {<br>    if (part.parts) {<br>      part.parts.forEach(recurse);<br>    } else if (part.mimeType === &#39;text/plain&#39; &amp;&amp; part.body?.data) {<br>      parts.push(Buffer.from(part.body.data, &#39;base64&#39;).toString(&#39;utf-8&#39;));<br>    } else if (part.mimeType === &#39;text/html&#39; &amp;&amp; part.body?.data) {<br>      const html = Buffer.from(part.body.data, &#39;base64&#39;).toString(&#39;utf-8&#39;);<br>      const stripped = html.replace(/&lt;[^&gt;]+&gt;/g, &#39;&#39;);<br>      parts.push(stripped);<br>    }<br>  }<br>  recurse(payload);<br>  return parts.join(&#39;\n&#39;).toLowerCase();<br>}</pre><p>4. src/email/sendReply.js</p><pre>import fs from &#39;fs&#39;;<br><br>export async function sendReplyInThread(gmail, threadId, to, subject, body, attachmentPath, filename) {<br>  const messageParts = [<br>    `To: ${to}`,<br>    `Subject: ${subject}`,<br>    `In-Reply-To: ${threadId}`,<br>    `References: ${threadId}`,<br>    &#39;Content-Type: multipart/mixed; boundary=&quot;boundary&quot;&#39;,<br>    &#39;&#39;,<br>    &#39;--boundary&#39;,<br>    &#39;Content-Type: text/plain; charset=&quot;UTF-8&quot;&#39;,<br>    &#39;&#39;,<br>    body,<br>    &#39;&#39;,<br>    &#39;--boundary&#39;,<br>    `Content-Type: application/pdf; name=&quot;${filename}&quot;`,<br>    &#39;Content-Disposition: attachment; filename=&quot;&#39; + filename + &#39;&quot;&#39;,<br>    &#39;Content-Transfer-Encoding: base64&#39;,<br>    &#39;&#39;,<br>    fs.readFileSync(attachmentPath).toString(&#39;base64&#39;),<br>    &#39;--boundary--&#39;,<br>  ];<br><br>  const rawMessage = Buffer.from(messageParts.join(&#39;\r\n&#39;)).toString(&#39;base64&#39;)<br>    .replace(/\+/g, &#39;-&#39;).replace(/\//g, &#39;_&#39;).replace(/=+$/, &#39;&#39;);<br><br>  await gmail.users.messages.send({<br>    userId: &#39;me&#39;,<br>    requestBody: { raw: rawMessage, threadId: threadId }<br>  });<br>}</pre><p>5. src/shopify/shopifyClient.js</p><pre>import Shopify from &#39;shopify-api-node&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>export const shopify = new Shopify({<br>  shopName: process.env.SHOPIFY_SHOP_NAME,<br>  accessToken: process.env.SHOPIFY_ACCESS_TOKEN<br>});</pre><p>6. src/shopify/productMap.js</p><pre>import { shopify } from &#39;./shopifyClient.js&#39;;<br><br>export async function buildProductMap() {<br>  const map = {};<br>  try {<br>    const products = await shopify.product.list({ limit: 250 });<br>    for (const product of products) {<br>      for (const variant of product.variants) {<br>        if (variant.sku) {<br>          map[variant.sku] = {<br>            id: product.id,<br>            variantId: variant.id,<br>            title: product.title,<br>            price: variant.price<br>          };<br>        }<br>      }<br>    }<br>    console.log(&#39;Generated productMap:&#39;, map);<br>  } catch (error) {<br>    console.error(&#39;Error building productMap:&#39;, error);<br>  }<br>  return map;<br>}</pre><p>7. src/utils/generateQuote.js</p><pre>import fs from &#39;fs&#39;;<br>import PDFDocument from &#39;pdfkit&#39;;<br><br>export function generateQuotePDF(items, filePath) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const doc = new PDFDocument();<br>    const stream = fs.createWriteStream(filePath);<br>    doc.pipe(stream);<br><br>    doc.fontSize(18).text(&#39;Quote - Order Summary&#39;, { align: &#39;center&#39; });<br>    doc.moveDown();<br>    doc.fontSize(12);<br><br>    let total = 0;<br>    items.forEach(({ sku, title, price, quantity }) =&gt; {<br>      const subtotal = parseFloat(price) * quantity;<br>      total += subtotal;<br>      doc.text(`${sku} - ${title} - ${quantity} pcs x ₹${price} = ₹${subtotal.toFixed(2)}`);<br>    });<br><br>    doc.moveDown();<br>    doc.text(`Total: ₹${total.toFixed(2)}`, { bold: true });<br>    doc.end();<br><br>    stream.on(&#39;finish&#39;, resolve);<br>    stream.on(&#39;error&#39;, reject);<br>  });<br>}</pre><p>8. src/ai/analyzeEmail.js</p><pre>import OpenAI from &#39;openai&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });<br><br>export async function analyzeEmailWithGPT(fullThreadText) {<br>  const prompt = `You&#39;re a helpful assistant... // SAME PROMPT`;<br><br>  try {<br>    const response = await openai.chat.completions.create({<br>      model: &quot;gpt-4-0613&quot;,<br>      messages: [{ role: &quot;user&quot;, content: prompt }],<br>      temperature: 0.2<br>    });<br>    return JSON.parse(response.choices[0].message.content.trim());<br>  } catch (err) {<br>    console.warn(&quot;GPT-4 failed to parse:&quot;, err);<br>    return { intent: &#39;other&#39;, skus: [] };<br>  }<br>}</pre><p>9. src/index.js</p><pre>import fs from &#39;fs&#39;;<br>import { google } from &#39;googleapis&#39;;<br>import { authorize } from &#39;./auth/gmailAuth.js&#39;;<br>import { extractFullEmailText } from &#39;./email/emailUtils.js&#39;;<br>import { sendReplyInThread } from &#39;./email/sendReply.js&#39;;<br>import { analyzeEmailWithGPT } from &#39;./ai/analyzeEmail.js&#39;;<br>import { generateQuotePDF } from &#39;./utils/generateQuote.js&#39;;<br>import { buildProductMap } from &#39;./shopify/productMap.js&#39;;<br>import { shopify } from &#39;./shopify/shopifyClient.js&#39;;<br><br>async function checkForApprovedEmails(auth) {<br>  const productMap = await buildProductMap();<br>  const gmail = google.gmail({ version: &#39;v1&#39;, auth });<br><br>  const poll = async () =&gt; {<br>    try {<br>      const res = await gmail.users.messages.list({ userId: &#39;me&#39;, q: &#39;is:unread&#39; });<br>      const messages = res.data.messages || [];<br><br>      for (const msg of messages) {<br>        const message = await gmail.users.messages.get({ userId: &#39;me&#39;, id: msg.id });<br>        const threadId = message.data.threadId;<br>        const thread = await gmail.users.threads.get({ userId: &#39;me&#39;, id: threadId });<br>        const fullThreadText = thread.data.messages.map(m =&gt; extractFullEmailText(m.payload)).join(&#39;\n\n&#39;);<br><br>        const senderHeader = message.data.payload.headers.find(h =&gt; h.name === &#39;From&#39;)?.value || &#39;&#39;;<br>        const match = senderHeader.match(/&lt;([^&gt;]+)&gt;/);<br>        const cleanedSender = match ? match[1] : senderHeader.trim();<br><br>        const aiResult = await analyzeEmailWithGPT(fullThreadText);<br>        console.log(&quot;GPT-4.1 parsed intent:&quot;, aiResult);<br><br>        const lineItems = [];<br>        const lineDetails = [];<br><br>        aiResult.skus.forEach(({ sku, quantity }) =&gt; {<br>          const product = productMap[sku.toUpperCase()];<br>          if (product) {<br>            lineItems.push({ variant_id: product.variantId, quantity });<br>            lineDetails.push({ sku, title: product.title, price: product.price, quantity });<br>          }<br>        });<br><br>        if (lineItems.length &gt; 0) {<br>          if (aiResult.intent === &#39;approval&#39;) {<br>            const order = await shopify.order.create({<br>              line_items: lineItems,<br>              financial_status: &#39;pending&#39;,<br>              email: cleanedSender,<br>              send_receipt: true,<br>              send_fulfillment_receipt: true<br>            });<br>            await generateQuotePDF(lineDetails, &#39;./quote.pdf&#39;);<br>            await sendReplyInThread(gmail, threadId, cleanedSender, &#39;Order Confirmation&#39;, `Hi, Your order is placed.`, &#39;./quote.pdf&#39;, &#39;quote.pdf&#39;);<br>          } else if (aiResult.intent === &#39;quote_request&#39;) {<br>            await generateQuotePDF(lineDetails, &#39;./quote.pdf&#39;);<br>            await sendReplyInThread(gmail, threadId, cleanedSender, &#39;Quote for your order&#39;, `Please find attached quote. Reply with &quot;approved&quot; to proceed.`, &#39;./quote.pdf&#39;, &#39;quote.pdf&#39;);<br>          }<br>        }<br><br>        await gmail.users.messages.modify({<br>          userId: &#39;me&#39;,<br>          id: msg.id,<br>          resource: { removeLabelIds: [&#39;UNREAD&#39;] },<br>        });<br>      }<br>    } catch (err) {<br>      console.error(&#39;Polling error:&#39;, err);<br>    }<br>  };<br><br>  setInterval(poll, 15000);<br>  await poll();<br>}<br><br>fs.readFile(&#39;credentials.json&#39;, (err, content) =&gt; {<br>  if (err) return console.log(&#39;Error loading client secret file:&#39;, err);<br>  authorize(JSON.parse(content), async (auth) =&gt; {<br>    await checkForApprovedEmails(auth);<br>  });<br>});</pre><p>10. .env</p><pre># Shopify Store Info<br>SHOPIFY_SHOP_NAME=your-shop-name     # e.g., my-store-name (no .myshopify.com)<br>SHOPIFY_ACCESS_TOKEN=your-access-token<br><br># OpenAI<br>OPENAI_API_KEY=your-openai-api-key</pre><p>Run the app once:</p><pre>node src/index.js</pre><p>This will:</p><ul><li>Prompt you with a Google authorization URL.</li><li>Ask you to paste the authorization code from the browser.</li><li>Create a token.json file in the root directory, which contains the access/refresh token for Gmail API access.</li></ul><pre>zmo-mac-joshuas-01@ZMO-MAC-JoshuaS-01s-MacBook-Air order-placement % node index.js<br>[dotenv@17.0.0] injecting env (4) from .env – encrypt with dotenvx: https://dotenvx.com<br>Generated productMap: {<br>  IMPLANT001: {<br>    id: 10016510017855,<br>    variantId: 51062693986623,<br>    title: &#39;Demo Product&#39;,<br>    price: &#39;210.00&#39;<br>  }<br>}<br>GPT-4.1 parsed intent: { intent: &#39;approval&#39;, skus: [ { sku: &#39;implant001&#39;, quantity: 5 } ] }<br>Creating Shopify order with: {<br>  line_items: [ { variant_id: 51062693986623, quantity: 5 } ],<br>  financial_status: &#39;pending&#39;,<br>  email: &#39;joshuasalema@gmail.com&#39;,<br>  send_receipt: true,<br>  send_fulfillment_receipt: true<br>}<br>Shopify order created: 6708721582399</pre><p>This project demonstrates the power of combining <strong>Agentic AI</strong>, <strong>email integration</strong>, and <strong>e-commerce APIs</strong> to fully automate a B2B ordering workflow. By leveraging:</p><ul><li><strong>OpenAI GPT-4.1</strong> for intelligent email parsing</li><li><strong>Gmail API</strong> for thread-aware communication</li><li><strong>Shopify API</strong> for real-time product/order management</li><li>and <strong>PDFKit</strong> for dynamic quote generation</li></ul><p>We’ve built a hands-free, end-to-end order approval pipeline.</p><p>This system doesn’t just <em>respond</em> to prompts — it takes <strong>proactive, intelligent action</strong> based on context, making it a real-world example of Agentic AI in action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cc7915bec1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redefining Productivity : Building an Agentic AI Assistant Using OpenAI and Gmail + Google Calendar…]]></title>
            <link>https://medium.com/@joshuasalema/building-an-agentic-ai-assistant-using-openai-and-gmail-google-calendar-integration-7eaf8038ffe9?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eaf8038ffe9</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 05:32:10 GMT</pubDate>
            <atom:updated>2025-07-01T07:18:03.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redefining Productivity : Building an Agentic AI Assistant Using OpenAI and Gmail + Google Calendar Integration</h3><h3>Introduction</h3><p>In recent years, artificial intelligence has moved from being reactive and conversational to more autonomous and task-oriented. This evolution brings us to the concept of <strong>Agentic AI — </strong>systems that can take actions based on context, data, and intent without being explicitly told every step.</p><p>In this application, we will walk through building a simple yet functional Agentic AI assistant that:</p><ul><li>Connects to your Gmail inbox</li><li>Reads emails and understands natural language</li><li>Extracts meeting intent and schedules calendar events</li></ul><p>We will build this using <strong>Node.js</strong>, integrate OpenAI’s <strong>GPT-3.5</strong>, and deploy it to <strong>AWS EC2</strong> for real-world use. This article assumes that you have some familiarity with Node.js and API integrations.</p><h3>What is Agentic AI?</h3><p>Agentic AI systems are proactive. They don’t just wait for user commands but operate semi-autonomously to perform tasks like a human assistant would. Think of them as goal-driven agents that interpret context and execute multi-step workflows.</p><p>In our use case:</p><ul><li>The AI will identify a meeting request from unstructured email</li><li>Parse the required details (like time, attendees)</li><li>Schedule it in your Google Calendar</li></ul><p>This is a small but powerful example of Agentic AI in practice.</p><h3>Tools and Technologies</h3><ul><li><strong>Node.js</strong> — JavaScript runtime for building our agent logic</li><li><strong>OpenAI GPT-3.5</strong> — for understanding email context and extracting structured data</li><li><strong>Gmail API</strong> — to fetch user emails securely</li><li><strong>Google Calendar API</strong> — to create calendar events</li><li><strong>dotenv</strong> — for managing API keys and environment variables</li><li><strong>AWS EC2</strong> — to host and run the solution continuously</li></ul><h3>Project Structure Explained</h3><pre>gmail-agentic-scheduler/<br>├── index.js               # Main runner<br>├── openai.js              # GPT extraction logic<br>├── gmail.js               # Gmail fetch logic<br>├── calendar.js            # Google Calendar event creation<br>├── analyze.js             # Meeting data extraction<br>├── credentials.json  # Google OAuth2 credentials<br>├── .env                   # Secrets file</pre><p>Each file has a clear responsibility. This modularity makes the project easy to extend.</p><h3>Setting Up API Access</h3><h3>1. Google Cloud Project</h3><ul><li>Go to Google Cloud Console</li><li>Create a new project</li><li>Enable <strong>Gmail API</strong> and <strong>Google Calendar API</strong></li><li>Under “Credentials”:</li><li>Create OAuth2 client ID (Web application)</li><li>Set http://localhost as the redirect URI</li><li>Download the credentials.json file</li><li>Add your Gmail account as a test user in OAuth Consent screen</li></ul><h3>2. OpenAI API Key</h3><ul><li>Go to <a href="https://platform.openai.com/">OpenAI Platform</a></li><li>Navigate to API Keys &gt; Create Key</li><li>Copy and store it securely</li><li>Add this to your .env file:</li></ul><pre>OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxx</pre><h3>3. Install Dependencies</h3><pre>npm install openai googleapis dotenv</pre><h3>How the Agent Works</h3><h3>Step 1: Read Emails</h3><p>The agent connects to Gmail using OAuth2 and fetches the last 10–20 emails.</p><h3>Step 2: Analyze with OpenAI</h3><p>For each email, the text is sent to GPT-3.5 with a prompt like:</p><pre>Extract meeting details from this email. Return JSON like:<br>{<br>  &quot;title&quot;: &quot;Project Sync&quot;,<br>  &quot;start&quot;: &quot;2025-07-01T15:00:00+05:30&quot;,<br>  &quot;end&quot;: &quot;2025-07-01T16:00:00+05:30&quot;,<br>  &quot;attendees&quot;: [&quot;alice@example.com&quot;]<br>}</pre><h3>Step 3: Parse the Response</h3><p>OpenAI returns a JSON structure. If all required fields are present, the agent proceeds to step 4.</p><h3>Step 4: Create a Calendar Event</h3><p>Using Google Calendar API, a new event is created and invite emails are sent automatically.</p><h3>Sample Input Email</h3><pre>Hi Joshua,<br><br>Can we meet tomorrow at 11 AM IST to discuss the Q3 roadmap? Please invite alice@example.com and bob@example.com as well.<br>Thanks,<br>John</pre><h3>GPT-3.5 Output</h3><pre>{<br>  &quot;title&quot;: &quot;Q3 Roadmap Discussion&quot;,<br>  &quot;start&quot;: &quot;2025-07-01T11:00:00+05:30&quot;,<br>  &quot;end&quot;: &quot;2025-07-01T12:00:00+05:30&quot;,<br>  &quot;attendees&quot;: [&quot;alice@example.com&quot;, &quot;bob@example.com&quot;]<br>}</pre><h3>Code Files</h3><h3>index.js (Main runner)</h3><pre>import fs from &#39;fs&#39;;<br>import readline from &#39;readline&#39;;<br>import { google } from &#39;googleapis&#39;;<br>import { readEmails } from &#39;./gmail.js&#39;;<br>import { createEvent } from &#39;./calendar.js&#39;;<br>import { analyzeEmail } from &#39;./analyze.js&#39;;<br><br>const SCOPES = [<br>  &#39;https://www.googleapis.com/auth/gmail.readonly&#39;,<br>  &#39;https://www.googleapis.com/auth/calendar.events&#39;<br>];<br>const TOKEN_PATH = &#39;token.json&#39;;<br><br>function authorize(credentials, callback) {<br>  const { client_secret, client_id, redirect_uris } = credentials.installed;<br>  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);<br><br>  if (fs.existsSync(TOKEN_PATH)) {<br>    oAuth2Client.setCredentials(JSON.parse(fs.readFileSync(TOKEN_PATH)));<br>    callback(oAuth2Client);<br>  } else {<br>    const authUrl = oAuth2Client.generateAuthUrl({ access_type: &#39;offline&#39;, scope: SCOPES });<br>    console.log(&#39;Authorize this app by visiting:&#39;, authUrl);<br>    const rl = readline.createInterface({ input: process.stdin, output: process.stdout });<br>    rl.question(&#39;Enter code from page: &#39;, (code) =&gt; {<br>      rl.close();<br>      oAuth2Client.getToken(code).then(({ tokens }) =&gt; {<br>        oAuth2Client.setCredentials(tokens);<br>        fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens));<br>        callback(oAuth2Client);<br>      });<br>    });<br>  }<br>}<br><br>async function runAgent(auth) {<br>  const emails = await readEmails(auth);<br>  for (const email of emails) {<br>    console.log(`\n From: ${email.from}\n${email.body}`);<br>    try {<br>      const parsedRaw = await analyzeEmail(email.body);<br>      console.log(&#39;Raw OpenAI output:&#39;, parsedRaw);<br>      const parsed = JSON.parse(parsedRaw);<br>      if (parsed.title &amp;&amp; parsed.start &amp;&amp; parsed.end &amp;&amp; parsed.attendees?.length) {<br>        await createEvent(auth, parsed);<br>      } else {<br>        console.log(&#39;No valid meeting intent found.&#39;);<br>      }<br>    } catch (err) {<br>      console.log(&#39;Could not parse meeting data.&#39;);<br>      console.error(err.message);<br>    }<br>  }<br>}<br><br>fs.readFile(&#39;credentials.json&#39;, (err, content) =&gt; {<br>  if (err) return console.error(&#39;credentials.json not found&#39;);<br>  authorize(JSON.parse(content), runAgent);<br>});</pre><h3>openai.js</h3><pre>import OpenAI from &#39;openai&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });<br>export default openai;</pre><h3>gmail.js</h3><pre>import { google } from &#39;googleapis&#39;;<br><br>export async function readEmails(auth) {<br>  const gmail = google.gmail({ version: &#39;v1&#39;, auth });<br>  const res = await gmail.users.messages.list({ userId: &#39;me&#39;, maxResults: 5 });<br>  const messages = res.data.messages || [];<br>  const emails = [];<br>  for (let msg of messages) {<br>    const full = await gmail.users.messages.get({ userId: &#39;me&#39;, id: msg.id, format: &#39;full&#39; });<br>    const payload = full.data.payload;<br>    const headers = payload.headers || [];<br>    const from = headers.find(h =&gt; h.name === &#39;From&#39;)?.value || &#39;Unknown&#39;;<br>    let body = &#39;&#39;;<br>    if (payload.parts) {<br>      const part = payload.parts.find(p =&gt; p.mimeType === &#39;text/plain&#39;);<br>      if (part?.body?.data) {<br>        body = Buffer.from(part.body.data, &#39;base64&#39;).toString();<br>      }<br>    } else if (payload.body?.data) {<br>      body = Buffer.from(payload.body.data, &#39;base64&#39;).toString();<br>    }<br>    emails.push({ from, body });<br>  }<br>  return emails;<br>}</pre><h3>analyze.js</h3><pre>import openai from &#39;./openai.js&#39;;<br><br>export async function analyzeEmail(text) {<br>  const prompt = `<br>Extract meeting details from this email. Return JSON like:<br>{<br>  &quot;title&quot;: &quot;Project Sync&quot;,<br>  &quot;start&quot;: &quot;2025-07-01T15:00:00+05:30&quot;,<br>  &quot;end&quot;: &quot;2025-07-01T16:00:00+05:30&quot;,<br>  &quot;attendees&quot;: [&quot;person@example.com&quot;]<br>}<br><br>Email: &quot;${text}&quot;<br>`;<br>  const res = await openai.chat.completions.create({<br>    model: &#39;gpt-4.1&#39;,<br>    messages: [{ role: &#39;user&#39;, content: prompt }]<br>  });<br>  return res.choices[0].message.content;<br>}</pre><h3>calendar.js</h3><pre>import { google } from &#39;googleapis&#39;;<br><br>export async function createEvent(auth, details) {<br>  const calendar = google.calendar({ version: &#39;v3&#39;, auth });<br>  const event = {<br>    summary: details.title,<br>    start: { dateTime: details.start, timeZone: &#39;Asia/Kolkata&#39; },<br>    end: { dateTime: details.end, timeZone: &#39;Asia/Kolkata&#39; },<br>    attendees: details.attendees.map(email =&gt; ({ email }))<br>  };<br>  const res = await calendar.events.insert({ calendarId: &#39;primary&#39;, resource: event });<br>  console.log(&#39;Event created:&#39;, res.data.htmlLink);<br>}</pre><h3>Deploying on AWS EC2</h3><h3>Step 1: Launch EC2 Instance</h3><ul><li>Choose Ubuntu 22.04 LTS</li><li>t2.micro (Free tier eligible)</li><li>Allow SSH port 22</li></ul><h3>Step 2: SSH and Set Up Environment</h3><pre>ssh -i agent-key.pem ubuntu@&lt;your-ec2-public-ip&gt;<br>sudo apt update &amp;&amp; sudo apt install nodejs npm unzip git -y</pre><h3>Step 3: Upload and Configure Project</h3><ul><li>Clone via Git or SCP your zipped project</li><li>Install dependencies</li><li>Add .env and credentials.json</li></ul><h3>Step 4: Run the Agent</h3><pre>node index.js  # For manual testing</pre><h3>Step 5: Automate with PM2 or Cron</h3><p><strong>PM2</strong>:</p><pre>npm install -g pm2<br>pm2 start index.js --name gmail-agent<br>pm2 save</pre><p><strong>Cron</strong>:</p><pre>crontab -e<br>*/30 * * * * /usr/bin/node /home/ubuntu/gmail-agentic-scheduler/index.js &gt;&gt; /home/ubuntu/gmail-agentic-scheduler/logs/run.log 2&gt;&amp;1</pre><h3>Test email</h3><pre>Subject: Sync Meeting<br> Body:<br> Hi John,<br> Let&#39;s meet on Friday at 3 PM IST to review the Q2 performance.<br> Please include James (james@company.com) and Tim (tim@company.com).<br> Thanks,<br> Ankit</pre><h3>Extending the Agent</h3><p>You can take this project much further:</p><ul><li>Add natural language support for rescheduling or canceling meetings</li><li>Integrate Zoom or Google Meet link generation</li><li>Use LangChain or AutoGen to chain multiple tools</li><li>Add a web dashboard or mobile alerts</li></ul><h3>Key Takeaways</h3><ul><li><strong>Agentic AI</strong> can automate tedious workflows like meeting scheduling.</li><li>Combining <strong>OpenAI + Gmail + Calendar</strong> makes a powerful productivity tool.</li><li>Deploying on <strong>AWS EC2</strong> makes it scalable, secure, and always-on.</li></ul><p>This is just the beginning — you can extend this into a full personal assistant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eaf8038ffe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Scalable Frontend Architectures: Building Microfrontends with Vite, React, Vue, and…]]></title>
            <link>https://medium.com/@joshuasalema/unlocking-scalable-frontend-architectures-building-microfrontends-with-vite-react-vue-and-2cac5da7eab8?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cac5da7eab8</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 07:27:39 GMT</pubDate>
            <atom:updated>2025-03-02T12:04:47.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Scalable Frontend Architectures: Building Microfrontends with Vite, React, Vue, and Angular</h3><blockquote>Building large-scale frontend applications often leads to complex, monolithic codebases that are hard to maintain and scale. In this article, we explore how to solve this problem by adopting a microfrontend architecture using Vite. Learn how to break down your app into independently deployable microfrontends using multiple frontend technologies like React, Vue, and Angular, and how to seamlessly integrate them into a single application for better maintainability and scalability.</blockquote><p>Microfrontend architecture is a great way to break down a large, monolithic frontend into smaller, independently deployable pieces. With <strong>Vite</strong>, this process becomes even smoother due to its speed and ease of configuration. In this guide, we’ll walk through how to build a microfrontend setup using <strong>React</strong>, <strong>Vue</strong>, and <strong>Angular</strong>, all served by a single host application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wXAk2J6rbo5iWBPfF_TvA.png" /></figure><h3>1. Setting Up the Microfrontend Projects</h3><p>We will create three separate Vite-based projects for each microfrontend: <strong>React</strong>, <strong>Vue</strong>, and <strong>Angular</strong>.</p><h4>Step 1: Create the Vite Projects for React, Vue, and Angular</h4><p>Start by creating Vite projects for React and Vue as usual. For Angular, we need to use the Angular CLI to set it up first.</p><ol><li>Create React App:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLMwVZMRoMy31cWjSy6iEg.png" /></figure><p>2. Create Vue App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jSFzJGnuVEYQKXhV3XkKQ.png" /></figure><p>3. Create Angular App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*XgZfjtUNcXsJLB80ZgEuOA.png" /></figure><p>Here, the @angular/vite package helps integrate Angular with Vite. After installation, you can run ng serve to start the Angular app, but we will need to configure it for microfrontend integration next.</p><p><strong>2. Configure Each Microfrontend</strong></p><p>For each microfrontend, we need to ensure that the application can be mounted dynamically in the host app. We’ll use <strong>single-spa</strong> to help us with the integration.</p><h4>React Microfrontend Configuration</h4><p>In your <strong>React</strong> microfrontend’s entry point (e.g., main.js), set up the mount function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lU9s5oGdL6yOaBxrV9ckvQ.png" /></figure><h4>Vue Microfrontend Configuration</h4><p>In the <strong>Vue</strong> microfrontend, similarly, set up the entry point to be mountable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpFVt3mTOwl9p4APge0Lng.png" /></figure><h4>Angular Microfrontend Configuration</h4><p>For <strong>Angular</strong>, since Angular isn’t naturally “mountable” the same way as React or Vue, we will use single-spa-angular. Install the necessary package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*uEeJy9-kz2MkHgqcbXw9Hg.png" /></figure><p>Then, configure the <strong>Angular microfrontend</strong> entry point in src/main.single-spa.ts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfZtGVVxHTBY9lZ17TzaOQ.png" /></figure><p>This setup ensures that Angular can be loaded and mounted in a host app, much like React and Vue.</p><h3>3. Host Application Configuration</h3><p>Now we need to create a <strong>host application</strong> that will dynamically load and display the microfrontends based on the URL. We’ll use <strong>single-spa</strong> to register the different microfrontends and control their lifecycle.</p><h4>Step 1: Create the Host Application</h4><p>Start by creating a new <strong>Vanilla JS</strong> Vite project for the host application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*bZZE3HOrjdgkzUaUJdwCxg.png" /></figure><p>Install <strong>single-spa</strong> to handle the loading of microfrontends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*9Npf1PfooK76uwrT6j16sg.png" /></figure><h4>Step 2: Set Up Single-spa in the Host Application</h4><p>In the <strong>host application</strong>’s entry point (src/main.js), register each microfrontend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFfK2_gxMktEqepGFD6fkg.png" /></figure><p>Here, each microfrontend is dynamically loaded based on the route. For example:</p><ul><li>/react will load the React microfrontend</li><li>/vue will load the Vue microfrontend</li><li>/angular will load the Angular microfrontend</li></ul><p>Make sure the import paths (&#39;react-app/ReactApp&#39;, &#39;vue-app/VueApp&#39;, and &#39;angular-app/AngularApp&#39;) point to the correct locations for your microfrontend builds.</p><h4>Step 3: Expose Microfrontends in Each Microfrontend Build</h4><p>Each microfrontend will be exposed using a <strong>SystemJS</strong> configuration or <strong>webpack module federation</strong>. For now, we’ll rely on single-spa and expose the entry points directly. You may need to configure your build system to output SystemJS-compatible files. For example, the React and Vue microfrontends should expose their mount functions to be consumed by the host.</p><p>You can export them like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*cw0TlMd5KTDASBNhZu4Z6Q.png" /></figure><h3>4. Running the Microfrontend Setup</h3><ol><li>Start the Microfrontends:</li></ol><p>For each microfrontend (React, Vue, and Angular), run the Vite dev server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*B6VWLZsUBoAcz2a0fwYzOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*VvAL01OylXMUlJmPzl2JRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*-TZ65bhcPTy9ZjqdVn2VXw.png" /></figure><p>This will start each microfrontend on a different port.</p><p>2. Start the Host Application:</p><p>In the <strong>host application</strong>, add logic to load the microfrontends. You can now run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*sV3LHd7Cr4_At_q4oLIEuw.png" /></figure><p>This will start the host application, which dynamically loads the microfrontends based on the URL.</p><h3>5. Deployment and Hosting</h3><p>Once everything is running locally, the next step is to deploy each microfrontend and the host app. Since microfrontends are independent, they can be deployed separately to different services or environments:</p><ul><li><strong>React, Vue, and Angular</strong> apps can be deployed to platforms like <strong>Netlify</strong>, <strong>Vercel</strong>, or <strong>AWS</strong>.</li><li><strong>The host app</strong> will need to load the microfrontends from their URLs.</li></ul><p>Make sure the URLs in the host application are updated to point to the correct deployment URLs of each microfrontend.</p><p>This setup gives you a modular, scalable microfrontend architecture using <strong>Vite</strong>, <strong>React</strong>, <strong>Vue</strong>, and <strong>Angular</strong>. By using tools like <strong>single-spa</strong>, you can independently develop, deploy, and update each part of your frontend application.</p><h4>Why Use Vite for Microfrontends?</h4><ul><li><strong>Fast Development</strong>: Vite’s lightning-fast HMR (Hot Module Replacement) and its ability to handle multiple frameworks in one setup are perfect for microfrontend development.</li><li><strong>Simplicity</strong>: Vite requires minimal configuration, making it easy to set up multiple microfrontends with different technologies.</li><li><strong>Scalable</strong>: As your application grows, you can scale each microfrontend independently, making it easier for teams to work in parallel.</li></ul><p>With this guide, you can create a robust, flexible microfrontend architecture that allows teams to work independently on different technologies and frameworks, all while integrating them into a cohesive and seamless user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cac5da7eab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Bundler: Vite, Webpack, and the New Era of UI Build Tools]]></title>
            <link>https://medium.com/@joshuasalema/choosing-the-right-bundler-vite-webpack-and-the-new-era-of-ui-build-tools-34a03354ae59?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a03354ae59</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 16:23:01 GMT</pubDate>
            <atom:updated>2025-02-20T16:23:01.314Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>In the world of modern web development, bundling tools are essential for optimizing and managing large applications. They help us bundle JavaScript, CSS, HTML, and other assets into one or more smaller files that can be efficiently served to users. Among the most popular bundlers are Webpack, Vite, and other emerging tools. But what makes these tools different, and which one should you choose for your project? In this article, we will compare Vite with Webpack and highlight some alternatives to help you make an informed decision.</strong></blockquote><h4>What is a JavaScript Bundler?</h4><p>A JavaScript bundler is a tool that takes all the JavaScript code (and other assets) in your project, processes it, and combines it into a smaller number of files — usually one file — so it can be sent to the browser more efficiently. Bundlers are crucial for optimizing code, reducing network requests, improving performance, and enabling features like code splitting.</p><p>Some of the most popular bundlers are:</p><ul><li><strong>Webpack</strong></li><li><strong>Vite</strong></li><li><strong>Parcel</strong></li><li><strong>Snowpack</strong></li><li><strong>esbuild</strong></li></ul><p>Each of these tools has its strengths and weaknesses, and they vary significantly in terms of speed, ease of use, configuration, and performance.</p><h3>Vite: The New Era of Bundling</h3><h4>What is Vite?</h4><p>Vite (pronounced “veet”) is a modern, next-generation build tool for front-end development. Created by <strong>Evan You</strong>, the creator of <strong>Vue.js</strong>, Vite is designed to be faster, simpler, and more efficient than traditional bundlers like Webpack.</p><p>Vite is not just a bundler; it is an opinionated tool that provides out-of-the-box support for modern web technologies, including <strong>ESM (ECMAScript Modules)</strong>, <strong>TypeScript</strong>, <strong>Hot Module Replacement (HMR)</strong>, and <strong>CSS preprocessing</strong>.</p><h4>Key Features of Vite</h4><ol><li><strong>Instant Server Start</strong>: Vite uses native ES modules in the browser, which allows for <strong>instant server startup</strong>. Instead of bundling your entire project during development, it only processes and serves files as they are requested. This makes the development experience incredibly fast.</li><li><strong>Hot Module Replacement (HMR)</strong>: Vite’s HMR is blazing fast, offering almost instantaneous feedback while making changes to the code. Since only the changed modules are updated, the application remains in a “live” state throughout development.</li><li><strong>Build Performance</strong>: Vite is powered by <strong>esbuild</strong>, a super-fast bundler written in Go. This makes the production build process extremely fast, especially for large applications, and it handles tree-shaking and minification out of the box.</li><li><strong>No Complex Configuration</strong>: Vite provides sensible defaults and doesn’t require the complex configurations typical of other bundlers. You can set up a new project with zero configuration in seconds.</li><li><strong>Plugin Ecosystem</strong>: Vite has a growing plugin ecosystem for extending its capabilities, such as adding support for <strong>React</strong>, <strong>Vue</strong>, <strong>Preact</strong>, <strong>TypeScript</strong>, and more.</li></ol><h4>When to Use Vite?</h4><p>Vite is an excellent choice for modern applications where:</p><ul><li>You need <strong>fast builds</strong> and <strong>instant feedback</strong> during development.</li><li>You want <strong>zero-config setups</strong> and ease of use.</li><li>You’re building applications with <strong>ES modules</strong> and <strong>modern JavaScript</strong> features.</li><li>You want <strong>super-fast production builds</strong>.</li><li>You’re using or planning to use a modern framework like <strong>Vue.js</strong>, <strong>React</strong>, or <strong>Svelte</strong>.</li></ul><h3>Webpack: The Battle-Tested Powerhouse</h3><h4>What is Webpack?</h4><p>Webpack has been the go-to JavaScript bundler for a long time. It is a highly configurable and powerful tool that can bundle various types of assets (JS, CSS, images, etc.) into one or more output files. It has a massive ecosystem and is the default bundler for many projects.</p><p>Webpack’s strength lies in its <strong>extensibility</strong>. Developers can configure Webpack to suit nearly any need, no matter how complex.</p><h4>Key Features of Webpack</h4><ol><li><strong>Loaders and Plugins</strong>: Webpack uses <strong>loaders</strong> and <strong>plugins</strong> to transform files before bundling them. This allows Webpack to handle assets like <strong>CSS</strong>, <strong>images</strong>, and <strong>fonts</strong>, as well as compile files written in languages like <strong>TypeScript</strong> or <strong>SASS</strong>.</li><li><strong>Tree Shaking</strong>: Webpack supports tree shaking, which is a technique to eliminate unused code during production builds, resulting in smaller file sizes.</li><li><strong>Code Splitting</strong>: Webpack can split your application into smaller bundles, enabling <strong>lazy loading</strong> of different parts of your app as needed. This can dramatically improve load times for large applications.</li><li><strong>Large Ecosystem</strong>: Webpack has a huge number of plugins and integrations. Whether you’re working with <strong>React</strong>, <strong>Vue</strong>, or <strong>Angular</strong>, Webpack has support for a wide variety of frameworks and tools.</li><li><strong>Configurability</strong>: One of Webpack’s defining features is its flexibility. You can tweak nearly every aspect of your build process, which makes it a perfect fit for large-scale applications where granular control is necessary.</li></ol><h4>When to Use Webpack?</h4><p>You should consider using Webpack if:</p><ul><li>You’re working on a <strong>complex</strong> or <strong>large-scale</strong> project that requires granular control over the build process.</li><li>You need fine-tuned configurations for things like <strong>asset management</strong>, <strong>optimization</strong>, and <strong>minification</strong>.</li><li>You’re dealing with <strong>legacy systems</strong> or require backward compatibility with older browsers.</li><li>You need to <strong>integrate with a variety of frameworks</strong> and custom configurations.</li></ul><h3>Comparing Vite and Webpack</h3><h4>1. Speed and Performance</h4><ul><li><strong>Vite</strong>: It is lightning fast in development because it leverages native ESM and only bundles files when they’re requested. The build process in production is also extremely fast due to <strong>esbuild</strong>.</li><li><strong>Webpack</strong>: Webpack can be slower in development due to its bundling process and requires optimizations like <strong>webpack-dev-server</strong> to improve speed. However, Webpack’s production build speed can be improved with optimizations like <strong>cache</strong>, <strong>parallelism</strong>, and <strong>code splitting</strong>.</li></ul><h4>2. Configuration Complexity</h4><ul><li><strong>Vite</strong>: Vite requires minimal configuration and works out of the box for most modern use cases. It’s particularly well-suited for users who want to focus on development rather than configuration.</li><li><strong>Webpack</strong>: Webpack is incredibly powerful but comes with a steep learning curve due to its intricate configuration options. It’s highly flexible but requires more effort to set up correctly, especially for beginners.</li></ul><h4>3. Ecosystem and Community Support</h4><ul><li><strong>Vite</strong>: Vite is gaining popularity rapidly and has an excellent community, particularly among Vue.js developers. However, its ecosystem isn’t as mature as Webpack’s.</li><li><strong>Webpack</strong>: Webpack has a massive ecosystem, and its community support is well-established. You’ll find plenty of resources, documentation, and third-party plugins for virtually every use case.</li></ul><h4>4. Flexibility</h4><ul><li><strong>Vite</strong>: Vite is opinionated and favors convention over configuration. While this is an advantage in most cases, it may be limiting if you require complex customizations.</li><li><strong>Webpack</strong>: Webpack is highly flexible and configurable. You can tweak virtually every aspect of your build pipeline, making it more suited for highly customized workflows.</li></ul><h4>5. Framework Compatibility</h4><ul><li><strong>Vite</strong>: Vite was designed for modern frameworks like <strong>Vue.js</strong> and <strong>React</strong> and works seamlessly with them. It provides excellent performance for these frameworks out of the box.</li><li><strong>Webpack</strong>: Webpack works well with <strong>React</strong>, <strong>Vue.js</strong>, <strong>Angular</strong>, and many other frameworks. However, it might require additional configuration depending on the framework you’re using.</li></ul><h3>Alternatives to Vite and Webpack</h3><h4>1. Parcel</h4><p>Parcel is an easy-to-use, zero-config bundler that is gaining popularity for small to medium-sized projects. It offers fast builds, hot reloading, and has good out-of-the-box support for a variety of file types. Parcel is an excellent alternative if you want something simpler than Webpack but more powerful than traditional bundlers.</p><h4>2. Snowpack</h4><p>Snowpack is another modern alternative that focuses on <strong>ESM</strong> and aims to be faster than Webpack for development. It compiles only the code you need and works well with modern frameworks. However, Snowpack focuses more on development rather than production builds.</p><h4>3. esbuild</h4><p>esbuild is a <strong>JavaScript bundler</strong> and <strong>minifier</strong> written in Go that focuses on speed. It’s significantly faster than Webpack and even Vite, especially during development. However, it’s still a bit young in terms of features compared to Webpack and Vite.</p><h3>Conclusion</h3><p>In conclusion, the right bundler for your project depends on your needs:</p><ul><li><strong>Vite</strong> is ideal for <strong>modern web applications</strong> where you prioritize speed, simplicity, and modern frameworks. Its performance, HMR, and minimal configuration make it an excellent choice for many developers today.</li><li><strong>Webpack</strong> is the <strong>powerhouse</strong> for large, complex projects. It’s highly configurable and ideal for situations where you need granular control over your build process or are working with legacy systems.</li><li><strong>Parcel</strong>, <strong>Snowpack</strong>, and <strong>esbuild</strong> are great alternatives if you want something between the simplicity of Vite and the power of Webpack.</li></ul><p>Ultimately, <strong>choose the bundler that aligns with your project requirements</strong> and your team’s expertise. All of these tools have their place in modern web development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a03354ae59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redux Toolkit: Simplifying State Management for Modern Web Apps]]></title>
            <link>https://medium.com/@joshuasalema/understanding-redux-toolkit-simplifying-state-management-for-modern-web-apps-bb336913aba3?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb336913aba3</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 18:43:28 GMT</pubDate>
            <atom:updated>2024-11-20T05:41:02.471Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern web development, managing state across various components can quickly become a challenge, especially as your application scales. While React’s built-in state management works for simple use cases, larger applications often require a more sophisticated solution to keep state consistent across multiple components. <strong>Redux</strong> has long been the go-to state management library for React apps, offering a predictable way to manage state. However, the boilerplate code involved in traditional Redux setups can be overwhelming, leading to the rise of <strong>Redux Toolkit (RTK)</strong>.</p><p>In this article, we’ll explore how Redux Toolkit simplifies the process of working with Redux and compare it to <strong>Redux Saga</strong>, another popular tool for managing side effects in Redux. Both libraries can handle asynchronous actions, but they do so in different ways. We’ll take a look at how each works and which might be the better choice depending on the complexity of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYkitaR24SuFNXYyTxL1xA.gif" /><figcaption>Data flow in a React application that uses Redux for state management</figcaption></figure><h3>Problems with Traditional Redux (Without Redux Toolkit)</h3><p>Before <strong>Redux Toolkit (RTK)</strong>, managing state in a Redux application involved significant <strong>boilerplate code</strong>, <strong>complex setup</strong>, and <strong>difficult maintenance</strong>. Redux was a great state management solution, but its complexity often led to problems in large-scale applications. Here’s a breakdown of the key issues:</p><h3>1. Boilerplate Code</h3><p>One of the most common complaints with traditional Redux is the <strong>amount of boilerplate code</strong> required to set up actions and reducers.</p><ul><li><strong>Action Creators</strong>: You had to manually define action creators for every action you wanted to dispatch, leading to repetitive and verbose code.</li></ul><pre>// Action type<br>const ADD_USER = &#39;ADD_USER&#39;;<br><br>// Action creator<br>const addUser = (user) =&gt; {<br>  return {<br>    type: ADD_USER,<br>    payload: user,<br>  };<br>};<br><br>// Reducer<br>const userReducer = (state = [], action) =&gt; {<br>  switch (action.type) {<br>    case ADD_USER:<br>      return [...state, action.payload];<br>    default:<br>      return state;<br>  }<br>};</pre><ul><li><strong>Action Types</strong>: You had to define and reference string constants for each action type, which led to <strong>action type typos</strong> being a common bug source.</li><li><strong>Reducers</strong>: Reducers were responsible for <strong>handling each action type</strong> manually, which led to repetitive logic in each case block of the switch statement.</li></ul><h3>2. Complex Configuration</h3><p>Setting up Redux required a series of manual configurations:</p><ul><li><strong>Store setup</strong>: You had to manually apply middleware, set up the root reducer, and configure Redux DevTools.</li></ul><pre>import { createStore, applyMiddleware } from &#39;redux&#39;;<br>import rootReducer from &#39;./reducers&#39;;<br>import thunk from &#39;redux-thunk&#39;;<br><br>const store = createStore(<br>  rootReducer,<br>  applyMiddleware(thunk)<br>);</pre><ul><li><strong>Middleware</strong>: Handling async actions with middleware like redux-thunk required additional setup, and the complexity increased with more advanced middleware like redux-saga.</li></ul><h3>3. Handling Asynchronous Actions</h3><p>Handling async logic in traditional Redux was complex and verbose:</p><ul><li><strong>Async Action Creators</strong>: You had to manually dispatch <strong>multiple actions</strong> (e.g., request, success, failure) to reflect the different states of an async operation (loading, success, error).</li></ul><pre>const fetchUser = (userId) =&gt; {<br>  return dispatch =&gt; {<br>    dispatch({ type: &#39;FETCH_USER_REQUEST&#39; });<br>    <br>    fetch(`/api/users/${userId}`)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; dispatch({ type: &#39;FETCH_USER_SUCCESS&#39;, payload: data }))<br>      .catch(error =&gt; dispatch({ type: &#39;FETCH_USER_FAILURE&#39;, error }));<br>  };<br>};</pre><ul><li><strong>Error Handling</strong>: Managing errors in async actions required additional reducers and action types. This often led to <strong>boilerplate code</strong> for every async action.</li></ul><h3>4. Immutability and State Updates</h3><ul><li><strong>Manual State Updates</strong>: In traditional Redux, you were responsible for <strong>managing immutability</strong> manually. If you directly mutated state inside reducers, it could lead to bugs or performance issues.</li></ul><pre>const userReducer = (state = [], action) =&gt; {<br>  switch (action.type) {<br>    case &#39;ADD_USER&#39;:<br>      state.push(action.payload); // Incorrect, mutation of state<br>      return state;<br>    default:<br>      return state;<br>  }<br>};</pre><ul><li><strong>Immer Library</strong>: Without tools like <strong>Immer</strong>, which is integrated into Redux Toolkit, managing immutability required a deep understanding of immutable operations. You needed to use methods like Object.assign() or spread operators to avoid mutating the state directly.</li></ul><h3>5. Verbose and Repetitive Code</h3><p>As your app grows, you need to add more actions, reducers, and action creators. This often results in <strong>repetitive patterns</strong>. For example, managing a collection of users required repeating the same patterns across different slices of the state (e.g., users, posts, comments).</p><h3>6. Difficult to Scale</h3><ul><li>As the complexity of your app increased, the boilerplate and configuration needed to scale Redux grew with it. You needed to manage <strong>multiple reducers</strong>, <strong>combine reducers</strong>, and ensure they were correctly handling <strong>async actions</strong>.</li><li><strong>Feature-specific state management</strong>: Managing state in separate slices (like users, posts, or products) became harder because each slice needed its own set of action types, action creators, and reducers.</li></ul><h3>7. Testing Complexity</h3><p>Writing tests for Redux logic was cumbersome:</p><ul><li>You had to <strong>mock action creators</strong>, <strong>manually dispatch actions</strong>, and verify that reducers returned the correct state.</li><li>Writing tests for <strong>async actions</strong> (using redux-thunk or redux-saga) added another layer of complexity.</li></ul><h3>8. Developer Experience</h3><p>While Redux was powerful, it wasn’t always developer-friendly:</p><ul><li>You had to <strong>memorize patterns</strong> for managing async actions and middleware.</li><li>Developers often made mistakes with <strong>action types</strong>, and debugging these issues was hard without proper tooling (though Redux DevTools helped).</li></ul><h3>What is Redux Toolkit?</h3><p><strong>Redux Toolkit</strong> is the official, recommended library for efficient Redux development. It was created to solve the common pain points of Redux, such as its verbose boilerplate code, lack of best practices, and the need for complex configuration. RTK provides a set of tools and utilities that help developers write Redux logic with less boilerplate and fewer errors.</p><h3>Key Features of Redux Toolkit</h3><ol><li><strong>Simplified Store Setup</strong>: With configureStore, Redux Toolkit sets up the store with the most common configurations for Redux, including built-in middleware like redux-thunk for handling asynchronous actions.</li><li><strong>createSlice for Reducers and Actions</strong>: Redux Toolkit introduces createSlice, a function that generates both actions and reducers in a single call. This reduces the need to write separate action creators and manually handle action types.</li><li><strong>createAsyncThunk for Asynchronous Logic</strong>: Handling async operations like API calls in Redux has traditionally been complex. RTK simplifies this with createAsyncThunk, which abstracts away manual action dispatching, error handling, and state updates.</li><li><strong>Immer Integration</strong>: Redux Toolkit uses the <strong>Immer</strong> library to allow you to write mutable code in reducers, making it easier to manage state updates without worrying about immutability.</li><li><strong>Built-in Redux DevTools</strong>: RTK automatically integrates with Redux DevTools, offering an out-of-the-box debugging experience.</li></ol><h3>Why Choose Redux Toolkit?</h3><ul><li><strong>Reduces Boilerplate</strong>: RTK eliminates the need to write separate action creators and reducers.</li><li><strong>Simplifies Async Operations</strong>: Handling async logic like API calls becomes more manageable with createAsyncThunk.</li><li><strong>Improved Developer Experience</strong>: Out-of-the-box support for debugging and a cleaner syntax make Redux easier to work with.</li></ul><h3>Redux Toolkit Architecture Setup</h3><p>When structuring a Redux Toolkit application, it’s important to keep the architecture modular and scalable. Here’s an overview of how to organize your project:</p><h3>1. File Structure</h3><p>A good file structure helps to separate concerns and makes your codebase easy to scale. Here’s a typical setup:</p><pre>/src<br>  /app<br>    store.js               # Configures the Redux store<br>  /features<br>    /user<br>      userSlice.js          # Redux slice for user-related state<br>      userAPI.js            # Optionally, API calls related to user data<br>    /posts<br>      postsSlice.js         # Redux slice for post-related state<br>      postsAPI.js           # Optionally, API calls related to posts data<br>  /components<br>    /UserProfile.js        # A React component that connects to Redux<br>    /PostList.js           # Another component that connects to Redux<br>  /services<br>    api.js                 # Generic API utilities (e.g., fetching data)<br>  /hooks<br>    useUser.js             # Custom hooks to interact with the Redux store<br>    usePosts.js            # Custom hooks to interact with the Redux store</pre><h3>2. Configuring the Redux Store</h3><p>Redux Toolkit simplifies store setup with configureStore(), which integrates Redux DevTools and includes middleware like redux-thunk.</p><pre>// src/app/store.js<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import userReducer from &#39;../features/user/userSlice&#39;;<br>import postsReducer from &#39;../features/posts/postsSlice&#39;;<br><br>const store = configureStore({<br>  reducer: {<br>    user: userReducer,<br>    posts: postsReducer<br>  },<br>});<br><br>export default store;</pre><h3>3. Creating Slices</h3><p>A <strong>slice</strong> combines actions and reducers for a particular piece of state. Here’s how we define slices for user and posts data:</p><pre>// src/features/user/userSlice.js<br>import { createSlice, createAsyncThunk } from &#39;@reduxjs/toolkit&#39;;<br><br>export const fetchUserData = createAsyncThunk(<br>  &#39;user/fetchUserData&#39;,<br>  async (userId) =&gt; {<br>    const response = await fetch(`/api/users/${userId}`);<br>    return response.json();<br>  }<br>);<br><br>const userSlice = createSlice({<br>  name: &#39;user&#39;,<br>  initialState: { user: null, loading: false, error: null },<br>  reducers: {},<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(fetchUserData.pending, (state) =&gt; { state.loading = true; })<br>      .addCase(fetchUserData.fulfilled, (state, action) =&gt; {<br>        state.loading = false;<br>        state.user = action.payload;<br>      })<br>      .addCase(fetchUserData.rejected, (state, action) =&gt; {<br>        state.loading = false;<br>        state.error = action.error.message;<br>      });<br>  }<br>});<br><br>export default userSlice.reducer;</pre><h3>4. Using Redux in Components</h3><p>You can use useSelector and useDispatch hooks from react-redux to interact with the Redux store in your components.</p><pre>// src/components/UserProfile.js<br>import React, { useEffect } from &#39;react&#39;;<br>import { useSelector, useDispatch } from &#39;react-redux&#39;;<br>import { fetchUserData } from &#39;../features/user/userSlice&#39;;<br><br>function UserProfile({ userId }) {<br>  const dispatch = useDispatch();<br>  const { user, loading, error } = useSelector((state) =&gt; state.user);<br><br>  useEffect(() =&gt; {<br>    dispatch(fetchUserData(userId));<br>  }, [dispatch, userId]);<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{user.name}&lt;/h2&gt;<br>      &lt;p&gt;{user.email}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UserProfile;</pre><h3>5. Custom Hooks (Optional)</h3><p>To make your components cleaner and more reusable, you can create <strong>custom hooks</strong> that abstract away logic for interacting with the Redux store.</p><pre>// src/hooks/useUser.js<br>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import { fetchUserData } from &#39;../features/user/userSlice&#39;;<br><br>export const useUser = (userId) =&gt; {<br>  const dispatch = useDispatch();<br>  const { user, loading, error } = useSelector((state) =&gt; state.user);<br><br>  const fetchUser = () =&gt; dispatch(fetchUserData(userId));<br><br>  return { user, loading, error, fetchUser };<br>};</pre><p>This approach makes components easier to manage, and the logic is reusable across your app.</p><h3>Redux Toolkit vs. Redux Saga: Which Should You Choose?</h3><p>Both <strong>Redux Toolkit</strong> and <strong>Redux Saga</strong> are powerful tools for handling side effects in Redux applications, but they have different approaches. Let’s compare them based on real-world use cases.</p><h3>Use Case 1: Simple Async API Call</h3><p>Suppose you need to fetch user data from an API. Let’s compare how Redux Toolkit and Redux Saga handle this.</p><h4>Redux Toolkit (with createAsyncThunk):</h4><pre>export const fetchUserData = createAsyncThunk(<br>  &#39;user/fetchUserData&#39;,<br>  async (userId) =&gt; {<br>    const response = await fetch(`/api/users/${userId}`);<br>    return response.json();<br>  }<br>);</pre><p>With Redux Toolkit, the createAsyncThunk function handles the async logic, managing pending, fulfilled, and rejected states automatically.</p><h4>Redux Saga:</h4><pre>import { call, put, takeEvery } from &#39;redux-saga/effects&#39;;</pre><pre>function* fetchUserDataSaga(action) {<br>  try {<br>    const response = yield call(fetch, `/api/users/${action.payload}`);<br>    const data = yield response.json();<br>    yield put({ type: &#39;user/fetchUserData/fulfilled&#39;, payload: data });<br>  } catch (error) {<br>    yield put({ type: &#39;user/fetchUserData/rejected&#39;, error: error.message });<br>  }<br>}</pre><pre>function* userSaga() {<br>  yield takeEvery(&#39;user/fetchUserData&#39;, fetchUserDataSaga);<br>}</pre><p>While Redux Saga provides more flexibility, it requires more setup. It excels in scenarios where you have complex async logic, such as multiple sequential or parallel API calls, retries, or cancellations.</p><h3>Use Case 2: Complex Async Workflows</h3><p>For more complex scenarios where you need to manage multiple async actions, such as fetching user data followed by posts or comments, <strong>Redux Saga</strong> is often a better choice due to its <strong>generator functions</strong> that allow fine-grained control over async flows.</p><h4>Redux Saga (Complex Workflow):</h4><pre>function* fetchUserAndPostsSaga(action) {<br>  try {<br>    const user = yield call(fetch, `/api/users/${action.payload}`);<br>    const posts = yield call(fetch, `/api/posts/${user.id}`);<br>    yield put({ type: &#39;user/fetchUserAndPosts/fulfilled&#39;, payload: { user, posts } });<br>  } catch (error) {<br>    yield put({ type: &#39;user/fetchUserAndPosts/rejected&#39;, error: error.message });<br>  }<br>}</pre><p>In contrast, <strong>Redux Toolkit</strong> would require manually chaining async thunks or using middleware for such advanced workflows, which could lead to more verbose code.</p><h3>Which One is More Widely Used?</h3><p><strong>Redux Toolkit</strong> is the <strong>dominant choice</strong> in the modern JavaScript and React ecosystem due to its:</p><ul><li>Simplicity.</li><li>Efficiency.</li><li>Strong <strong>developer experience</strong> improvements.</li><li>Official endorsement by the Redux team.</li></ul><p>It’s the go-to solution for <strong>most projects</strong> today, particularly those that need to manage <strong>simple to moderate async workflows</strong> (e.g., API calls, user authentication, state persistence).</p><p><strong>Redux Saga</strong>, on the other hand, is still in use but is <strong>niche</strong> and primarily used for <strong>complex systems</strong> with challenging side effects, concurrency management, or workflows that go beyond simple async actions.</p><h3>Conclusion</h3><ul><li><strong>Redux Toolkit</strong> is far more widely used and is the <strong>default choice</strong> for most modern applications, offering an easier, more streamlined development experience for managing state and async actions.</li><li><strong>Redux Saga</strong> is still valuable for more <strong>complex scenarios</strong>, but it has a steeper learning curve and is typically reserved for projects where async logic is intricate and needs fine-grained control.</li></ul><p>If you’re starting a new React project, <strong>Redux Toolkit</strong> is likely the best option for most use cases. Use <strong>Redux Saga</strong> if your app has <strong>highly complex side effects</strong> or specific concurrency needs that Redux Toolkit can’t easily handle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb336913aba3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modern Web Stack: GraphQL, React.js, Apollo Client, MongoDB Atlas, and Node.js]]></title>
            <link>https://medium.com/@joshuasalema/building-a-modern-web-stack-graphql-react-js-apollo-client-mongodb-atlas-and-node-js-297409232465?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/297409232465</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 15:42:59 GMT</pubDate>
            <atom:updated>2024-11-10T13:18:00.533Z</atom:updated>
            <content:encoded><![CDATA[<p>GraphQL is a query-based language that gives clients the power to ask for exactly what they need nothing more nothing less, makes it easier to evolve APIs over time, and enables powerful developer tools.To explain the concepts for this setup I will be creating a simple movies application using React.js . Below is the overview of the setup and various components I will be using to create this application.</p><h4>Overview of the Application</h4><p>The project will be divided into backend and frontend layers. MongoDB Atlas will be used to store data on the backend. Apollo GraphQL will be used to build API’s to query MongoDB backend. Apollo Client will be used to connect the API layer with the UI layer. This application will follow microservices architecture wherein new modules can be added on the go without disturbing the current features.</p><p><strong>Frontend</strong> : React.js+Apollo Client</p><p><strong>Backend</strong> : MongoDB Atlas+Node.js+Express+GraphQL</p><p>Find the entire project <a href="https://github.com/69ghostrider/GraphQL-React">here</a></p><h4>React application setup</h4><h4>Step 1</h4><p>Create a new folder for the application containing two subfolders frontend and backend. In the frontend folder create a new React.js project by executing the command below.</p><pre>npx create-react-app movie-maker</pre><p>After executing the command, a new React.js project is bundled in the frontend folder. In the next step let’s add components and containers and put in some React code.</p><h4>Step 2</h4><p>Add two more folders in the src folder namely container and components. The container folder will contain all the parent container elements for the screen whereas the component folder will be used to develop the display components for various sections on the screen. Add the relevant files and code by cloning the <a href="#6eda">git repo</a>. After adding the relevant files and code, your folder structure should look like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*CK276VdShrJUcouIqAJZYA.png" /><figcaption>Containers and Components</figcaption></figure><h4>Step 3</h4><p>Let’s add routing to our React application and also include the Apollo Client by executing the commands below inside the frontend folder.</p><pre>#Apollo client<br>npm i --save @apollo/client graphql</pre><pre>#Adding react-router-dom and react-router-hash-link<br>npm i --save react-router-hash-link react-router-dom</pre><p>We can add navigation functionalities to our react application using react-router-hash-link, and this is included as a part of the header.js component created in step 2:</p><pre>import React from &#39;react&#39;<br>import {HashLink as Link} from &#39;react-router-hash-link&#39;;<br>export default function Header() {<br>return (<br>&lt;div className=&#39;topnav&#39;&gt;<br>&lt;a className=&#39;logo&#39; href=&#39;/&#39;&gt;Movie Maker&lt;/a&gt;<br>&lt;div className=&#39;search-container&#39;&gt;<br>&lt;form&gt;<br>&lt;Link smooth to=&quot;#form&quot;&gt;Add Movies&lt;/Link&gt;<br>&lt;input type=&#39;text&#39; placeholder=&#39;Search movies...&#39; name=&#39;search&#39;/&gt;<br>&lt;button type=&#39;submit&#39;&gt;&lt;i className=&quot;fa fa-magnifying-glass&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>)<br>}</pre><p>Next lets setup the Apollo client and provide it in the index.js file created in step 1. Lets us also add routing capabilities to this application.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import &#39;./App.css&#39;;<br>import App from &#39;./App&#39;;<br>import reportWebVitals from &#39;./reportWebVitals&#39;;<br>import { ApolloClient, InMemoryCache, ApolloProvider, gql } from &#39;@apollo/client&#39;;<br>import { BrowserRouter as Router} from &#39;react-router-dom&#39;;</pre><pre>const client = new ApolloClient({<br>uri: &#39;http://localhost:4000/graphql&#39;,<br>cache: new InMemoryCache(),<br>});</pre><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>&lt;Router&gt;<br>&lt;React.StrictMode&gt;<br>&lt;ApolloProvider client={client}&gt;<br>&lt;App /&gt;<br>&lt;/ApolloProvider&gt;<br>&lt;/React.StrictMode&gt;<br>&lt;/Router&gt;<br>);</pre><p><strong>Note:</strong> GraphQL server setup is explained in step 6 and the server url is used as a parameter to the Apollo Client.</p><h4>Step 4</h4><p>Include all the components into the App.js component and complete the frontend project setup. Below are the contents of the App.js file.</p><pre>import React from &#39;react&#39;<br>import Header from &#39;./components/header&#39;;<br>import Footer from &#39;./components/footer&#39;;<br>import Movies from &#39;./containers/movies&#39;;<br>import AddMovie from &#39;./components/addMovie&#39;;</pre><pre>export default function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header/&gt;<br>      &lt;Movies/&gt;<br>      &lt;AddMovie/&gt;<br>      &lt;Footer/&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Step 5</h4><p>Let us now work on the setting up the backend layer with Node.js and GraphQL. For this application I am using Node v14.17.3. Install node.js via NVM <a href="https://github.com/nvm-sh/nvm#install--update-script">here</a>.</p><p>Before we move on with creating the node.js server let us provision a MongoDB cluster by following the steps <a href="https://www.youtube.com/watch?v=5feydQRZ298">here</a>. For this application I will create a new MongoDB database titled Movie Maker.</p><p>Once the MongoDB cluster is created add your current IP Address to the Cluster and copy the connection string and keep handy. This connection string will be used to connect the Node.js server to MongoDB Atlas database.</p><p>You can read more about MongoDB Atlas <a href="https://www.mongodb.com/docs/atlas/">here</a>.</p><p>Now let us move on with installing the required packages for setting up the Node.js server. Create a new package.json file by following the steps <a href="https://medium.com/@mariokandut/how-to-create-a-package-json-file-e62580a982d8">here</a> and install the NPM packages below in the backend folder.</p><pre>npm i --save cors express mongoose mongodb graphql express-graphql</pre><p>After installing all the packages successfully, the contents of your package.json file should look like the one below.</p><pre>{<br>  &quot;name&quot;: &quot;backend&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;app.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;node app.js&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;express&quot;: &quot;^4.18.1&quot;,<br>    &quot;express-graphql&quot;: &quot;^0.12.0&quot;,<br>    &quot;graphql&quot;: &quot;^16.6.0&quot;,<br>    &quot;mongodb&quot;: &quot;^4.9.1&quot;,<br>    &quot;mongoose&quot;: &quot;^6.6.0&quot;<br>  }<br>}</pre><p>After installing the required packages create the folder structure as shown below, this will be our base setup for writing our GraphQL queries and setting up the node.js server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*Y1cSvPWEUiXRtG9iLF8esA.png" /><figcaption>Backend folder structure</figcaption></figure><h4>Step 6</h4><p>Let’s make use of the app.js file to create our node.js server. The contents of the app.js file is seen below.</p><pre>const express = require(&#39;express&#39;)<br>const app = express()<br>const mongoose = require(&#39;mongoose&#39;)<br>const {graphqlHTTP} = require(&#39;express-graphql&#39;);<br>const movieSchema = require(&#39;../backend/schema/schema&#39;);<br>const resolvers = require(&#39;./resolver/resolver&#39;);<br>const cors = require(&#39;cors&#39;);</pre><pre>// Connect to MongoDB Atlas database  <br>mongoose.connect(&#39;mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.qkydjsl.mongodb.net/?retryWrites=true&amp;w=majority&#39;, {<br>    useNewUrlParser: true,<br>    useUnifiedTopology:true,<br>    authSource:&quot;admin&quot;,<br>    ssl: true,<br>}).then(() =&gt; console.log(&#39;Mongo Connected&#39;))<br>.catch(() =&gt; console.log(&#39;Error occured&#39;))</pre><pre>// To avoid CORS erros while connecting to frontend<br>app.use(cors());</pre><pre>// Supply the GraphQL schema and resolvers created in step 7 and 8<br>app.use(&#39;/graphql&#39;,graphqlHTTP({<br>    schema: movieSchema,<br>    graphiql:true,<br>    rootValue: resolvers<br>}));</pre><pre>app.get(&#39;/&#39;,(req,res) =&gt; {<br>    res.send(&quot;Hello from node&quot;)<br>})</pre><pre>//Start the Node.js server<br>app.listen(4000, () =&gt; {<br>    console.log(&quot;Listening on 4000&quot;)<br>})</pre><h4>Step 7</h4><p>Let’s create and setup the movie schema in the model.js file by using the code below. Each movie will have a name, genre and year.</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const movieSchema = new mongoose.Schema({<br>    name: String,<br>    genre: String,<br>    year: String<br>})</pre><pre>module.exports = new mongoose.model(&#39;Movie&#39;, movieSchema);</pre><h4>Step 8</h4><p>Let’s create a resolver to fetch data from the MongoDB Atlas database using the code below:</p><pre>const Movie = require(&#39;../model/model&#39;);</pre><pre>const resolver = {<br>    movies: () =&gt; {<br>        return Movie.find({})<br>    },<br>    addMovie: (args) =&gt; {<br>        let movie = new Movie({<br>            name: args.name,<br>            year: args.year,<br>            genre: args.genre<br>        })<br>        movie.save();<br>        return movie;<br>    },<br>    movieByName: (args) =&gt; {<br>        return Movie.findOne({name : args.name});<br>    }<br>}</pre><pre>module.exports = resolver;</pre><h4>Step 9</h4><p>Let’s define our queries and mutations as a part of the schema.js file using the code below:</p><pre>const {buildSchema} = require(&#39;graphql&#39;)</pre><pre>const movieSchema = buildSchema(`<br>    type Query {<br>        movies : [Movie],<br>        movieByName(name: String!): Movie<br>    }<br>    <br>    type Mutation {<br>       addMovie(name: String!, genre: String!, year :String!): Movie<br>    }</pre><pre>type Movie {<br>        name : String,<br>        genre : String,<br>        year : String<br>    }<br>`)</pre><pre>module.exports = movieSchema;</pre><h4>Step 10</h4><p>We have now completed the setup for our frontend and backend applications. Let’s start our dev servers for node.js and react as seen below.</p><p><strong>React.js dev server</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-DzixvSC2fqZPFJEvCCHA.png" /></figure><p><strong>Node.js backend server</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-lSgmGf5oOgfhxzu5wR6Q.png" /></figure><p><strong>GraphQL (GraphiQL) server will be running on </strong><a href="https://localhost:4000/graphql"><strong>https://localhost:4000/graphql</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrINTNp2IuwcXYhkYPSFRg.png" /></figure><p>If the setup is complete without any erros you will see data getting added under the movies collection in MongoDB as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZbpRYqHf1tpMQfc_MLK1Q.png" /></figure><blockquote><strong><em>An investment in knowledge always pays the best interest.</em></strong></blockquote><blockquote>-Benjamin Franklin</blockquote><p>If you enjoyed setting up your application and loved reading this article kindly share this article to a wider audience to help simplify the setup and spread knowledge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=297409232465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Business Potential: Seamlessly Integrating Amazon PayFort with OutSystems for Secure and…]]></title>
            <link>https://medium.com/@joshuasalema/unlocking-business-potential-seamlessly-integrating-amazon-payfort-with-outsystems-for-secure-and-e4493d6a2d92?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4493d6a2d92</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 07:17:41 GMT</pubDate>
            <atom:updated>2024-09-12T12:54:29.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Business Potential: Seamlessly Integrating Amazon PayFort with OutSystems for Secure and Efficient Payment Solutions</h3><p>In today’s digital economy, integrating robust payment solutions into your applications is crucial for enhancing user experience and driving business growth. OutSystems, a leading low-code development platform, empowers organizations to rapidly build and deploy applications. When combined with Amazon PayFort, a trusted payment gateway in the Middle East and North Africa (MENA) region, you can create secure, seamless payment experiences for your customers. Let’s explore how integrating Amazon PayFort with OutSystems can benefit your business.</p><p><strong>Why Choose Amazon PayFort?</strong></p><p>Amazon PayFort stands out as a reliable payment gateway for businesses looking to process online payments securely. Here are some key reasons why businesses opt for Amazon PayFort:</p><ul><li><strong>Security and Compliance:</strong> Amazon PayFort adheres to stringent security standards and compliance regulations, ensuring that sensitive payment information is protected.</li><li><strong>Regional Expertise:</strong> It caters specifically to the MENA region, supporting local currencies and payment methods tailored to the preferences of regional customers.</li><li><strong>Flexible Integration:</strong> Amazon PayFort offers easy-to-integrate APIs and plugins for various platforms, making it straightforward to incorporate into your OutSystems applications.</li></ul><p><strong>Benefits of Integrating with OutSystems</strong></p><p>OutSystems provides a powerful platform for building applications quickly and efficiently, making it an ideal choice for integrating payment gateways like Amazon PayFort. Here’s how your business can benefit:</p><ul><li><strong>Accelerated Development:</strong> OutSystems’ low-code environment allows developers to drag and drop components, reducing the time and effort required to build and deploy payment functionalities.</li><li><strong>Scalability:</strong> As your business grows, OutSystems ensures that your applications can scale seamlessly. Integration with Amazon PayFort supports this scalability by handling increased transaction volumes efficiently.</li><li><strong>User Experience:</strong> By integrating Amazon PayFort, you enhance the checkout experience for your customers. They can make payments using their preferred methods, fostering trust and satisfaction.</li></ul><p><strong>Steps to Integrate Amazon PayFort with OutSystems</strong></p><p>Integrating Amazon PayFort with OutSystems can be simplified into the following steps:</p><ol><li><strong>Register and Configure Amazon PayFort:</strong> Sign up for an Amazon PayFort account and configure your merchant settings to receive API credentials.</li><li><strong>Develop the Integration:</strong> Utilize OutSystems’ visual development tools to create screens and workflows for payment processing. Use the Amazon PayFort API documentation to integrate payment features into your application.</li><li><strong>Test and Deploy:</strong> Thoroughly test the integration in a staging environment to ensure smooth functionality and security. Once validated, deploy the integrated solution to production.</li><li><strong>Monitor and Optimize:</strong> Continuously monitor transaction performance and user feedback. Optimize the payment flow based on analytics to improve conversion rates and user satisfaction.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIMB3o8GZtNge0EXP5i8nA.png" /><figcaption>Payment Integration Process</figcaption></figure><p><strong>Payment Integration Process Setup Prerequisites</strong></p><ul><li>Admin should have merchant account credentials/keys required to interface with the payment gateway. Credentials like access_code, merchant_identifier, request_phrase, and response_phrase will need to be configured.</li><li>The admin should have installed OutSystems Integration Studio to create .NET extensions.</li><li>Admin should have installed Visual Studio 2019/2022. Developers need to write .NET code to generate the signature for payment.</li><li>The admin should have permission to publish the extension code in Integration Studio.</li><li>The admin requires deployment permission to deploy the extension from the developer to another environment.</li></ul><p><strong>Let’s dive further into the implementation:</strong></p><ol><li><strong>Create a payment service application in OutSystems.</strong></li><li><strong>Create a .NET connector to generate signatures.</strong></li><li><strong>Use the signatures to call the Payment API, which will redirect to the Amazon PayFort payment portal.</strong></li><li><strong>Use the response signature to validate the response after payment processing.</strong></li><li><strong>Store the whole response received from the payment gateway in the central payment service module and the relevant subset of parameters in the consumer module.</strong></li></ol><p><strong>Creating a SHA Request &amp; Response Passphrase</strong></p><p>Redirection to the Amazon PayFort payment gateway involves creating a SHA-256 request signature with the following parameters:</p><p><strong>Signature Generation:</strong></p><ol><li><strong>Sort all Amazon Payment Services request parameters</strong> (both mandatory and optional) in ascending alphabetical order based on the parameter names.</li><li><strong>Concatenate</strong> the parameter name with the value separated by = (e.g., param_name=param_value).</li><li><strong>Concatenate all the parameters directly</strong> without any separator (e.g., param_name1=param_value1param_name2=param_value2).</li><li><strong>Add the Merchant’s Passphrase</strong> at the beginning and end of the parameters string (e.g., REQUESTPHRASEparam_name1=param_value1param_name2=param_value2REQUESTPHRASE).</li><li><strong>Use the SHA or HMAC SHA function</strong> to generate the SHA or HMAC SHA value of the resulting string depending on the type of SHA or HMAC SHA selected by the Merchant.</li></ol><p>Please note that all values mentioned in the examples are fictitious.</p><p><strong>The following is an example of the Request Parameters:</strong></p><ul><li>command = PURCHASE</li><li>merchant_reference = Test010</li><li>amount = 2120</li><li>access_code = SILgpo7pWbmzuURp2qri</li><li>merchant_identifier = MxvOupuG</li><li>currency = AED</li><li>language = en</li><li>customer_email = test@gmail.com</li><li>req_passphrase = REQPASS</li><li>redirect_url = <a href="http://www.myredirectpage.com/">www.myredirectpage.com</a></li></ul><p><strong>Below are the Merchant signature settings from the back office:</strong></p><ul><li><strong>SHA Request Phrase:</strong> PASS</li><li><strong>SHA-Type:</strong> SHA-256</li></ul><p>These parameters have to be sorted in ascending order as seen below to generate the response signature:</p><pre>REQPASSaccess_code=SILgpo7pWbmzuURp2qriamount=1000command=PURCHASEcurrency=AEDcustomer_email=test@gmail.comlanguage=enmerchant_identifier=MxvOupuGmerchant_reference=Test010REQPASS</pre><p>Below is the C# code to generate the SHA 256 signature</p><pre>using System;<br>using System.Security.Cryptography;<br>using System.Text;<br><br>public class PayFortSignatureGenerator<br>{<br>    public static string GenerateSignature(string requestPhrase, string responsePhrase, string[] parameters)<br>    {<br>        // Step 1: Sort parameters<br>        Array.Sort(parameters);<br><br>        // Step 2: Concatenate parameters<br>        StringBuilder concatenatedParams = new StringBuilder();<br>        foreach (var param in parameters)<br>        {<br>            concatenatedParams.Append(param);<br>        }<br><br>        // Step 3: Add passphrase<br>        string stringToHash = $&quot;{requestPhrase}{concatenatedParams}{responsePhrase}&quot;;<br><br>        // Step 4: Compute SHA-256 hash<br>        using (SHA256 sha256 = SHA256.Create())<br>        {<br>            byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(stringToHash));<br><br>            // Step 5: Convert to hexadecimal string<br>            StringBuilder hashString = new StringBuilder();<br>            foreach (byte b in hashBytes)<br>            {<br>                hashString.Append(b.ToString(&quot;X2&quot;)); // Convert byte to hexadecimal string<br>            }<br><br>            return hashString.ToString();<br>        }<br>    }<br><br>    public static void Main()<br>    {<br>        // Example parameters<br>        string requestPhrase = &quot;REQPASS&quot;;<br>        string responsePhrase = &quot;RESPONSEPASS&quot;;<br>        string[] parameters = <br>        {<br>            &quot;command=PURCHASE&quot;,<br>            &quot;merchant_reference=Test010&quot;,<br>            &quot;amount=1000&quot;,<br>            &quot;access_code=SILgpo7pWbmzuURp2qri&quot;,<br>            &quot;merchant_identifier=MxvOupuG&quot;,<br>            &quot;currency=AED&quot;,<br>            &quot;language=en&quot;,<br>            &quot;customer_email=test@gmail.com&quot;<br>        };<br><br>        string signature = GenerateSignature(requestPhrase, responsePhrase, parameters);<br>        Console.WriteLine(&quot;Generated SHA-256 Signature: &quot; + signature);<br>    }<br>}</pre><p>After running this through the SHA-256 algorithm, the following signature is obtained:</p><pre>Signature = 94C38AFC7BDAE0114FC8C740EDF12416F22998241CE4B4EA70D5521233A2C882</pre><p>Using the above signature, submit a POST redirection request to the Amazon PayFort payment gateway with the parameters indicated with $. To do this, create a JavaScript action using the JavaScript Widget and pipe the signature response along with other required parameters in a single Payment action</p><pre>// Define the request parameters<br>var requestParams = {<br>  &quot;command&quot;: $parameters.command,<br>  &quot;access_code&quot;: $parameters.access_code,<br>  &quot;merchant_identifier&quot;: $parameters.merchant_id,<br>  &quot;merchant_reference&quot;: $parameters.merchant_ref,<br>  &quot;amount&quot;: $parameters.amount,<br>  &quot;currency&quot;: $parameters.curr,<br>  &quot;language&quot;: $parameters.lang,<br>  &quot;customer_email&quot;: $parameters.cust_email,<br>  &quot;return_url&quot;: $parameters.return_url,<br>  &quot;signature&quot;: $parameters.signature<br>  // Add other parameters as needed<br>};<br>// Create an HTML element<br>// Create a form element<br>var form = document.createElement(&#39;form&#39;);<br>form.action = paymentGatewayURL;<br>form.method = &#39;post&#39;;<br>form.name = &#39;frm&#39;;<br>// Add hidden input fields to the form<br>for (var key in requestParams) {<br>  if (requestParams.hasOwnProperty(key)) {<br>    var input = document.createElement(&#39;input&#39;);<br>    input.type = &#39;hidden&#39;;<br>    input.name = key;<br>    input.value = requestParams[key];<br>    form.appendChild(input);<br>  }<br>}<br>// Create a script element to submit the form automatically after it&#39;s appended to the body<br>var script = document.createElement(&#39;script&#39;);<br>script.type = &#39;text/javascript&#39;;<br>script.innerHTML = &#39;document.frm.submit();&#39;;<br>// Append the form and script elements to the body<br>document.body.appendChild(form);<br>document.body.appendChild(script);<br>console.log(document.body);</pre><p>After the above JavaScript code has executed, the PayFort will automatically redirect from the client application to the payment gateway using the “paymentGatewayURL” and you will see the screen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Buv3NvTt6C3BLpMsy-yIZA.png" /></figure><p><strong>Once the payment is processed, Amazon PayFort will automatically redirect to the URL we provided in the </strong><strong>redirect_url parameter while creating the request signature.</strong></p><p>The redirect_url has to be a POST request, which will be treated as a webhook by Amazon PayFort to send back the below JSON:</p><pre>{<br>  &quot;response_message&quot;: &quot;Success&quot;,<br>  &quot;amount&quot;: &quot;21200&quot;,<br>  &quot;response_code&quot;: &quot;14000&quot;,<br>  &quot;signature&quot;: &quot;d02ab49f6117fd8dc03a3708160e42908dfaa3e95208c491928337d809c9a0dd&quot;,<br>  &quot;merchant_identifier&quot;: &quot;f607a65f&quot;,<br>  &quot;access_code&quot;: &quot;hhw5KWsQTbx6ny1IXYVO&quot;,<br>  &quot;card_number&quot;: &quot;5123********0008&quot;,<br>  &quot;card_holder_name&quot;: &quot;Jamie&quot;,<br>  &quot;payment_option&quot;: &quot;MASTERCARD&quot;,<br>  &quot;expiry_date&quot;: &quot;3901&quot;,<br>  &quot;merchant_reference&quot;: &quot;CM1117390360&quot;,<br>  &quot;fort_id&quot;: &quot;169996200018759633&quot;,<br>  &quot;language&quot;: &quot;en&quot;,<br>  &quot;eci&quot;: &quot;ECOMMERCE&quot;,<br>  &quot;authorization_code&quot;: &quot;310005&quot;,<br>  &quot;token_name&quot;: &quot;110be15d16d645b4890a102fe6a377f0&quot;,<br>  &quot;customer_email&quot;: &quot;jamie@jack.com&quot;,<br>  &quot;reconciliation_reference&quot;: &quot;424716010005&quot;,<br>  &quot;currency&quot;: &quot;AED&quot;,<br>  &quot;status&quot;: &quot;14&quot;<br>}</pre><p>Below are the steps to be followed to extract the response and redirect to a confirmation or error page post-payment processing:</p><ol><li><strong>Set the status code in this API to 302</strong>, indicating that the control will be redirected out of the API post-processing the response.</li><li><strong>Using the GetFormValue server action</strong>, extract each and every JSON key-value pair.</li><li><strong>Once all the key-value pairs are extracted</strong>, use the same C# signature extension created earlier to generate the reverse signature to verify against the signature obtained in the JSON response.</li><li><strong>If the signature received and the signature generated using the extension match</strong>, the client application will accept the response as success or failure and vice versa.</li><li><strong>The signature also contains a response_code</strong>, which is a combination of a 2-digit status and a 3-digit message as seen here.</li><li><strong>Irrespective of the result, the entire response received from the Amazon PayFort payment gateway needs to be stored</strong> in a central payment service module, which can be handy in case of reconciliations with the bank.</li><li><strong>Redirect the user to the necessary landing zone</strong>, i.e., page based on the processed outcome.</li></ol><blockquote><strong>“The journey of a thousand miles begins with one step. And the more you share, the more you will learn and grow.”</strong></blockquote><blockquote>— <strong>Lao Tzu</strong> &amp; <strong>Leonard Nimoy</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4493d6a2d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Real-Time Communication: A Comprehensive Guide to Exposing Webhooks in an OutSystems…]]></title>
            <link>https://medium.com/@joshuasalema/mastering-real-time-communication-a-comprehensive-guide-to-exposing-webhooks-in-an-outsystems-b11d36e2c171?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/b11d36e2c171</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 08:12:40 GMT</pubDate>
            <atom:updated>2024-03-13T06:04:49.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Real-Time Communication: A Comprehensive Guide to Exposing Webhooks in an OutSystems Application</h3><p>Webhooks serve as a dynamic communication mechanism between software systems, ensuring real-time data transmission without the need for continuous polling. In essence, they establish a streamlined method for one system to promptly notify another when specific events transpire. Unlike traditional polling, where systems repeatedly check for updates, webhooks allow for automatic transmission of information, fostering instant awareness and response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*F_JaReLkKTZc1TsA4MkaxA.jpeg" /></figure><p>These automated notifications are triggered by predefined events, such as a user sign-up or a completed transaction. By providing a designated URL endpoint, the receiving system, or subscriber, specifies where it wishes to receive these event-driven updates. The sending system, or publisher, then dispatches an HTTP POST request to this endpoint, carrying relevant event data — typically formatted in JSON. Subsequently, the subscriber processes this data, executing predetermined actions like updating databases, triggering workflows, or issuing user notifications. Webhooks, with their emphasis on immediacy and efficient event-based communication, have become integral in modern software development, enhancing the responsiveness and synchronization of diverse applications and services.</p><h4>How to expose Webhooks from an OutSystems Application?</h4><p>Creating webhooks in OutSystems provide a powerful mechanism for real-time communication between different systems and applications. Webhooks enable your OutSystems applications to send and receive data automatically when specific events occur, facilitating seamless integration and timely updates. With webhooks, you can streamline processes, enhance automation, and improve the responsiveness of your applications.</p><p>Webhooks are based on an event-driven architecture. You define specific events in your application (e.g., a new record creation, an update, or a user action), and the webhook is triggered when these events occur.</p><h4>Let’s build a Pub-Sub architecture in OutSystems using Webhooks</h4><ol><li>We will build a simple reactive web application in OutSystems to create an employee record.</li><li>Let us assume that for every new employee created, we want to trigger a notification to an external system.</li><li>To achieve the above we will use the <a href="https://www.outsystems.com/forge/component-overview/5249/webhooks-producer">Webhook Producer Forge component</a> available on OutSystems forge. This will act as the source/producer to facilitate the webhook trigger.</li><li>To simulate the Consumer we will use <a href="https://www.celigo.com/">Celigo Integrations Platform</a> to receive the webhook Payload.</li></ol><p><strong>Note</strong>: Any other application can be used as a consumer.</p><h4>Steps</h4><ol><li>Create a simple Employee OutSystems Reactive web application and bootstrap it using OutSystems AI Autogenerate capabilities.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EO_SQ0AbdN8ntmVxqqJgRQ.png" /><figcaption>Employee List</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfEL2jblPPJX19J26sDDvg.png" /><figcaption>Employee Details &amp; Trigger Webhook</figcaption></figure><p>2. Install the <a href="https://www.outsystems.com/forge/component-overview/5249/webhooks-producer">Webhooks Producer Forge component</a> from Outsystems Forge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhJEY8BPDcxMJC19HCTuyQ.png" /><figcaption>Webhooks Producer Forge Component</figcaption></figure><p>3. Add this component is added as a dependency via manage dependencies.</p><p>4. This component has various submodules and a back office application where the webhook configurations and related data are stored.</p><p>5. Once imported the component will be available in the server actions tab under logic with the below modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*6ligizz7EkSgYEaTmR7Zmg.png" /><figcaption>Webhooks Producer Actions</figcaption></figure><p>i) Under Authentication we can configure various authentication methods like OAuth, Basic etc as well as configure custom headers and generate secrets and access tokens</p><p>ii) The webhook signature can be validated by using the ValidateWebhookSignature server action.</p><p>iii) The actions under Webhooks Producer enable us to Define webhook events and trigger them as and when required in our application.</p><h4>Now let’s wire all of the above and create a Pub-Sub architecture</h4><ol><li>Let us get started by creating an event using the Webhooks Producer Module</li><li>Open the Webhooks Producer forge component and go to the static entity name WebhookEventType under the Data tab and add records for the the events you are expecting to trigger as seen below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*oc_CkWwFgzKVzrvntWPOMQ.png" /><figcaption>Webhooks Producer Component Database</figcaption></figure><p>3. Create a screen on the demo application and use the value from the static entity to create a Webhook Event as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBigCcWmZ7HsyzWCn2eC2A.png" /><figcaption>Creating Webhook Event Interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihlnara8Ouy32oB_pqnLrw.png" /><figcaption>WebhookEventType Database</figcaption></figure><p>4. Create a Consumer (Ex: Celigo) to consume the payload generated by the above events once they are triggered in an OutSystems Application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5s4grRkv8MKYYzN_0VGLg.png" /></figure><p>5. Let us now configure the Subscriber(listener) URL and trigger it whenever a new employee is created.</p><p>i) Copy the public listener URL from Celigo as seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSS35aKGl82NdDx96X_BsQ.png" /></figure><p>ii) Go to the Webhooks Producer application and open the webhook module in the browser and configure the webhook as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FaNUN_soqpUQQ1WWRYPkyw.gif" /><figcaption>Webhook Configuration</figcaption></figure><p>The Webhook configuration step allows us to set additional configurations as indicated below:</p><ol><li>Authentication: This module supports two types of authentication for webhook listener URL’s Basic authentication and OAuth authentication as seen below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCei_3Uk72xgAm0qyI9rGw.png" /><figcaption>Basic Authentication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQQRe6qVJno-F21vmOQpTA.png" /><figcaption>OAuth Authentication</figcaption></figure><p>2. <strong>Retry Policy</strong>: This policy defines the method to retry the call to the Subscriber incase the call to the configured url fails. There are two types of retry policies.</p><p>i) <strong><em>Retry with Linear Backoff</em></strong> - A linear retry policy will attempt to resend the request n number of times for a certain interval. As a best practice, the minimum interval is 3 and the maximum retry count is 60 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emQtWEld7OFR8ub_yH4fEA.png" /><figcaption>Retry with Linear Backoff</figcaption></figure><p>ii) <strong><em>Retry with Exponential Backoff</em></strong> - If your initial attempt to send a webhook fails, you don’t want to keep hammering the server incessantly. Instead, you wait for a brief moment and then try again. If it fails the second time, you wait a bit longer, and the cycle continues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irOTKtDTFY6_fD8752Qulg.png" /><figcaption>Retry with Exponential Backoff</figcaption></figure><p>3.<strong>Retention Policy</strong>: This policy defines how long the webhook activity history will be retained for logging/analysis purposes. There are two retention policies namely Retain history but discard payload and Retain history and payload as seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2UbBLB39MlszkueVIFt8A.png" /><figcaption>Retain history but discard payload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFrEn9u9JrxNqB8abwAMpw.png" /><figcaption>Retain history and payload</figcaption></figure><p>After the above steps are configured as per your requirement you should see a new webhook created on the dashboard as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnnN7oYVr4KQvtEVupfAeA.png" /><figcaption>New webhook created</figcaption></figure><p>Click on the webhook URL and go to the Webhook details page to subscribe to the events we created in the webhooks producer. In the below example, the Create Employee Webhook has been subscribed to. Hence, whenever a new employee is created and the corresponding webhook is triggered a request payload will be received on the Webhook listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdRhy7n19f1q_l08lJ3__Q.png" /><figcaption>Webhook event subscription</figcaption></figure><p>Next, we have to trigger the webhook event from the Reactive Outsystems application which in turn will send the desired payload from the producer as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axps6pwhI2LDDjPOnW0miQ.png" /><figcaption>Webhook Event Trigger</figcaption></figure><pre>{<br>  &quot;Id&quot;: 10,<br>  &quot;Firstname&quot;: &quot;Stan&quot;,<br>  &quot;Lastname&quot;: &quot;Lee&quot;,<br>  &quot;DOB&quot;: &quot;1978-02-15&quot;,<br>  &quot;Gender&quot;: &quot;Male&quot;<br>}</pre><p><strong>Note: </strong>Although the Webhooks Producer Forge component is a Traditional Web app component it will work with Reactive Applications.</p><p>Below is a detailed end-to-end demo of the working application :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFfO3hMhEH9Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFfO3hMhEH9Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFfO3hMhEH9Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/64171f22dfb6a66449bdd3e7004a5303/href">https://medium.com/media/64171f22dfb6a66449bdd3e7004a5303/href</a></iframe><blockquote><strong><em>In the social age, knowledge is only powerful if you share what you know.</em></strong></blockquote><p><strong><em>— Charles Helen Robinson</em></strong></p><p><em>If you found this article helpful do share it with a wider audience and help simplify learning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b11d36e2c171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event driven architecture in Outsystems using Celigo Integrations Platform]]></title>
            <link>https://medium.com/@joshuasalema/event-driven-architecture-in-outsystems-using-celigo-integrations-platform-27a731105777?source=rss-a363b96ba651------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a731105777</guid>
            <dc:creator><![CDATA[Joshua Salema]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 18:03:55 GMT</pubDate>
            <atom:updated>2022-12-26T05:37:47.524Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will provide a detailed overview of how to build an event driven architecture that enables trigger based data inflow and outflow in context of Outsystems and multiple external data inflow/outflow services. With event based architecture one can achieve easy decoupling of multiple dependent child services/applications with the parent application assuring minimum scope for error delta.</p><h3>What is event driven architecture?</h3><p>In the modern world most of the applications are developed using the microservices architecture which allows easy fault detection and prevention. An event-driven architecture uses events to trigger and communicate between decoupled services and is common in modern applications built with microservices. An event is a change in state, or an update, like an item being placed in a shopping cart on an e-commerce website. Events can either carry the state (the item purchased, its price, and a delivery address) or events can be identifiers (a notification that an order was shipped).</p><h4>Event based architecture has 3 essential components:</h4><ol><li>Event Producers</li><li>Event Routers</li><li>Event Consumers</li></ol><p>A producer publishes an event to the router, which filters and pushes the events to consumers. Producer services and consumer services are decoupled, which allows them to be scaled, updated, and deployed independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xtn4qvlDL0IcicrBHmJxQ.png" /><figcaption>Event Driven Architecture</figcaption></figure><h3>When to use event-driven architecture?</h3><p>As explained by AWS there are 4 key areas where one should use event driven architecture to simplify complex event based triggers to communicate with multiple decoupled services.</p><ol><li><strong>Scale and fail independently</strong></li></ol><p>By decoupling your services, they are only aware of the event router, not each other. This means that your services are interoperable, but if one service has a failure, the rest will keep running. The event router acts as an elastic buffer that will accommodate surges in workloads.</p><p>2. <strong>Develop with agility</strong></p><p>You no longer need to write custom code to poll, filter, and route events; the event router will automatically filter and push events to consumers. The router also removes the need for heavy coordination between producer and consumer services, speeding up your development process.</p><p>3. <strong>Audit with ease</strong></p><p>An event router acts as a centralized location to audit your application and define policies. These policies can restrict who can publish and subscribe to a router and control which users and resources have permission to access your data. You can also encrypt your events both in transit and at rest.</p><p>4.<strong> Cut costs</strong></p><p>Event-driven architectures are push-based, so everything happens on-demand as the event presents itself in the router. This way, you’re not paying for continuous polling to check for an event. This means less network bandwidth consumption, less CPU utilization, less idle fleet capacity, and less SSL/TLS handshakes.</p><blockquote><strong>Without knowledge action is useless and knowledge without action is futile</strong></blockquote><p>-Abu Bakr</p><p>The applications defined below play an important role in building the event-driven architecture on the Outsystems Platform</p><ol><li>Event Producer — Shopify</li><li>Event Router — Celigo Integrations Platform</li><li>Event Consumers — Outsystems API</li></ol><p>For this integration I will trigger events from Shopify and those events will be routed to an Outsystems endpoint (Learn more <a href="https://www.outsystems.com/">here</a>) using the Celigo Integrations Platform.</p><h3>Celigo Integrations Platform</h3><p>Celigo Integrations Platform is an iPaas which acts as a bridge between the event producer(Shopify) and any external decoupled services. In Celigo, an “integration flow” is considered as the movement of a record type plus any dependent sub-record types, from one application to the another. With over 250+ inbuilt connectors and custom REST integration capabilities Celigo offers a one stop solution for system-to-system data flow with minimum error delta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaNJt8IPU6FssFRRa15dGw.png" /><figcaption>Celigo Integrations Platform</figcaption></figure><h4>Create a new integration in Celigo</h4><ol><li>Login to the Celigo dashboard and select the create connection option.</li><li>Once you click on the create connection tab. Input the connection name and description and hit the Save &amp; Close button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1G33Z7eAKUr_E6x0CSeG5A.png" /><figcaption>Create Integration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OtsUD4gZ8Vj07z2LvCzZA.png" /><figcaption>Integration Created</figcaption></figure><p>Once a new integration is created it will show up in the connections list on the Celigo dashboard.</p><h4>Adding a connection in Celigo</h4><ol><li>Navigate inside the newly created integration (Dev Integration) and select the create connection option.</li><li>Give the connection a name and enter all the necessary details like base uri, authentication mechanism, mode, media type, rate limit, concurrency and hit the test connection button. If the entered values are correct you will get the screen below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3gryt1NpJbbYl-SibCZCA.png" /><figcaption>Connection Created</figcaption></figure><h4>Creating a flow</h4><ol><li>Click on the Flows tab and select the Create Flow(export) option.</li><li>A dropdown list with multiple pre-created connectors will be presented on clicking of Add sources. In our case we will select the Shopify options as we will be triggering events from Shopify and creating records in Outsystems.</li><li>Give a name to the source listener, generate the public url by clicking on the “+” icon and setup the listener.</li><li>If all works fine the the above steps you should see a screen like the one below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rU69C9gsGrT9qm55Ep1QA.png" /><figcaption>Shopify Listener</figcaption></figure><h4>Creating a destination</h4><ol><li>After creating the listener, click on the “+” icon to add any branching logic based on the input received from the listener.</li><li>If no branching logic is required proceed to adding a destination into which the data must flow.</li><li>After selecting the connection(In this case Outsystems Connection) select the appropriate HTTP method , relative URI, export type, paging if any and click on Save and close. Your Screen should look like below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXYFDaXD089vYkRIseWPZg.png" /><figcaption>Import Created</figcaption></figure><p>4. Learn more about creating API’s in outsystems <a href="https://www.youtube.com/watch?v=Hd1p3kTVpP4">here</a>.</p><p>5. Click on the enable flow option on the top right hand corner and enable this flow to capture requests made to the listener URL generated in the earlier steps. After completion of all steps you should see a flow dashboard like the one below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MJYw20epdnKhiZoc1VEpw.png" /><figcaption>Flow complete</figcaption></figure><p><em>References</em></p><ol><li><a href="https://aws.amazon.com/what-is/eda/">https://aws.amazon.com/what-is/eda/</a></li><li><a href="https://www.celigo.com/ipaas-integration-platform/">https://www.celigo.com/ipaas-integration-platform/</a></li></ol><p><em>If you found this article helpful do share it with a wider audience and help simplify learning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a731105777" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>