<?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 Anjali Rajwar on Medium]]></title>
        <description><![CDATA[Stories by Anjali Rajwar on Medium]]></description>
        <link>https://medium.com/@anjalirajwar101?source=rss-77d561f8ccf5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vvmJ0Tm5uIqHvfExCnuYgA.jpeg</url>
            <title>Stories by Anjali Rajwar on Medium</title>
            <link>https://medium.com/@anjalirajwar101?source=rss-77d561f8ccf5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anjalirajwar101/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[Why Backtracking Exists: Memory, References, and Recursion in C++ and JavaScript]]></title>
            <link>https://medium.com/@anjalirajwar101/why-backtracking-exists-memory-references-and-recursion-in-c-and-javascript-f444255b82be?source=rss-77d561f8ccf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f444255b82be</guid>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anjali Rajwar]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 13:18:55 GMT</pubDate>
            <atom:updated>2026-10-22T13:18:55.388Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started learning backtracking, one question confused me: <strong>Why do we need to undo a choice after a recursive call?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ATq94bOBQQx9xujWpb6dCg.webp" /></figure><p>The answer becomes easier when we understand how variables and references work.</p><h3>1. Pass by Value vs. Reference</h3><p>In C++, we can pass a variable by reference using &amp;. Changes inside the function affect the original variable.</p><p>In JavaScript, arguments are passed by value. For objects and arrays, the copied value is a reference to the same object. So, modifying an array inside a function can affect the original array.</p><h3>2. Why Does Backtracking Need Undo?</h3><p>Consider generating permutations of &quot;abc&quot;.</p><p>In JavaScript, strings are immutable, so we cannot swap their characters directly. We usually convert the string into an array and swap its elements.</p><pre>let arr = &quot;abc&quot;.split(&quot;&quot;);</pre><pre>function solve(i) {<br>    if (i === arr.length) {<br>        console.log(arr.join(&quot;&quot;));<br>        return;<br>    }</pre><pre>    for (let j = i; j &lt; arr.length; j++) {<br>        [arr[i], arr[j]] = [arr[j], arr[i]];</pre><pre>        solve(i + 1);</pre><pre>        [arr[i], arr[j]] = [arr[j], arr[i]];<br>    }<br>}</pre><p>The final swap restores the array to its previous state. Without it, one recursive branch could leave changes behind and affect the next branch.</p><h3>3. Is Undo Always Necessary?</h3><p>No. If we create a new array for each recursive branch, we generally don’t need to undo the changes manually.</p><pre>solve(i + 1, [...path, arr[j]]);</pre><p>Here, each branch receives a new array instead of modifying the shared path array.</p><h3>The Key Takeaway</h3><p>Backtracking is not caused by memory allocation itself. It is a technique for exploring different choices while maintaining the correct state.</p><p><strong>Choose → Explore → Undo</strong></p><p>Once I understood the difference between modifying a shared array and creating a new one, backtracking started making much more sense.</p><p>#DSA #JavaScript #Cpp #Backtracking #ProblemSolving</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f444255b82be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From React to Android: My Experience with Capacitor]]></title>
            <link>https://medium.com/@anjalirajwar101/from-react-to-android-my-experience-with-capacitor-bf8e3f0dee72?source=rss-77d561f8ccf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8e3f0dee72</guid>
            <category><![CDATA[capacitor]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Anjali Rajwar]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 10:35:50 GMT</pubDate>
            <atom:updated>2026-10-21T10:35:50.253Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted to run my existing React application as an Android app without rewriting everything from scratch, so I decided to explore Capacitor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWrcHEpxmB0fppL7bnafxg.png" /></figure><p>The setup was straightforward initially, but getting everything to work on Android required some extra effort, especially with live reload, API connectivity, and native configuration.</p><p>Here are the steps I followed and the issues I learned to troubleshoot.</p><h3>1. Setting Up Capacitor</h3><p>I started by installing Capacitor in my existing React project.</p><pre>npm install @capacitor/core<br>npm install -D @capacitor/cli<br>npx cap init</pre><p>I configured the application name, application ID, and web directory. Since my project uses Vite, the build directory is dist.</p><h3>2. Adding Android Support</h3><p>Next, I installed the Android platform and created the native project.</p><pre>npm install @capacitor/android<br>npx cap add android<br>npm run build<br>npx cap sync android</pre><p>This generated the Android project and synchronized my React application with it.</p><h3>3. Running the App on Android</h3><p>Initially, I used the usual Capacitor workflow:</p><pre>npx cap open android</pre><p>From Android Studio, I could launch the application on an emulator or a connected phone.</p><p>However, I faced some issues with the emulator and wanted a quicker way to test the app on my actual device.</p><p>I explored connecting my phone directly instead of relying on the emulator. Here is the guide I wrote about that setup: <a href="https://medium.com/@anjalirajwar101/android-studio-was-giving-me-trouble-so-i-started-testing-my-app-on-a-real-phone-26a720dfe1b6?sharedUserId=anjalirajwar101">How to Run Your Mobile App on a Real Android Phone</a>.</p><h3>4. Setting Up Live Reload</h3><p>Rebuilding the app after every small UI change was slowing down development, so I worked on configuring live reload.</p><p>The basic process is:</p><ol><li>Start the Vite development server with network access.</li><li>Configure Capacitor to load the development server URL.</li><li>Make sure the Android device can reach the server.</li><li>Launch the app using the development configuration.</li></ol><p>One issue I encountered was the difference between localhost on my computer and localhost inside the Android environment. The device needs a reachable address for the development server and backend.</p><p>Once this is configured correctly, frontend changes can be tested much faster without rebuilding the app for every UI update.</p><h3>5. Integrating Native Features</h3><p>I also explored Capacitor plugins for native functionality.</p><p>Some of the features I worked with included:</p><ul><li><strong>Splash Screen</strong> — controlling the app’s startup experience.</li><li><strong>Status Bar</strong> — adjusting its appearance.</li><li><strong>Mobile layouts</strong> — handling safe areas and screen dimensions.</li></ul><p>These features require testing on the actual device because the behavior can differ from the browser.</p><h3>6. Troubleshooting Android Issues</h3><p>A few issues required additional investigation.</p><p><strong>API requests failing:</strong> I checked the API base URL, network accessibility, and Android-specific networking restrictions.</p><p><strong>White screen on startup:</strong> I investigated JavaScript errors, asset loading, and the development server configuration.</p><p><strong>Live reload not working:</strong> I checked the server port, device connectivity, and the URL configured in Capacitor.</p><p>These issues taught me to inspect logs and verify the environment before changing multiple configurations at once.</p><h3>7. Preparing the Production Build</h3><p>Once the development setup was working, the next step was preparing the production application.</p><pre>npm run build<br>npx cap sync android</pre><p>Before generating a release, I made sure the app used its production assets instead of the development server URL.</p><p>The Android project can then be used to generate a signed APK for direct installation or an Android App Bundle for distribution through Google Play.</p><h3>What I Learned</h3><p>Working with Capacitor helped me understand how a React application interacts with the Android environment.</p><p>The main things I learned were:</p><ul><li>Native configuration matters as much as frontend code.</li><li>Live reload makes UI development faster when configured correctly.</li><li>API URLs need to account for the device’s network environment.</li><li>Testing on a physical phone helps identify issues that may not appear in the browser.</li></ul><p>The most useful part of this experience was learning how to troubleshoot the complete setup instead of looking at everything as a React problem.</p><p><strong>Resources:</strong> <a href="https://capacitorjs.com/docs">Capacitor Documentation</a> · <a href="https://developer.android.com/studio">Android Developer Guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8e3f0dee72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Studio Was Giving Me Trouble, So I Started Testing My App on a Real Phone]]></title>
            <link>https://medium.com/@anjalirajwar101/android-studio-was-giving-me-trouble-so-i-started-testing-my-app-on-a-real-phone-26a720dfe1b6?source=rss-77d561f8ccf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a720dfe1b6</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Anjali Rajwar]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 10:12:31 GMT</pubDate>
            <atom:updated>2026-10-21T10:12:31.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ckMRzfm0ypBgIJP8KUUZA.png" /></figure><p>While working on mobile app development, I faced quite a few issues with Android Studio. Sometimes the emulator was slow, sometimes the build process took time, and sometimes I just wanted to check a small UI change without going through the whole process again.</p><p>I started looking for a simpler way to run my app directly on my Android phone.</p><p>Here is the setup that helped me understand how to connect a real device to a mobile development workflow.</p><h3>Step 1: Enable USB Debugging</h3><p>First, I enabled Developer Options on my Android phone.</p><ul><li>Open Settings → About Phone.</li><li>Tap Build Number seven times.</li><li>Open Developer Options.</li><li>Enable USB Debugging.</li></ul><p>The exact steps may vary depending on your phone.</p><h3>Step 2: Connect Your Phone to Your Laptop</h3><p>Connect your phone using a USB cable and accept the debugging authorization prompt.</p><p>Then open your terminal and run:</p><pre>adb devices</pre><p>If everything is configured correctly, your phone should appear in the device list with the status device.</p><p>If it shows unauthorized, check your phone for the authorization prompt.</p><p>This is the first thing I check whenever my laptop doesn’t detect my phone.</p><h3>Step 3: Run the App on Your Phone</h3><p>The command depends on the technology you are using.</p><p><strong>React Native:</strong></p><pre>npm run android</pre><p><strong>Expo:</strong></p><pre>npx expo start</pre><p>For compatible projects, scan the QR code with Expo Go.</p><p><strong>Flutter:</strong></p><pre>flutter devices<br>flutter run</pre><p><strong>Capacitor:</strong></p><pre>npm run build<br>npx cap sync android<br>npx cap run android</pre><p>These commands assume the relevant framework, dependencies, and Android build tools are already configured.</p><p>Once the build and installation complete, the application should open on your phone.</p><h3>Step 4: Make Testing Easier</h3><p>One thing I wanted to avoid was rebuilding the application every time I changed something in the UI.</p><p>Most modern mobile development workflows provide a faster option:</p><ul><li>React Native and Expo support Fast Refresh.</li><li>Flutter supports hot reload.</li><li>Capacitor supports live reload when configured to use a reachable development server.</li></ul><p>For Capacitor, make sure your phone can access the development server through your laptop’s network IP address. Using localhost on the phone will not point to your laptop.</p><h3>Step 5: If Your Phone Is Not Detected</h3><p>Here are the first things to check:</p><ul><li>Is USB debugging enabled?</li><li>Did you accept the authorization prompt?</li><li>Does adb devices show your phone?</li><li>Is your USB cable capable of transferring data?</li><li>Do you need a USB driver on Windows?</li></ul><p>If the phone connects but the application fails to launch, check the build output and Android logs to identify the actual error.</p><h3>Final Thoughts</h3><p>For me, the main goal was to make mobile testing simpler and spend less time dealing with the emulator.</p><p>Connecting a physical phone is a useful alternative, especially when you want to test the application on an actual device.</p><p>Android Studio is still useful for native configuration and debugging, but you don’t always need to run its emulator.</p><p>Sometimes, connecting the phone and running a single command is all you need to get started.</p><p><strong>Happy coding!</strong></p><p><strong>Useful resources:</strong></p><ul><li><a href="https://reactnative.dev/docs/running-on-device">React Native — Running on a Device</a></li><li><a href="https://docs.expo.dev/">Expo Documentation</a></li><li><a href="https://docs.flutter.dev/">Flutter Documentation</a></li><li><a href="https://capacitorjs.com/docs">Capacitor Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a720dfe1b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate a dynamic PDF from React component]]></title>
            <link>https://medium.com/@anjalirajwar101/how-to-generate-a-dynamic-pdf-from-react-component-329fbb4c54f5?source=rss-77d561f8ccf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/329fbb4c54f5</guid>
            <category><![CDATA[pdf-generation-in-react]]></category>
            <category><![CDATA[dynamic-pdfs-with-react]]></category>
            <category><![CDATA[easy-pdf-creation-react]]></category>
            <category><![CDATA[pdfs-with-jspdf-react]]></category>
            <category><![CDATA[jspdf-and-html2canvas]]></category>
            <dc:creator><![CDATA[Anjali Rajwar]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 05:43:22 GMT</pubDate>
            <atom:updated>2025-01-08T15:06:54.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iE7QtvPdu0HzZXWSPzkeTQ.png" /></figure><p>Hey there! 👋</p><p>Have you ever needed to turn something from your React app into a PDF? You know, like those nice reports or documents you can download and share? I just figured out how to do it, and it’s actually pretty cool (and not too hard once you get the hang of it!). Let me walk you through it step by step.</p><h4><strong>Why Would You Want to Do This?</strong></h4><p>Well, sometimes users want to save or print a report or document directly from your app. Instead of asking them to copy-paste stuff into Word or something, you can generate a neat PDF for them. Cool, right?</p><p>We are going to generate a 4-page PDF with a constant header and footer for all four pages. Each page will have dynamic data (e.g., userName, generatedDate, etc.) and a consistent design.</p><p><strong>The Tools You Need</strong></p><p>We’re going to use two main tools<strong>:</strong></p><ol><li><strong>jsPDF</strong>: This library helps create PDFs.</li><li><strong>html2canvas</strong>: This one converts your React components into images that we can put in the PDF.</li></ol><p><strong><em>Step 1: Start with the Basics</em></strong></p><p>jsPDF() takes 4 Parameter =&gt;orientation: ‘p’, unit: ‘mm’, format: ‘a4’, putOnlyUsedFonts:true , I am going to use default values</p><pre>const doc= new jsPDF(); // creating new PDF documents, jsPDF takes <br>// define weidth and hieght<br>const imgWidth= doc.internal.pageSize.getWidth();<br><br>// if you have header and footer<br>const headerWidth= 30 // 30 is on mm because unit: mm(default)<br>const footerHeight= 30 <br></pre><p><strong><em>Step 2: Turning React Components into Images</em></strong></p><p>Now, this part might sound tricky, but it’s not too bad. We need to convert our React components (like headers, pages, or footers) into images that we can put into the PDF. Here’s how you can do that:</p><pre>const renderToImage = async (component) =&gt; {<br>  // Create a hidden div<br>  const container = document.createElement(&#39;div&#39;);<br>  container.style.position = &#39;absolute&#39;;<br>  container.style.top = &#39;-9999px&#39;;<br>  document.body.appendChild(container);<br><br>  // Render the component inside this div<br>  const root = createRoot(container);<br>  root.render(component);<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 100));<br><br>  // Use html2canvas to take a snapshot of the component<br>  const canvas = await html2canvas(container, {<br>    scrollY: -window.scrollY,<br>    scale: 2,<br>    useCORS: true,<br>  });<br><br>  // Clean up<br>  root.unmount();<br>  document.body.removeChild(container);<br><br>  return canvas.toDataURL(&#39;image/png&#39;);<br>};</pre><p><strong><em>Step 3: Building the PDF</em></strong></p><p>Now, we take our components (turned into images) and add them to the PDF. Here’s a simple loop that does that for each page:</p><pre>for (let i = 0; i &lt; pages.length; i++) {<br>  const imgData = await renderToImage(pages[i]);<br>  const imgWidth = pageWidth;<br>  const pageHeight = (pageWidth * 297) / 210;<br><br>  if (i &gt; 0) doc.addPage();<br>  doc.addImage(headerImg, &#39;PNG&#39;, 0, 0, imgWidth, headerHeight);<br>  doc.addImage(imgData, &#39;PNG&#39;, 0, headerHeight, imgWidth, pageHeight - headerHeight - footerHeight);<br>  doc.addImage(footerImg, &#39;PNG&#39;, 0, pageHeight - footerHeight, imgWidth, footerHeight);<br>}</pre><p><strong><em>Step 4: Save and Success!</em></strong></p><p>Finally, once all the pages are added, we save the PDF and show a success message to the user:</p><pre>doc.save(&#39;Report.pdf&#39;);<br>toast.success(&#39;Downloaded !&#39;);</pre><p><strong><em>Step 5: Handling Errors</em></strong></p><p>What if something goes wrong? No worries! We catch the error and show an error message instead:</p><pre>catch {<br>  toast.error(&#39;Error generating PDF&#39;);<br>} finally {<br>  setLoading(false);<br>}</pre><p><strong>Summary : </strong>React component(s) -&gt; image -&gt; pdf</p><p>That’s It!</p><p>So, that’s how you can create a PDF from your React app. It’s not super hard, right? Just follow these steps, and you’ll have a nice, professional-looking PDF that your users can download and share.</p><p>I hope this helps you as much as it helped me. Happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329fbb4c54f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Daily Diet Tracker Using Node.js, PostgreSQL, and Sequelize]]></title>
            <link>https://medium.com/@anjalirajwar101/build-a-daily-diet-tracker-using-node-js-postgresql-and-sequelize-bdb30d15d898?source=rss-77d561f8ccf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdb30d15d898</guid>
            <dc:creator><![CDATA[Anjali Rajwar]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 05:30:20 GMT</pubDate>
            <atom:updated>2024-10-09T05:30:20.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Create, Read, Update, and Delete Your Daily Diet Plans. This guide is perfect for beginners looking to understand how to set up a basic backend API with database connectivity.</p><p>In this blog, we’ll create a <strong>CRUD (Create, Read, Update, Delete)</strong> application that helps users manage their daily diet entries. Think of it as a Diet-To-Do app where users can add their meals for the day, view them, make changes, and delete old entries. We’ll use Node.js for the backend, PostgreSQL as our database, and Sequelize for ORM (Object Relational Mapping) to interact with the database efficiently.</p><h3>Table of Contents</h3><ol><li>Setting Up the Environment</li><li>Installing Node.js, PostgreSQL, and Sequelize</li><li>Creating the Database and Setting Up Sequelize</li><li>Defining the Daily Diet Model</li><li>Building the CRUD API Endpoints</li><li>Testing the API with Postman</li><li>Conclusion</li></ol><h3>1. Setting Up the Environment</h3><p><strong>Prerequisites</strong>:<br>Ensure the following tools are installed:<br>- Node.js: For building the API.<br>- PostgreSQL: Our database to store daily diet entries.<br>- Postman: For testing our API endpoints.</p><p>Start by creating a new directory for the project and initializing it as a Node.js project:</p><pre>mkdir diet-tracker<br>cd diet-tracker<br>npm init -y</pre><h3><strong>2. Installing Node.js, PostgreSQL, and Sequelize</strong></h3><p>We will need some packages for building the app:<br>- Express.js: To handle routes and requests.<br>- Sequelize: ORM for PostgreSQL.<br>- pg &amp; pg-hstore: Required for connecting Sequelize with PostgreSQL.</p><p>Install the necessary packages:</p><pre>npm install express sequelize pg pg-hstore dotenv</pre><h3><strong>3. Creating the Database and Setting Up Sequelize</strong></h3><ul><li>First, create a PostgreSQL database for our project:</li></ul><pre>CREATE DATABASE diet_tracker_db;</pre><ul><li>Next, create a `.env` file to store database credentials:</li></ul><pre>DB_NAME=diet_tracker_db<br>DB_USER=yourusername<br>DB_PASSWORD=yourpassword<br>DB_HOST=localhost<br>DB_PORT=5432</pre><ul><li>Configure Sequelize to connect with PostgreSQL by adding <em>config/config.js </em>:</li></ul><pre>module.exports = {<br> development: {<br> username: process.env.DB_USER,<br> password: process.env.DB_PASSWORD,<br> database: process.env.DB_NAME,<br> host: process.env.DB_HOST,<br> dialect: &#39;postgres&#39;<br> }<br> };</pre><h3><strong>4. Defining the Daily Diet Model</strong></h3><p>We will define a model for our diet entries, which will store information such as the meal, type (e.g., breakfast, lunch), calories, and date.</p><p>Create the `models/dailyDiet.js` file:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br> const DailyDiet = sequelize.define(&#39;DailyDiet&#39;, {<br> meal: {<br> type: DataTypes.STRING,<br> allowNull: false<br> },<br> type: {<br> type: DataTypes.ENUM(&#39;breakfast&#39;, &#39;lunch&#39;, &#39;dinner&#39;, &#39;snack&#39;),<br> allowNull: false<br> },<br> calories: {<br> type: DataTypes.INTEGER,<br> allowNull: false<br> },<br> date: {<br> type: DataTypes.DATEONLY,<br> defaultValue: DataTypes.NOW<br> }<br> });<br> return DailyDiet;<br>};</pre><p>After defining the model, create a migration file and migrate to the database:</p><pre>npx sequelize-cli model:generate - name DailyDiet - attributes meal:string,type:enum:breakfast,lunch,dinner,snack,calories:integer,date:dateonly<br>npx sequelize-cli db:migrate</pre><h3><strong>5. Building the CRUD API Endpoints</strong></h3><p>We will now build the Create, Read, Update, and Delete API endpoints using Express.js.</p><ul><li>First, create an `index.js` file for setting up the server:</li></ul><pre>const express = require(&#39;express&#39;);<br>const diteRoute=express.router()<br>diteRoute.post(&#39;/diets&#39;, async (req, res) =&gt; {<br> try {<br> const diet = await DailyDiet.create(req.body);<br> res.status(201).json(diet);<br> } catch (error) {<br> res.status(400).json({ error: error.message });<br> }<br>});<br>// Get all daily diet entries<br>diteRoute.get(&#39;/diets&#39;, async (req, res) =&gt; {<br> try {<br> const diets = await DailyDiet.findAll();<br> res.status(200).json(diets);<br> } catch (error) {<br> res.status(500).json({ error: error.message });<br> }<br>});<br>// Get a specific diet entry by ID<br>diteRoute.get(&#39;/diets/:id&#39;, async (req, res) =&gt; {<br> try {<br> const diet = await DailyDiet.findByPk(req.params.id);<br> if (diet) {<br> res.status(200).json(diet);<br> } else {<br> res.status(404).json({ error: &#39;Diet entry not found&#39; });<br> }<br> } catch (error) {<br> res.status(500).json({ error: error.message });<br> }<br>});<br>// Update a diet entry<br>diteRoute.put(&#39;/diets/:id&#39;, async (req, res) =&gt; {<br> try {<br> const diet = await DailyDiet.findByPk(req.params.id);<br> if (diet) {<br> await diet.update(req.body);<br> res.status(200).json(diet);<br> } else {<br> res.status(404).json({ error: &#39;Diet entry not found&#39; });<br> }<br> } catch (error) {<br> res.status(400).json({ error: error.message });<br> }<br>});<br>// Delete a diet entry<br>diteRoute.delete(&#39;/diets/:id&#39;, async (req, res) =&gt; {<br> try {<br> const diet = await DailyDiet.findByPk(req.params.id);<br> if (diet) {<br> await diet.destroy();<br> res.status(204).send();<br> } else {<br> res.status(404).json({ error: &#39;Diet entry not found&#39; });<br> }<br> } catch (error) {<br> res.status(500).json({ error: error.message });<br> }<br>});<br>export default diteRoute</pre><pre>const express = require(&#39;express&#39;);<br>const { Sequelize, DataTypes } = require(&#39;sequelize&#39;);<br>const { DailyDiet } = require(&#39;./models&#39;);<br>const diteRoute = require(&#39;./diteRoute.js&#39;);<br>const app = express();<br>app.use(express.json()); // Middleware to parse JSON<br>// CRUD Endpoints<br>// Add a new daily diet entry<br>app.use(&#39;/dites&#39;,diteRoute)<br>// Start the server<br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br> console.log(`Server running on port ${PORT}`);<br>});</pre><h3><strong>6. Testing the API with Postman</strong></h3><p>Let’s test our CRUD operations:</p><ol><li>Create a Diet Entry: <em>POST /diets</em><br> — Body:</li></ol><pre>{<br> &quot;meal&quot;: &quot;Oatmeal&quot;,<br> &quot;type&quot;: &quot;breakfast&quot;,<br> &quot;calories&quot;: 300,<br> &quot;date&quot;: &quot;2024–10–09&quot;<br> }</pre><p>2. Get All Diet Entries: <em>GET /diets</em><br> — Response will return a list of all diet entries.</p><p>3. Get a Specific Diet Entry: <em>GET /diets/:id</em><br> — Provide the `id` in the URL to fetch a single diet entry.</p><p>4. Update a Diet Entry: <em>PUT /diets/:id</em><br> — Update the details like calories or meal names.</p><p>5. Delete a Diet Entry: <em>DELETE /diets/:id</em><br> — Remove a diet entry by its `id`.</p><h3><strong>7. Conclusion</strong></h3><p>In this tutorial, we created a Diet Tracker app using Node.js, PostgreSQL, and Sequelize that lets users manage their daily meals in a to-do-like structure. You now have a simple backend that can:<br>- Store user diet data in a PostgreSQL database.<br>- Handle CRUD operations for diet entries.<br> <br>This app is a great starting point and can be extended further with user authentication, a frontend interface, or even daily diet recommendations!</p><p>This guide is perfect for beginners looking to understand how to set up a basic backend API with database connectivity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdb30d15d898" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>