<?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 Jayant Gangwani on Medium]]></title>
        <description><![CDATA[Stories by Jayant Gangwani on Medium]]></description>
        <link>https://medium.com/@gangwanijayant737?source=rss-a1954cfcf938------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_qum2vrm2daqtERLgYAZNg.jpeg</url>
            <title>Stories by Jayant Gangwani on Medium</title>
            <link>https://medium.com/@gangwanijayant737?source=rss-a1954cfcf938------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:43:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gangwanijayant737/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[How Humans and AI Agents Actually Collaborate (Without Meetings)]]></title>
            <link>https://medium.com/@gangwanijayant737/how-humans-and-ai-agents-actually-collaborate-without-meetings-eb6e5d37000b?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6e5d37000b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 19:48:35 GMT</pubDate>
            <atom:updated>2026-08-31T19:48:35.183Z</atom:updated>
            <content:encoded><![CDATA[<p>If you read Parts 1 and 2 of Running Agents Overnight, this is the piece that makes the team durable. If you didn’t — start here. You can steal this without adopting overnight loops or an orchestrator.</p><p>Most teams don’t have a memory problem because they lack tools. They have one because whatever they’ve learned lives in the worst possible places: someone’s head, a Slack thread from three weeks ago, a comment on a ticket that’s since closed. Add AI agents into the mix and it gets worse — every session starts from zero unless someone hand-feeds it context, every single time.</p><p>Two more problems show up the moment you run agents for real:</p><p>1. Agents forget everything between sessions. Close the window, and today’s hard-won context is gone.</p><p>2. The moment a second person joins, you have two AI setups that know nothing about each other, quietly undoing each other’s work.</p><p>The answer to all of that turned out to be the same, and it’s almost boringly simple: a shared, git-tracked filing system that people and AI agents both read from and write to. The files are the memory. The files are also the collaboration protocol. No tool, no service, no plugin — just files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jeg54qoVw2zYNZZxacBIiw.png" /></figure><p>How to collaborate: six files, one ritual</p><p>We keep six plain markdown files in the repo. Both humans and agents open them first and update them last.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ojuJeDACBWDwhmWB_W4Nw.png" /></figure><p>Status — Where do things stand, and what’s the exact next step? Written by whoever just finished working. Updated every session.</p><p>Backlog — What’s broken or unfinished, and how urgent is it? Written by anyone who finds something. Updated as discovered.</p><p>Decisions — Why did we choose this, and what did we reject? Written by whoever made the call. Updated when a real choice is made.</p><p>Session log — What actually happened, session by session? Everyone writes here. Append-only. Every session.</p><p>Risks / known issues — What could still go wrong, and what’s the workaround? Anyone who spots one. As discovered.</p><p>Memory index — Where’s the deeper context, so I don’t re-read everything? Whoever writes the deep note. Occasionally.</p><p>Five minutes reading these before you start replaces an hour of “wait, why did we do it this way” and “didn’t we already find this bug.”</p><p>The one rule that makes collaboration work</p><p>Read first, write last.</p><p>Every session — human or AI — opens with the status file, not a re-briefing from a person. It ends by updating that file, appending to the session log, and filing anything new to the backlog. Skip either half and the files quietly rot into fiction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Pg84_ok1BBks8PV0ShlNQ.png" /></figure><p>One caveat: a status file can lie by omission. If nobody checks it against the actual code, it will happily keep reporting “all good” long after that stopped being true. The fix is cheap — glance at what’s actually changed since it was last written, before you trust it — but skipping that glance is the single most common way this system quietly fails.</p><p>Memory is a filing system, not a bigger context window</p><p>People assume the fix for “the agent forgot” is a longer memory or a bigger context window. It isn’t. The fix is giving agents a place to write things down that outlives the session — and a habit of reading it first.</p><p>The “memory” isn’t in the model. It’s in the repo. Any agent, any session, any day can rehydrate from it.</p><p>This also quietly fixes a classic failure: an agent that finds a second bug while fixing the first one. Without a filing habit, that second bug evaporates. With it, the agent stops, files it in the backlog, and moves on — so it’s still there next week when we choose to deal with it.</p><p>Label every finding, including “no”</p><p>A backlog only stays useful if you can tell, at a glance, which of the (eventually hundreds of) filed issues need attention today. We use a small set of labels, applied honestly:</p><p>Fix now — blocks the current phase of work</p><p>Fix later, on a named trigger — “deal with this when we’re back working on this area,” not just “someday”</p><p>Nice-to-have — real, but only worth doing if time allows</p><p>Explicitly dismissed — a reason is recorded, even when the answer is “we’re not doing this”</p><p>Done — closed, kept for the audit trail, not deleted</p><p>The one that surprised me is how much value sits in “explicitly dismissed, with a reason.” The default instinct is to delete a finding you’ve decided not to act on — and months later someone rediscovers the same thing and re-litigates it from zero. Writing down why not is cheaper than re-arguing it later.</p><p>Verify memory before you trust it</p><p>Here’s the failure mode that taught me the most. A status file can keep confidently reporting “this area is fully covered” long after that stopped being true — and every agent that reads it and moves on is doing exactly what it was told, while quietly reporting on a version of the product that no longer exists.</p><p>A real example from my own project: a testing checklist for one feature area had sat at roughly a dozen items for weeks, all reported passing. When someone finally checked how much the underlying code had moved since that checklist was last honestly written, dozens of commits and several entirely new capabilities had shipped in that exact area — none of them named anywhere in the checklist. Three separate sessions had read the file, seen “all green,” and moved on. All three were technically correct and all three were wrong.</p><p>So the ritual is slightly sharper than “read status first”: read status first, spot-check that status against what’s actually on disk, then do the work. A memory file is a claim about reality. Claims need to be checked.</p><p>Why this is actually a collaboration tool</p><p>The magic isn’t the files individually — it’s what they let you skip. Two people, or two people each running their own AI agent, don’t need a standup, a handoff call, or a shared Slack thread to stay in sync. One finishes a session and writes down what happened and what’s next. The other opens the same files the next day and picks up exactly there.</p><p>The backlog is the shared to-do list, so a finding never depends on someone remembering to mention it out loud.</p><p>The decisions log stops the same argument from happening twice, months apart.</p><p>The status file is the standup that never needs scheduling.</p><p>The session log is a handoff note nobody has to write specially, because it’s already a habit.</p><p>Not every file needs the same collision rule. Anything append-only — backlog, session log — can be shared by any number of people at once. Anything that holds one current position — status — needs to split per person once more than one person is active, so nobody overwrites someone else’s “here’s where I am.”</p><p>Two people, two orchestrators, one shared memory</p><p>Here’s the part I find genuinely powerful. My collaborator and I don’t sit in the same session. Each of us has our own orchestrator. Mine runs my agents; theirs runs theirs. We’re often working on the same product, sometimes near the same code.</p><p>We almost never need to interrupt each other to coordinate, because both orchestrators read and write the same shared files. When my side finds and files an issue, tomorrow their side already knows. When their side finishes a big piece and updates status and the session log, my side picks it up on the next run.</p><p>The files are the meeting. The status file is the standup. The backlog is the shared to-do. The session log is the handoff note. Two humans and their agent teams stay in sync asynchronously, through git, instead of through constant real-time chatter.</p><p>(If you’re also using private git worktrees per agent — from Part 2 — that keeps the code collision-free while these files keep the thinking collision-free.)</p><p>Promote repeated procedures to skills</p><p>Some things we do the same way every time — how we review a change, how we prepare a release, how we verify a fix end-to-end. Instead of re-explaining those every session, they get promoted to skills: named, reusable procedures agents can invoke. The first time you catch yourself explaining the same workflow twice, that’s the signal. It’s how the team’s know-how compounds instead of resetting.</p><p>If you only do one thing</p><p>Start with a status file that has exactly one non-negotiable line: Next step (exact).</p><p>Not “keep working on the thing” — the literal next action, specific enough that a stranger, or a fresh AI session with zero memory, could do it without asking a single question. Everything else on this list earns its place over time; that one line pays for itself on day one.</p><p>What to steal</p><p>Templates, diagrams, and the full kit:</p><p><a href="https://github.com/Jayant2907/coding-agent-harness">https://github.com/Jayant2907/coding-agent-harness</a></p><p>Copy these six files into your repo (plus GOAL.md and CONTRACT.md if you run unattended agents):</p><p>STATUS.md<br>BACKLOG.md<br>DECISIONS.md<br>SESSION-LOG.md<br>RISKS.md<br>MEMORY-INDEX.md</p><p>Rule: read first, write last — and verify status against the real code before you trust it.</p><p>Related reading in this series (optional):<br>Part 1 — /loop, the goal file, and the overnight contract<br><a href="https://medium.com/@gangwanijayant737/how-i-taught-claude-code-to-work-the-night-shift-bb1b555ef734">https://medium.com/@gangwanijayant737/how-i-taught-claude-code-to-work-the-night-shift-bb1b555ef734</a></p><p>Part 2 — one orchestrator, many agents, private worktrees, mandatory review<br><a href="https://medium.com/@gangwanijayant737/i-run-a-team-of-ai-agents-with-one-orchestrator-heres-what-keeps-it-from-turning-into-chaos-ed59dbf73b12">https://medium.com/@gangwanijayant737/i-run-a-team-of-ai-agents-with-one-orchestrator-heres-what-keeps-it-from-turning-into-chaos-ed59dbf73b12</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6e5d37000b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Run a Team of AI Agents With One Orchestrator. Here’s What Keeps It From Turning Into Chaos.]]></title>
            <link>https://medium.com/@gangwanijayant737/i-run-a-team-of-ai-agents-with-one-orchestrator-heres-what-keeps-it-from-turning-into-chaos-ed59dbf73b12?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed59dbf73b12</guid>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 19:58:50 GMT</pubDate>
            <atom:updated>2026-08-30T19:58:50.220Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 2 of Running Agents Overnight. Read Part 1 first:<br><a href="https://medium.com/@gangwanijayant737/how-i-taught-claude-code-to-work-the-night-shift-bb1b555ef734">https://medium.com/@gangwanijayant737/how-i-taught-claude-code-to-work-the-night-shift-bb1b555ef734</a></p><p>Most people use an AI coding agent the way you’d use a very fast intern: give it one task, watch it work, take the result. That’s genuinely useful. But it hits a wall the moment your work looks like real software work — many things happening at once, across days, with correctness that actually matters, and a teammate touching the same codebase.</p><p>So my collaborator and I stopped using our agent as a single worker. We started running one instance as an orchestrator — a manager that almost never writes code itself. It breaks the work down, hands each piece to a subagent, waits for them to report back, and then does the one thing that makes the whole thing safe: it reviews everything before anything ships.</p><p>Here’s the model, in plain terms.</p><h3>The orchestrator doesn’t do the work. It runs the work.</h3><p>The orchestrator’s job is decomposition, delegation, verification, and integration. On a normal afternoon it might be running four or five subagents at once:</p><p>a research agent reading across the codebase to answer “how does X actually work today?”</p><p>two build agents, each implementing a separate feature or fix</p><p>a review agent tearing apart what a build agent just produced</p><p>Each subagent gets its own tailored prompt — think of it as a profile: who you are, exactly what to do, how to prove it worked, and what to do when finished. A research agent’s profile says “read, don’t change, report findings.” A build agent’s says “implement this, test it live, commit, report the diff.” A review agent’s says “try to break this; assume it’s wrong until proven right.”</p><p>The orchestrator kicks them off, keeps working on other things, and collects each one as it reports back. Some tasks fan out one problem into several agents — three different agents attacking the same bug from different angles, then comparing notes. Others run several unrelated tasks in parallel — a UI tweak, a data-export fix, and a business-rule fix, all in flight at once. The orchestrator is the only one holding the whole board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cAcMbeXtE0vFWObC-Gcag.png" /></figure><h4>The non-obvious part: agents need their own private workspace</h4><p>The first time you run two agents editing code at the same time, you learn a painful lesson: they overwrite each other. One agent’s half-finished change lands in the middle of another’s, and now you can’t tell whose work is whose.</p><p>The fix is git worktrees — and if you take one practical thing from this post, take this. A worktree is a separate, private copy of the same repository, on its own branch. Each build agent gets its own worktree. They can all edit “the same files” at the same time without ever colliding, because each one is really editing its own isolated copy. When an agent is done, its branch gets reviewed and merged in cleanly. No stepped-on toes, no mystery changes.</p><p>This one decision is what turns “a few agents I babysit one at a time” into a team that actually runs in parallel.</p><p><strong>Review is not optional</strong>. It’s the whole point.</p><p>Here’s the rule we never break: nothing an agent produces is trusted until an independent review says so. Not the tests passing. Not a green checkmark. An actual review — a separate agent, and then the orchestrator, reading the real source and checking the real behavior — before anything merges.</p><p>Why so strict? Because agents are confident even when they’re wrong. A build agent will hand you a beautiful summary that says “verified, all good,” and it’ll be 90% right and 10% quietly broken. The review layer exists to catch that 10%.</p><p>And it catches the orchestrator too. In one recent session, my orchestrator flagged what looked like a data problem — duplicate-looking records piling up. The review pass proved the orchestrator itself had misread the data: those weren’t duplicates, they were intentional history. No code got changed on a false alarm. That only happened because “review before you trust” applies to everyone, including the manager.</p><h3>What one loop actually looks like</h3><p>A real, small example, start to finish:</p><p>1. I ask a plain-English question: “this date-cutoff logic looks wrong for one of our edge cases.”</p><p>2. The orchestrator investigates (a read-only research pass) and finds the root cause — the same setting was being interpreted three different ways in three parts of the code.</p><p>3. It writes a precise profile and hands a build agent the fix, in its own worktree.</p><p>4. The agent implements it, tests it against the live system, and reports back with the diff and evidence.</p><p>5. The orchestrator reviews it against the source, runs the change on the real app to watch the behavior, confirms it, and merges.</p><p>6. It files the finding so the reasoning is never lost, and updates the shared status so a teammate’s setup will know about it tomorrow.</p><p>I stayed in the loop the whole time — I made the judgment calls at the forks, and at one point I told it to stop mid-task and it stopped immediately. The orchestrator scales the doing. It never takes the deciding away from me.</p><h3>Coming up</h3><p>That’s the model: one manager, many specialized agents, isolated workspaces, and review as a law rather than a nicety. But none of this survives if the agents forget everything the moment a session ends, or if a second person joins and the two setups quietly undo each other’s work. Part 3 is the memory-and-collaboration problem — solved, surprisingly, with something low-tech: shared files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed59dbf73b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Taught Claude Code to Work the Night Shift]]></title>
            <link>https://medium.com/@gangwanijayant737/how-i-taught-claude-code-to-work-the-night-shift-bb1b555ef734?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1b555ef734</guid>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 19:47:44 GMT</pubDate>
            <atom:updated>2026-08-30T19:47:44.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgyxd6PLJfk__OMJLj0G0w.png" /></figure><p>Running Agents Overnight (and whenever else you’re not at the desk)—Part 1: /loop, the goal file, and the contract that keeps it honest</p><p>I used to treat my coding agent like an intern I had to hover over. Every few minutes: “keep going,” “yes, now do the next part,” “wait, don’t touch that file.” The moment I looked away, it either stalled waiting for me, or it “helpfully” did five things I never asked for.</p><p>Then I found two small habits that changed how I work with Claude Code entirely: /loop, and a lightweight technique I now just call ”the goal file.” Together, they let an agent keep working for hours—sometimes overnight—and hand me something safe and reviewable in the morning, instead of a mess.</p><p>This is Part 1 of a series on running Claude Code unattended. Today: the two primitives, and the “contract” I write before every overnight run so it doesn’t go off the rails.</p><p>The first primitive: /loop</p><p>/loop does one simple thing: it re-runs a prompt on a cadence—every 30 seconds, every 5 minutes, or “whenever the model thinks is reasonable”—until you stop it or it hits a condition you set.</p><p>That’s it. No magic. A babysitting instruction, repeated.</p><p>Some plain examples:</p><p>- /loop 30s check if the build finished; if it failed, read the error and fix it<br>- /loop run the test suite; stop once two runs in a row are clean<br>- /loop read today’s task list, do the next item, update the list</p><p>The unlock isn’t the repetition—it’s that each “tick” of the loop can read where it left off and pick up from there. Which brings me to the second habit.</p><p>The second primitive: the goal file</p><p>Here’s the part most people miss: you don’t need a special feature to give an agent a target. You just need a short file that states, in plain language, what “done” looks like—and you tell the agent to check it, and tick it off, every single tick.</p><p>This is also where “big” tasks stop being scary. A whole feature is too large for one tick to swallow safely—so the goal file’s real job is to break it into phases, and each phase into small, checkable steps. I call mine GOAL.md:</p><p>## Goal<br>Ship a complete notification system: in-app bell, email digests, and per-user preferences.</p><p>Phase 1—Data layer<br>- [ ] Notification table + migration<br>- [ ] Read/unread state tracking</p><p>Phase 2—Backend<br>- [ ] Create-notification endpoint<br>- [ ] Mark-as-read endpoint<br>- [ ] Nightly email-digest job</p><p>Phase 3—Frontend<br>- [ ] Notification bell + dropdown<br>- [ ] Preferences page (per-type email on/off)</p><p>Phase 4—Polish<br>- [ ] One event never fires two notifications<br>- [ ] End-to-end test covering all three channels</p><p>Notice what this does to a genuinely big feature: it’s no longer one intimidating blob called “add notifications.” It’s eleven small, independently checkable steps, grouped into four phases with a natural order. Every tick of the loop reads this file, picks the smallest unchecked box, does only that, and ticks it only once it’s verified—not merely attempted. A vague “keep working on notifications” becomes something both the agent and I can objectively track, phase by phase, overnight.</p><p>That’s the whole trick behind Part 1: /loop gives you repetition; a goal file gives that repetition a stopping point.</p><p>Why “just let it loop” is a bad idea</p><p>Here’s what I discovered the hard way, early on: a loop with no rules is a liability, not a convenience. Left alone, an agent will happily:</p><p>- Restart a server you didn’t want touched<br>- Wander outside the one folder you meant it to change<br>- Burn through your token budget on a task that should’ve taken five minutes<br>- Or just… keep “improving” things forever, because nobody told it when to stop</p><p>None of that is the agent being reckless. It’s doing exactly what a loop does: repeating, without a fence around it. The fence is on you to build.</p><p>The contract: seven questions, answered once, obeyed every tick</p><p>Before I let anything run unattended—especially overnight—I write a short “contract” at the top of the loop prompt. It’s just answers to seven questions. I fill these in fresh for every project, but the questions never change:</p><p>1. Cadence—When does a tick fire? Fixed interval, or let the model self-pace? (e.g., “every 3 minutes” vs. “as soon as the last step finishes”)<br>2. Guardrails—What can never happen, no matter what? (e.g., “never restart a shared server,” “never force-push,” “never touch the payments folder”)<br>3. Scope—Where is it allowed to make changes? A branch, a folder, a set of files—named explicitly, not implied.<br>4. Action—What does one tick actually do? The smallest unit of work, followed immediately by a way to check it worked (a test, a build, a read-only query).<br>5. Budget—What’s the ceiling? How many helper agents per tick, how many tokens, how many retries before giving up on one approach.<br>6. Stop conditions—When does it park and wait for me? All goal-file boxes checked; three failed attempts at the same step in a row; or it needs something only I can approve (a restart, a real answer, a judgment call).<br>7. Report—What must every tick tell me? What it did, how it verified that, and what’s next—written down, not just implied by a green checkmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YERhAJk71KBousUyVnvHKA.png" /></figure><p>Answer those seven once, and you can hand the loop a task and walk away—because it now knows what it’s allowed to do, how far it can go, and exactly when to stop and wait for you instead of guessing.</p><p>Putting it together: a small worked example</p><p>Say I want an overnight run that builds that notification system. My contract might read:</p><p>Cadence: self-paced, no fixed timer. Guardrails: never touch the email-sending credentials or run a destructive migration; if a step needs a live server or a real email to go out, stop and ask. Scope: only files under /notifications/ and the shared UI shell it plugs into, branch feature/notifications only. Action: one unchecked box from GOAL.md per tick, in phase order; verify with that step’s test or a build check. Budget: at most one helper agent per tick. Stop: every phase in GOAL.md checked, or three failed attempts on the same box. Report:** box completed, how it was verified, next box.</p><p>That’s maybe eight lines of setup. In exchange, I’ve woken up more than once to find a whole phase done—say, the entire data layer and backend, cleanly separated into small commits, each backed by a real check—instead of one giant, unreviewable diff, or a half-built feature with the frontend expecting an API that was never finished.</p><p>What this actually buys you</p><p>The honest version of what changed for me: I stopped thinking of /loop as “let the AI run wild for a while” and started thinking of it as delegation with a written brief—the same brief I’d give a junior engineer working a night shift I couldn’t personally supervise. Clear cadence, clear no-go zones, one task at a time, a way to verify it, a budget, a stopping point, and a report waiting for me in the morning.</p><p>That’s the whole idea. Two primitives—/loop and a goal file—plus one habit: write the seven-point contract before you walk away, not after something goes wrong.</p><p>Coming up</p><p>Part 2 is about what happens when one loop isn’t enough—how I coordinate several agents working on different pieces of the same project at once, without them stepping on each other (the “orchestrator” pattern). Part 3 gets into the memory files and reusable skills that let an agent stay coherent across days, not just one overnight run.</p><p>If you’ve tried running Claude Code unattended and hit a wall—or a 2 a.m. surprise—I’d genuinely like to hear about it in the comments.</p><p>Templates for GOAL.md and the 7-point contract: [GitHub—running-agents-overnight](#)—paste the repo URL after you publish it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1b555ef734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elastic reindexing (Dynamic mapping)]]></title>
            <link>https://medium.com/@gangwanijayant737/elastic-reindexing-dynamic-mapping-42a98a6bd53a?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a98a6bd53a</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[re-indexing]]></category>
            <category><![CDATA[elasticsearch-reindex]]></category>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 17:36:23 GMT</pubDate>
            <atom:updated>2024-04-18T04:54:46.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQ3YDimCr0bstz9RKa9h8A.png" /></figure><p>Use cases- It happens quite often that your elastic index is flooded with more than 1000 fields ,or you need to explicitly change the data type of a field( including values ) in a <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-field-mapping.html">dynamic mapping</a>. A solution to this problem would be to re-index .</p><p>Let’s say I have an index named Sheet and that is corrupted . We will take a simple example to remove a field <strong>rowsOrder</strong> while reindexing -</p><pre>POST /_reindex<br>{<br>  &quot;source&quot;: {<br>    &quot;index&quot;: &quot;sheet&quot;<br>  },<br>  &quot;dest&quot;: {<br>    &quot;index&quot;: &quot;new_sheet&quot;<br>  },<br>  &quot;script&quot;: {<br>    &quot;source&quot;: &quot;ctx._source.remove(&#39;rowsOrder&#39;)&quot;<br>  }<br>}</pre><p>Coming to a second use case where data type of a field has to be changed. If you mistakenly store a date field into an existing field with dynamic data type configuration elastic will automatically change its type to date. To avoid this you have to make a new index with predefined mapping for this field and make a ingest pipeline to avoid this in future.</p><pre>PUT /sheet_new/_mapping<br>{<br>  &quot;properties&quot;: {<br>    &quot;Rows&quot;:{<br>      &quot;properties&quot;:{<br>    &quot;Column2&quot;: { //column2 is the field name<br>      &quot;type&quot;: &quot;text&quot;  // data type<br>      # Add any other relevant mapping settings here<br>    }<br>      }<br>    }<br>  }<br>}</pre><p>and now you can re-index</p><pre>POST _reindex<br>{<br>  &quot;source&quot;: {<br>    &quot;index&quot;: &quot;sheet&quot;  // Source index<br>  },<br>  &quot;dest&quot;: {<br>    &quot;index&quot;: &quot;sheet_new&quot;  // Destination index<br>  },<br>  &quot;script&quot;: {<br>    &quot;source&quot;: &quot;&quot;&quot;<br>      if (ctx._source.containsKey(&#39;Column2&#39;)) {<br>        ctx._source.Column2.value = ctx._source.Column2.value.toString(); // Change the datatype of the field<br>      }<br>    &quot;&quot;&quot;<br>  }<br>}</pre><p>Also to make sure change in data type does not happen in future. Make a ingest pipeline. Here’s the template to change all fields that have name “value”.</p><pre>PUT _template/nested_value_template<br>{<br>  &quot;index_patterns&quot;: [&quot;sheet_new&quot;],  <br>  &quot;mappings&quot;: {<br>    &quot;_source&quot;: {<br>      &quot;enabled&quot;: true<br>    },<br>    &quot;dynamic_templates&quot;: [<br>      {<br>        &quot;nested_value_fields&quot;: {<br>          &quot;path_match&quot;: &quot;**.value&quot;,  // Match any path ending with &quot;.value&quot;<br>          &quot;mapping&quot;: {<br>            &quot;type&quot;: &quot;text&quot;<br>          }<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>In this way your data from all shards will be successfully transferred with updated schema configuration.</p><p>If you want to use the same name of index “sheet” , you can DELETE old index and create an alias for new index</p><p>Thanks . Do comment for questions or suggestions.</p><p>Your techy dude will be happy to help you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a98a6bd53a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ReactJs, GraphQL API, Nestjs & TypeORM]]></title>
            <link>https://blog.stackademic.com/using-reactjs-graphql-api-nestjs-typeorm-16548c050440?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/16548c050440</guid>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typeorm]]></category>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 17:32:58 GMT</pubDate>
            <atom:updated>2024-03-18T01:10:57.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*q9P1no45u0HTeEmFUU602g.jpeg" /></figure><p>Let’s start with React &amp; GraphQL by installing <strong>@apollo/client</strong></p><p>We will wrap our React app with apollo graphql client. This is how my apolloGraphQlClient looks like</p><pre>import { ApolloProvider, ApolloClient, InMemoryCache } from &#39;@apollo/client&#39;;<br> <br>const  apolloGraphQlClient = new ApolloClient({<br>    uri: process.env.GRAPHQL_URL, // Replace with your GraphQL API endpoint . In my case its server url<br>    cache: new InMemoryCache()<br>  });<br> <br>  export default apolloGraphQlClient</pre><p>Wrap your app.js or any parent component with the apollo client.</p><pre>import { ApolloProvider } from &#39;@apollo/client&#39;;<br>import apolloGraphQlClient from &#39;./GraphQL/DataAccessGraphQLClient&#39;;<br><br>function App(props) {<br> return (<br>  &lt;div&gt;<br>     &lt;ApolloProvider client={apolloGraphQlClient}&gt;<br>     &lt;Routes&gt;<br>    &lt;Route path=&#39;/login&#39; element={&lt;Login/&gt;} /&gt;<br>    &lt;Route path=&#39;/home&#39; element={&lt;AppContent page=&quot;workbook&quot; /&gt;} /&gt;<br>     &lt;/Routes&gt;<br>   &lt;/ApolloProvider&gt;<br>  &lt;/div&gt;<br>   );<br> }<br>export default App;</pre><p>Let’s write queries to fetch workspaces &amp; add a workspace. Workspace is just an entity that we have in our app. Make a file Queries.js and write this query.</p><pre><br>export const FETCH_WORKSPACES = gql`<br> query fetchWorkSpaces($user_email: String!){ //input params to the query<br>   fetchWorkSpaces(   //actual query with variables                         <br>  user_email: $user_email<br> ) <br> {<br>   id  // fields to be returned<br>   name<br>   user_email<br>   created_date<br>   updated_date<br> }<br> }<br>`;<br>export const CREATE_WORKSPACE = gql`<br>query createWorkspace($workspace: WorkspaceDto!){<br>  createWorkspace(<br>    workspace: $workspace<br>) {<br>  id<br>  }<br>}<br>`;</pre><p>In your workspace.js , you will fetch the data from this gql</p><pre>import { useQuery } from &#39;@apollo/client&#39;;<br>import { FETCH_WORKSPACES } from &#39;../../GraphQL/Queries&#39;;<br>const WorkSpace = (props) =&gt; {<br>  const { loading, error, data } = useQuery(FETCH_WORKSPACES,{<br>    variables:{<br>      user_email:props.userEmail<br>    }<br>  });<br>  return (<br> &lt;div&gt; <br>  {<br>   loading ? &lt;div&gt;Loading&lt;/div&gt;<br>   :<br>  &lt;WorkSpaceTree myWorkspaces={data} /&gt;<br>  }<br> &lt;/div&gt;<br>  )<br>}</pre><p>or if you want to call this query in a function</p><pre>export const fetchWorkspaces= async(user_email)=&gt;{<br>    const apolloGraphQlClient=(await import(&#39;../../GraphQL/DataAccessGraphQLClient.js&#39;)).default //this is lazy loading, you can import at the top of the file also<br>    const {FETCH_WORKSPACES} = await import(&quot;../../GraphQL/Queries&quot;) //lazy loading<br>    let workspacevariables={<br>        user_email:user_email,<br>    }<br>    const { workspaceResponse } = await apolloGraphQlClient.query({ query: CREATE_FOLDER, variables:{workspacevariables });<br>}<br>export const createWorkspace = () =&gt; async () =&gt; {<br>    try {<br>        let workspace = {<br>         id:uuidv4(),<br>         &quot;name&quot;: &quot;New workspace&quot;,<br>         &quot;user_email&quot;: &quot;jayant@gmail.com&quot;,<br>         &quot;isParent&quot;:false,<br>         created_date:new Date(),<br>         updated_date:new Date(),<br>        }<br>        const apolloGraphQlClient=(await import(&#39;../../GraphQL/DataAccessGraphQLClient.js&#39;)).default<br>        const {CREATE_WORKSPACE} = await import(&quot;../../GraphQL/Queries&quot;)<br>        const variables = { workspace };<br>        const { data } = await apolloGraphQlClient.query({ query: CREATE_WORKSPACE, variables }); <br>    } <br>    catch (error) {<br>        console.log(&quot;error in creating workspace&quot;, error)<br>    }<br>}</pre><p>That’s it we are done with React part of the code.Let’s move to the nestjs</p><p>We have a postgres db, but we will fetch and update data via TypeORM .Install <strong>@nestjs/typeorm</strong> , <strong>@nestjs/apollo</strong>, <strong>@nestjs/graphql</strong> .</p><p>So let’s start by creating request response graphql DTO’s and TypeORM entities.</p><p>workspace.dto.ts- This will be used while creating a workspace</p><pre>import { ObjectType, Field, InputType } from &#39;@nestjs/graphql&#39;;<br>import { IsBoolean, IsString, IsNotEmpty, IsObject } from &#39;class-validator&#39;;<br>import { GraphQLJSONObject } from &#39;graphql-type-json&#39;<br>@InputType()<br>export class WorkspaceDto {<br>  @Field(() =&gt; Date)<br>  @IsBoolean()<br>  created_date: Date;<br>  @Field(() =&gt; Date)<br>  @IsBoolean()<br>  updated_date: Date;<br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  id: string;<br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  user_email: string;<br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  name: string;<br>  @Field(() =&gt; Boolean, { defaultValue:false })<br>  @IsBoolean()<br>  isParent: boolean;<br>}</pre><p>workspace.response.dto.ts- Response type for</p><pre>mport { ObjectType, Field, InputType } from &#39;@nestjs/graphql&#39;;<br>import { IsBoolean, IsString, IsNotEmpty, IsObject } from &#39;class-validator&#39;;<br>import { GraphQLJSONObject } from &#39;graphql-type-json&#39;<br> <br> <br>@ObjectType()<br>export class WorkspaceResponseDto {<br>  @Field(() =&gt; Date)<br>  @IsBoolean()<br>  created_date: Date;<br> <br>  @Field(() =&gt; Date)<br>  @IsBoolean()<br>  updated_date: Date;<br> <br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  id: string;<br> <br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  user_email: string;<br> <br>  @Field(() =&gt; String)<br>  @IsNotEmpty()<br>  @IsString()<br>  name: string;<br> <br>  @Field(() =&gt; Boolean)<br>  @IsBoolean()<br>  isParent: boolean;<br> <br>}</pre><p>workspace.entity.ts for TypeORM and postgres DB</p><pre>import { Entity, PrimaryGeneratedColumn, Column,PrimaryColumn } from &#39;typeorm&#39;;<br>@Entity()<br>export class workspaces {<br>  @PrimaryColumn()<br>  id: string;<br>  @Column({ type: &#39;timestamp&#39; })<br>  created_date: Date;<br>  @Column({ type: &#39;timestamp&#39; })<br>  updated_date: Date;<br>  @Column({ nullable: true ,default:false})<br>  isParent: boolean;<br>  @Column({ nullable: true })<br>  user_email: string;<br>  @Column({ nullable: true })<br>  name: string;<br>}</pre><p>We will have to create a module for workspace in nestjs ,a graphql resolver for resolving queries and mutations. Lastly a service file named workspace.service.ts for the business logic.</p><p>workspace.service.ts</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { workspaces } from &#39;./workspace.entity&#39;;<br>@Injectable()<br>export class WorkspaceService {<br>  private readonly users: any[] = [];<br> <br>  constructor(<br>    @InjectRepository(workspaces)<br>    private readonly workspaceRepository: Repository&lt;workspaces&gt;,<br>  ) {}<br> <br>  async fetchWorkspaces(user_email:string):Promise&lt;workspaces[]&gt; {<br>    try{<br>      //fetching my workspaces<br>      const savedWorkspaces = await this.workspaceRepository.find({ where:{user_email}  });<br>      return savedWorkspaces; <br>    }<br>    catch(err){<br>      console.error(&quot;error in connecting&quot;,err)<br>    } <br>  }<br>  async createWorkspace(workspace:workspaces):Promise&lt;any&gt; {<br>    try{<br>      const savedWorkspace = await this.workspaceRepository.save(workspace);<br>      return savedWorkspace; <br>    }<br>    catch(err){<br>      console.error(&quot;error in connecting&quot;,err)<br>    } <br>  }<br>  async deleteWorkspace(workspace_id:string):Promise&lt;any&gt; {<br>    try{<br>      const savedWorkspace = await this.workspaceRepository.delete(workspace_id);<br>      return savedWorkspace; <br>    }<br>    catch(err){<br>      console.error(&quot;error in connecting&quot;,err)<br>    } <br>  }<br>}</pre><p>workspace.resolver.ts</p><pre>import { Args, Mutation, Query, Resolver } from &#39;@nestjs/graphql&#39;;<br>import { WorkspaceService } from &#39;./workspace.service&#39;;<br>import { WorkspaceDto } from &#39;./workspace.dto&#39;;<br>import { WorkspaceResponseDto } from &#39;./dto/workspaceresponse.dto&#39;; <br> <br>@Resolver()<br>export class WorkspaceResolver {<br>  constructor(private readonly workspaceService: WorkspaceService) {} <br> <br>  @Query(() =&gt; WorkspaceResponseDto)<br>  async createWorkspace(@Args(&#39;workspace&#39;) workspace: WorkspaceDto): Promise&lt;WorkspaceResponseDto&gt; {<br>    var records = this.workspaceService.createWorkspace(workspace);<br>    return records;<br>  } <br> <br>  @Query(() =&gt; [WorkspaceResponseDto])<br>  async fetchWorkSpaces(@Args(&#39;user_email&#39;) user_email: string): Promise&lt;WorkspaceResponseDto[]&gt; {<br>    var records = this.workspaceService.fetchWorkspaces(user_email);<br>    return records;<br>  } <br>}</pre><p>workspace.module.ts</p><pre>import { WorkspaceService } from &#39;./workspace.service&#39;;<br>import { WorkspaceResolver } from &#39;./workspace.resolver&#39;;<br>import { GraphQLModule } from &#39;@nestjs/graphql&#39;;<br>import { ApolloDriver, ApolloDriverConfig } from &#39;@nestjs/apollo&#39;;<br>import { WorkspaceDto } from &#39;./workspace.dto&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { workspaces } from &#39;./workspace.entity&#39;;<br>@Module({<br>    imports: [<br>      GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({<br>        driver: ApolloDriver,<br>        autoSchemaFile: &#39;schema.gql&#39;, // The output file for the generated schema<br>      }),<br>      TypeOrmModule.forFeature([workspaces]),<br>    ],<br>    providers:[WorkspaceService, WorkspaceResolver],<br>    controllers:[]<br>  })<br>  export class WorkspaceModule {}</pre><p>And at last, register your DB in TypeORM and import this workspace module in the NestJS main module called app.</p><pre>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { WorkspaceModule } from &#39;./modules/workspace/workspace.module&#39;;<br>import { workspaces } from &#39;./modules/workspace/workspace.entity&#39;;<br> <br>@Module({<br>  imports: [TypeOrmModule.forRoot({<br>    type: &#39;postgres&#39;,<br>    host: process.env.POSTGRES_HOST,<br>    port: parseInt(process.env.POSTGRES_PORT) ||26257,<br>    username: process.env.POSTGRES_USER ,<br>    password:process.env.POSTGRES_PASSWORD,<br>    database: process.env.POSTGRES_DATABASE,<br>    ssl: {<br>      rejectUnauthorized: false, // Ignore SSL certificate verification (NOT recommended for production)<br>    },<br>    entities: [workspaces], // Add your entities here<br>  }),WorkspaceModule],<br>  controllers: [],<br>  providers: [],<br>  exports:[]<br>})<br>export class AppModule implements NestModule {<br>  configure(consumer: MiddlewareConsumer) {<br>    consumer<br>      .apply(CacheControlMiddleware,FrontendMiddleware)<br>      .forRoutes({ path: &#39;/**&#39;, method: RequestMethod.ALL });<br>  }<br>}</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16548c050440" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/using-reactjs-graphql-api-nestjs-typeorm-16548c050440">Using ReactJs, GraphQL API, Nestjs &amp; TypeORM</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React File Upload to S3 via NestJS Serverside]]></title>
            <link>https://blog.stackademic.com/react-file-upload-to-s3-via-nestjs-serverside-e9c7a2fdd019?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c7a2fdd019</guid>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 11:16:28 GMT</pubDate>
            <atom:updated>2024-03-18T01:11:15.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DO3TKTrTz39JgLYqXNWLVw.jpeg" /></figure><p>We will be using Reactjs on Frontend and nestjs on serverside to upload &amp; delete files from s3</p><p>Let’s create a simple input in react for user to upload some files.</p><pre>import &#39;./App.css&#39;;<br>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>function App() {<br>  const [files, setFiles] = useState([]);<br><br>  function handleMultipleChange(event) {<br>    setFiles([...event.target.files]);<br>  }<br><br>  function handleMultipleSubmit(event) {<br>    event.preventDefault();<br>    // API calls will go here<br>  }<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;form onSubmit={handleMultipleSubmit}&gt;<br>        &lt;h1&gt;React Multiple File Upload&lt;/h1&gt;<br>        &lt;input type=&quot;file&quot; multiple onChange={handleMultipleChange} /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Upload&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Now our state files has the uploaded files. We will send these files to nestjs server via REST APIs.</p><pre>import &#39;./App.css&#39;;<br>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>function App() {<br>  const [files, setFiles] = useState([]);<br>  const [uploadedFiles, setUploadedFiles] = useState([]);<br><br>  function handleMultipleChange(event) {<br>    setFiles([...event.target.files]);<br>  }<br><br>  function handleMultipleSubmit(event) {<br>    event.preventDefault();<br>    const url = &#39;file/uploadToS3&#39;;<br>    const formData = new FormData();<br>    files.forEach((file) =&gt; {<br>      formData.append(&#39;files&#39;, file,file.name);<br>    });<br><br>    const config = {<br>      headers: {<br>        &#39;content-type&#39;: &#39;multipart/form-data&#39;,<br>      },<br>    }; //if you face problem in sending files remove this config<br><br>    axios.post(&#39;file/uploadToS3&#39;, formData, config)<br>      .then((response) =&gt; {<br>        console.log(response.data);<br>        setUploadedFiles(response.data.files);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error uploading files: &quot;, error);<br>      });<br>  }<br>  <br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;form onSubmit={handleMultipleSubmit}&gt;<br>        &lt;h1&gt;React Multiple File Upload&lt;/h1&gt;<br>        &lt;input type=&quot;file&quot; multiple onChange={handleMultipleChange} /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Upload&lt;/button&gt;<br>      &lt;/form&gt;<br>      {uploadedFiles.map((file, index) =&gt; (<br>        &lt;img key={index} src={file} alt={`Uploaded content ${index}`} /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Adding delete attachment functionality.</p><pre>import &#39;./App.css&#39;;<br>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>function App() {<br>  const [files, setFiles] = useState([]);<br>  const [uploadedFiles, setUploadedFiles] = useState([]);<br><br>  function handleMultipleChange(event) {<br>    setFiles([...event.target.files]);<br>  }<br><br>  function handleMultipleSubmit(event) {<br>    event.preventDefault();<br>    const url = &#39;file/uploadToS3&#39;;<br>    const formData = new FormData();<br>    files.forEach((file) =&gt; {<br>      formData.append(&#39;files&#39;, file,file.name);<br>    });<br><br>    const config = {<br>      headers: {<br>        &#39;content-type&#39;: &#39;multipart/form-data&#39;,<br>      },<br>    }; //if you face problem in sending files remove this config<br><br>    axios.post(&#39;file/uploadToS3&#39;, formData, config)<br>      .then((response) =&gt; {<br>        console.log(response.data);<br>        setUploadedFiles(response.data.files);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error uploading files: &quot;, error);<br>      });<br>  }<br> function removeAttachment = async(file) =&gt;{<br>  try {<br>   const response = await axios.post(`file/removeAttachmentFromSheet`,{file:file.url}); // just send the url/key of file stored in s3<br>  } catch (error) {<br>   console.log(&quot;error in deleting sheet&quot;, error);<br>  }<br> }<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;form onSubmit={handleMultipleSubmit}&gt;<br>        &lt;h1&gt;React Multiple File Upload&lt;/h1&gt;<br>        &lt;input type=&quot;file&quot; multiple onChange={handleMultipleChange} /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Upload&lt;/button&gt;<br>      &lt;/form&gt;<br>      {uploadedFiles.map((file, index) =&gt; (<br>        &lt;div&gt; {index}- &lt;img key={index} src={file} alt={`Uploaded content ${index}`} /&gt;&lt;button onClick={()=&gt;removeAttachment(file)} type=&quot;submit&quot;&gt;Remove&lt;/button&gt;&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Let’s move to nestjs part . I assume you have basic understanding of nestjs and what are module, controllers and service files.You will need to install <strong>aws-sdk </strong>package for communicating with AWS S3 and <strong>@nestjs/platform-express</strong> for intercepting files coming from React client. Also from your AWS account you need to get accessKeyId as well as secretAccessKey to upload files to S3.</p><p>We will make a controller file.controller.ts and a service file fileUpload.service.ts</p><pre>//file.controller.ts<br>import { Body, Controller,  Get,  Req, Res ,UseInterceptors,UploadedFiles} from &#39;@nestjs/common&#39;;<br>import {  FilesInterceptor } from &#39;@nestjs/platform-express&#39;;<br>import { FileUploadService } from &#39;../fileUpload/fileUpload.service&#39;;<br> <br>@Controller(&#39;file&#39;)<br>export class FileController {<br><br>  constructor(private readonly fileUploadService:FileUploadService) {}<br> <br>  @Post(&#39;uploadToS3&#39;)<br>  @UseInterceptors(FilesInterceptor(&#39;files&#39;, 10))<br>  async uploadToS3(@Req() req: Request, @Res() res: Response,@UploadedFiles() files: Express.Multer.File[]): Promise&lt;[any]&gt; {<br><br>    let uploadedFiles,attachments=[]<br>    if(files &amp;&amp; files.length){<br>      uploadedFiles=await this.fileUploadService.uploadToS3(files);<br>     files.forEach((file:any,index) =&gt;{<br>        if(!uploadedFiles[index])<br>        return &quot;Error in uploading file.&quot;<br>        attachments.push({fileName:file.originalname,mimetype:file.mimetype,size:file.size,url:uploadedFiles[index],createdOn:new Date()})<br>      })<br>    }<br>   return attachments<br>  }<br><br>  @Post(&#39;deleteFromS3&#39;)<br>  @HttpCode(201)<br>  async deleteFileFromS3(@Body() data:{file: string}): Promise&lt;string&gt; {<br>    return this.fileUploadService.deleteFromS3(data.file)<br>  }<br><br>}</pre><p>UseInterceptors &amp; FilesInterceptor for intercepting files.I have also used uuid package for generating random unique ids for the attachments. You can use any unique id.</p><pre>//fileUpload.service.ts<br><br>import { Injectable,UploadedFiles } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { S3 } from &#39;aws-sdk&#39;;<br>import {v4 as uuid} from &#39;uuid&#39;; <br> <br>@Injectable()<br>export class FileUploadService {<br>  constructor(<br>    private configService: ConfigService<br>  ) {}<br> <br>  async uploadToS3(@UploadedFiles() files) {<br>    const s3 = new S3({<br>      accessKeyId:this.configService.get&lt;string&gt;(&#39;accessKeyId&#39;)  , //configService just fetches fields from env<br>      secretAccessKey: this.configService.get&lt;string&gt;(&#39;secretAccessKey&#39;) <br>    });<br>    // This creates an s3 instance which can be used to call inbuilt functions of s3<br>    const uploadedFiles = []; <br>    for (const file of files) {<br>      let id=uuid()<br>      const params = {<br>        Bucket: &#39;xtables&#39;,<br>        Key: id, // Adjust path as needed<br>        Body: file.buffer,<br>      };<br> <br>     try {<br>        const data = await s3.upload(params).promise();<br>        uploadedFiles.push(data.Location);<br>     } <br>     catch (error) {<br>        console.error(&#39;Error uploading file to S3:&#39;, error);<br>     }<br>    } <br>    return uploadedFiles;<br>  }<br> <br>  async deleteFromS3(keyToDelete: string): Promise&lt;void&gt; {<br>    const s3 = new S3({<br>      accessKeyId:this.configService.get&lt;string&gt;(&#39;accessKeyId&#39;)  ,<br>      secretAccessKey: this.configService.get&lt;string&gt;(&#39;secretAccessKey&#39;) <br>    });<br><br>    const params = {<br>      Bucket: &#39;xtables&#39;, // Replace with your S3 bucket name<br>      Key: keyToDelete,  // The key of the file you want to delete<br>    };<br><br>    try {<br>      await s3.deleteObject(params).promise();<br>    } <br>    catch (error) {<br>      console.error(&#39;Error deleting file from S3:&#39;, error);<br>      throw new Error(&#39;Failed to delete file from S3&#39;);<br>    }<br><br>  }<br><br>}</pre><p>That’s it we are done with uploading files to S3. Feel free to comment your doubts &amp; suggestions.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c7a2fdd019" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/react-file-upload-to-s3-via-nestjs-serverside-e9c7a2fdd019">React File Upload to S3 via NestJS Serverside</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with AWS Lambda and Serverless Framework in Node.js]]></title>
            <link>https://awstip.com/getting-started-with-aws-lambda-and-serverless-framework-in-node-js-15534d19558d?source=rss-a1954cfcf938------2</link>
            <guid isPermaLink="false">https://medium.com/p/15534d19558d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Jayant Gangwani]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 11:06:06 GMT</pubDate>
            <atom:updated>2024-03-19T09:26:51.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*jKCN3J84ZS1baMQKXMXh-A.jpeg" /></figure><p>AWS Lambda, coupled with the Serverless Framework, provides a powerful platform for building serverless applications.In this tutorial, I’ll walk through the process of creating a simple AWS Lambda function using Node.js(express app) and deploying it with the Serverless Framework.</p><h3>Prerequisites</h3><p>Before getting started, make sure you have the following:</p><ul><li>Node.js installed</li><li>An AWS account with appropriate permissions</li><li>Serverless Framework installed (npm install -g serverless)</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> installed .</li><li>a cup of coffee on your desk ☕️ because you would need some patience and debugging if stuck.</li></ul><p>Let’s gear up!</p><h3>Step 1: Setting up the Project</h3><p>Create a new directory for your project and navigate to it. Run the following command to set up a new Serverless project:</p><pre>serverless create --template aws-nodejs --path my-lambda-function<br>cd my-lambda-function</pre><p>This command generates a basic Node.js template for your AWS Lambda function.</p><h3>Step 2: Configuring the AWS</h3><p>Now once you have AWS CLI , you can need to connect to your AWS account via this directory so that serverless can deploy to this account.Write this command in your terminal</p><pre>aws configure</pre><p>This will prompt your for AWS Access Key ID, Secret Access Key, default region, and default output format.</p><p>Great your basic setup is done , template is created , AWS account is configured. So let’s write a simple function to print “Hello” using lambda function.</p><h3>Step 3: Writing the Lambda Function</h3><p>Create a file named handler.js with the following content:</p><pre>// handler.js<br>&#39;use strict&#39;;<br><br>module.exports.hello = async (event) =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &#39;Hello&#39;,<br>      input: event,<br>    }),<br>  };<br>};</pre><h3>Step 4: Configuring Serverless</h3><p>serverless.yml file contains information about your service, provider (cloud platform like <strong>AWS</strong>, Azure, or Google Cloud), functions, events, and other settings..Open the serverless.yml file and update it with the following configuration:</p><pre># serverless.yml<br>service: my-lambda-function<br><br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br><br>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - http:<br>          path: /<br>          method: get</pre><p>Notice we have wired the serverless.yml file to execute the function hello in handler file triggered by an HTTP GET request.</p><p>Our function looks ready to deploy now. Let’s deploy it using serverless</p><h3>Step 5: Deploying the Lambda Function</h3><p>Run the following command to deploy your Lambda function:</p><pre>serverless deploy</pre><p>This command packages and deploys your function to AWS Lambda. After deployment, you’ll receive a URL endpoint for your function.</p><p>Login to your aws console -&gt; click on the region -&gt; go to Lambda function and you will see your lambda function named “my-lambda-function” . Click on test write some configs if you want to and then run the lambda.</p><p>Voila! You got the response “Hello” and you are done with writing your first lambda function.</p><p>Now let’s say you want to write some config env which you can use in your lambda function.</p><h3>Step 5: Using env variables using event</h3><p>When you test your lambda function in AWS console , you see an option test where you can write your env in JSON format.</p><p>Let’s say I want to store my name . So I will write</p><pre>{<br>&quot;name&quot;:&quot;Jayant&quot;<br>}</pre><p>How do you use this name ?</p><p>In the hello function inside your handler.js file there is a parameter event</p><pre>module.exports.hello = async (event) =&gt; {<br>console.log(&quot;env config&quot;,event.name) <br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &#39;Hello&#39;,<br>      input: event,<br>    }),<br>  };<br>};</pre><p>Notice we have the name inside event and that will be printed in the console when you run your lambda function.</p><blockquote>In your AWS lambda dashboard , edit your configuration like memory and time limit as per your functional requirement.</blockquote><p>Currently, we are executing lambda manually on AWS console. What if we want to execute it like a cron job. You can create a CloudWatch event in AWS and</p><p>Go to configuration-&gt;Trigger-&gt;Add trigger .</p><p>Select cloudwatch event and then give the role (role is a completely different topic but you can use IAM console for defining roles and permissions)</p><p>Now this was a basic project in the next blog I will use MYSQL DB and S3 bucket to write a lambda that will fetch some data from SQL and upload the data to a csv/zip file in your S3 bucket.</p><p>Thanks for reading, feel free to reach out to me or add some comments to appreciate .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15534d19558d" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/getting-started-with-aws-lambda-and-serverless-framework-in-node-js-15534d19558d">Getting Started with AWS Lambda and Serverless Framework in Node.js</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>