<?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"><channel><title><![CDATA[Ipseeta's personal blog]]></title><description><![CDATA[Software Developer 👩🏼‍💻 
Foodie 😋 
Explorer 🕵️‍♀️ 
Dog lover 🐶]]></description><link>https://blog.ipseeta.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/58e3733b3b44892f8fa99997/b43bf6f5-c095-46b4-b487-a09444c727b8.png</url><title>Ipseeta&apos;s personal blog</title><link>https://blog.ipseeta.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 09 Apr 2026 03:24:15 GMT</lastBuildDate><atom:link href="https://blog.ipseeta.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Adding AI Features to Your Next.js App Without Overengineering It]]></title><description><![CDATA[AI features are everywhere now: chatbots, image analysis, content generation. But integrating AI into a production Next.js app doesn't have to mean building a complex pipeline. In this post, I'll walk]]></description><link>https://blog.ipseeta.dev/adding-ai-features-to-your-next-js-app-without-overengineering-it</link><guid isPermaLink="true">https://blog.ipseeta.dev/adding-ai-features-to-your-next-js-app-without-overengineering-it</guid><category><![CDATA[AI]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[openai]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Tue, 31 Mar 2026 09:35:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/54d750ac3adc13883c24a9be/72556568-1a9d-4970-aaca-5dadb69edea2.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>AI features are everywhere now: chatbots, image analysis, content generation. But integrating AI into a production Next.js app doesn't have to mean building a complex pipeline. In this post, I'll walk through practical patterns I used in my <a href="https://calorie-counter.ipseeta.dev/">Calorie Counter</a> app, which uses GPT-4o for nutrition analysis and food image recognition.</p>
<p>The goal is simple: add AI that works reliably, without overengineering it.</p>
<h2>What We're Building</h2>
<p>I built the Calorie Counter as a solo project. Users can type a food item (or upload a photo) and get back structured nutrition data, a health score, and recipe video recommendations.</p>
<p>The AI handles two things:</p>
<ol>
<li><p><strong>Text input</strong> → Extract detailed nutrition information</p>
</li>
<li><p><strong>Image input</strong> → Identify the food item from a photo, then extract nutrition</p>
</li>
</ol>
<p>Everything else, health scoring, video search, data persistence, is handled by regular code. This is the first principle: <strong>use AI only where it adds value</strong>.</p>
<h2>1. Structured Outputs with Zod</h2>
<p>The biggest mistake I see developers make is treating LLM responses as free-form text and then writing fragile parsing logic. OpenAI supports structured outputs: you pass a schema, and the response is guaranteed to match it.</p>
<p>First, define your schema with Zod:</p>
<pre><code class="language-typescript">import { z } from "zod";

const FatDetailsSchema = z.object({
  saturated: z.number(),
  unsaturated: z.number(),
  trans: z.number(),
});

const CarbohydrateDetailsSchema = z.object({
  fiber: z.number(),
  sugar: z.number(),
  starch: z.number(),
});

export const NutritionScoresSchema = z.object({
  food_item: z.string(),
  calories: z.number(),
  protein: z.number(),
  fat: z.number(),
  fat_details: FatDetailsSchema,
  carbohydrates: z.number(),
  carbohydrate_details: CarbohydrateDetailsSchema,
  cholesterol: z.number(),
  sodium: z.number(),
  potassium: z.number(),
  vitamin_c: z.number(),
  calcium: z.number(),
  iron: z.number(),
});
</code></pre>
<p>Then use <code>zodResponseFormat</code> when calling the API:</p>
<pre><code class="language-typescript">import { zodResponseFormat } from "openai/helpers/zod";

const response = await client.chat.completions.parse({
  model: MODEL,
  messages: [
    { role: "system", content: systemPrompt },
    { role: "user", content: userPrompt },
  ],
  response_format: zodResponseFormat(NutritionScoresSchema, "NutritionScores"),
  temperature: 0.3,
});

return response.choices[0].message.parsed!;
</code></pre>
<p>The key things here:</p>
<ul>
<li><p><code>zodResponseFormat</code> tells OpenAI to return JSON matching your Zod schema. No manual parsing needed.</p>
</li>
<li><p><code>temperature: 0.3</code> keeps responses consistent. For factual data like nutrition info, you want low creativity.</p>
</li>
<li><p><code>.parsed!</code> gives you a fully typed object. Your TypeScript types and your AI output are the same schema.</p>
</li>
</ul>
<p>This is much cleaner than parsing free-form text with regex or hoping the model returns valid JSON.</p>
<h2>2. Handling Rate Limits with Retry Logic</h2>
<p>If you're using OpenAI (or Azure OpenAI), you will hit rate limits eventually. A simple retry wrapper with exponential backoff handles this gracefully:</p>
<pre><code class="language-typescript">async function withRetry&lt;T&gt;(fn: () =&gt; Promise&lt;T&gt;, maxRetries = 3): Promise&lt;T&gt; {
  for (let attempt = 0; attempt &lt;= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err: unknown) {
      const status = (err as { status?: number }).status;
      if (status === 429 &amp;&amp; attempt &lt; maxRetries) {
        const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
        await new Promise((r) =&gt; setTimeout(r, delay));
        continue;
      }
      throw err;
    }
  }
  throw new Error("Unreachable");
}
</code></pre>
<p>Then wrap your API calls:</p>
<pre><code class="language-typescript">const response = await withRetry(() =&gt;
  client.chat.completions.parse({
    model: MODEL,
    messages: [...],
    response_format: zodResponseFormat(NutritionScoresSchema, "NutritionScores"),
    temperature: 0.3,
  })
);
</code></pre>
<p>This only retries on 429 (rate limit) errors. Other errors fail immediately: you don't want to retry on a bad prompt or authentication failure.</p>
<h2>3. Vision API: A Two-Pass Approach</h2>
<p>For image analysis, I used a two-call pattern:</p>
<p><strong>Call 1: Identify the food</strong> — Send the image to GPT-4o's vision endpoint with strict guardrails.</p>
<pre><code class="language-typescript">const base64Image = imageBuffer.toString("base64");

const visionResponse = await withRetry(() =&gt;
  client.chat.completions.create({
    model: MODEL,
    messages: [
      {
        role: "system",
        content: `You are a precise food image analyzer. Your rules:
1. Determine if the image contains food or not
2. Never classify non-food items as food
3. If the image contains people, landscapes, or non-food objects,
   respond with is_food: false`,
      },
      {
        role: "user",
        content: [
          { type: "text", text: "Analyze this image and return a JSON response..." },
          {
            type: "image_url",
            image_url: { url: `data:\({mimeType};base64,\){base64Image}` },
          },
        ],
      },
    ],
    response_format: { type: "json_object" },
  })
);
</code></pre>
<p><strong>Call 2: Normalize the output</strong> — A second, cheaper call formats the vision result into a clean schema.</p>
<p>Why two calls instead of one? The vision model is good at identifying food, but its output format can be inconsistent. A dedicated formatting pass gives you reliable structure. This is cheaper and more predictable than asking the vision model to do both at once.</p>
<h2>4. Keep AI Out of What Doesn't Need It</h2>
<p>This is the part most developers skip. The Calorie Counter computes a health score for every food item — but this is done algorithmically, not by the LLM:</p>
<pre><code class="language-typescript">export function calculateHealthScore(nutrition: NutritionData): HealthScore {
  // Each nutrient has a signed weight: positive = good, negative = bad
  const weights = {
    protein: 0.15,
    fiber: 0.12,
    vitamin_c: 0.08,
    calcium: 0.08,
    // ...
    saturated_fat: -0.12,
    trans_fat: -0.15,
    sugar: -0.10,
    sodium: -0.08,
  };

  // Score each nutrient against its healthy range,
  // multiply by weight, sum to get 0-10 score
}
</code></pre>
<p>Why not ask GPT for the health score? Three reasons:</p>
<ul>
<li><p><strong>Cost</strong> — Every LLM call costs money. A math function is free.</p>
</li>
<li><p><strong>Consistency</strong> — The same input always produces the same score. LLMs can vary.</p>
</li>
<li><p><strong>Debuggability</strong> — When a score seems wrong, you can trace the algorithm. With an LLM, you'd be guessing.</p>
</li>
</ul>
<p><strong>Rule of thumb:</strong> If the logic can be expressed as a deterministic function, don't use AI for it.</p>
<h2>5. API Route Structure</h2>
<p>Keep your API routes thin. They should validate input, call your AI functions, and return the response:</p>
<pre><code class="language-typescript">// app/api/calculate-nutrition/route.ts
export async function POST(request: Request) {
  const body = await request.json();
  const parsed = CalculateNutritionRequestSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      { error: "Invalid request", details: parsed.error.flatten() },
      { status: 400 }
    );
  }

  const nutrition = await getNutritionInfo(parsed.data);
  const healthScore = calculateHealthScore(nutrition);
  const videos = await getRecipeVideos(nutrition.food_item);

  return NextResponse.json({ nutrition, healthScore, videos });
}
</code></pre>
<p>Zod validates the input. The AI function returns typed data. The health score is computed. Videos are fetched. No middleware chains, no abstraction layers — just a straightforward pipeline.</p>
<h2>6. Client-Side: Don't Overthink It</h2>
<p>On the frontend, a simple loading state is often enough:</p>
<pre><code class="language-typescript">const [loading, setLoading] = useState(false);
const [result, setResult] = useState&lt;NutritionResult | null&gt;(null);

const handleSubmit = async () =&gt; {
  setLoading(true);
  try {
    const response = await fetch("/api/calculate-nutrition", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ food_item, quantity, unit }),
    });
    const data = await response.json();
    setResult(data);
  } catch (err) {
    setError("Something went wrong. Please try again.");
  } finally {
    setLoading(false);
  }
};
</code></pre>
<p>I deliberately did not use streaming here. For a nutrition lookup, the user needs the complete table: partial results aren't useful. Streaming adds complexity (managing chunks, partial UI states, error handling mid-stream). It makes sense for chatbots, but not for structured data.</p>
<p><strong>Add streaming when the user benefits from seeing partial output. Skip it when they need the complete result.</strong></p>
<h2>7. Cost Control Checklist</h2>
<p>A few practical things that keep API costs in check:</p>
<ul>
<li><p><strong>Validate before calling</strong> — Client-side validation prevents empty or garbage requests from hitting the API.</p>
</li>
<li><p><strong>Limit file sizes</strong> — The calorie counter enforces a 10MB image limit client-side. Smaller images = fewer tokens.</p>
</li>
<li><p><strong>Use low temperature</strong> — For factual queries, <code>temperature: 0.3</code> or lower reduces token usage and gives more focused responses.</p>
</li>
<li><p><strong>Hybrid approach</strong> — Use AI for what requires intelligence (food identification, nutrition extraction). Use regular code for everything else (scoring, video search, CRUD).</p>
</li>
</ul>
<h2>Wrapping Up</h2>
<p>Adding AI to a Next.js app comes down to a few principles:</p>
<ol>
<li><p><strong>Use structured outputs</strong> — Zod schemas with <code>zodResponseFormat</code> eliminate parsing headaches.</p>
</li>
<li><p><strong>Handle failures gracefully</strong> — Exponential backoff for rate limits, Zod validation for inputs.</p>
</li>
<li><p><strong>Keep AI scoped</strong> — Not everything needs an LLM. Deterministic logic should stay deterministic.</p>
</li>
<li><p><strong>Skip streaming for structured data</strong> — Simple request/response is easier to build and debug.</p>
</li>
<li><p><strong>Control costs at every layer</strong> — Validate early, limit payloads, use low temperature.</p>
</li>
</ol>
<p>If you have questions or want to share how you're integrating AI into your apps, find me on <a href="https://x.com/IpseetaP">X</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How AI Changed My Coding Workflow: Real Examples That Boosted My Productivity]]></title><description><![CDATA[A few months ago, I was debugging a small Node.js issue that should have taken five minutes. Instead, I opened about 10 Stack Overflow tabs, skimmed documentation, tried two different fixes, and still]]></description><link>https://blog.ipseeta.dev/how-ai-changed-my-coding-workflow-real-examples-that-boosted-my-productivity</link><guid isPermaLink="true">https://blog.ipseeta.dev/how-ai-changed-my-coding-workflow-real-examples-that-boosted-my-productivity</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Thu, 12 Mar 2026 07:31:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/54d750ac3adc13883c24a9be/e45bf8bb-3163-4fd1-a310-08c856753f8f.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A few months ago, I was debugging a small Node.js issue that should have taken five minutes. Instead, I opened about <strong>10 Stack Overflow tabs</strong>, skimmed documentation, tried two different fixes, and still wasn't confident the solution was correct. That's when I realized something: a lot of my development time wasn't spent writing code. It was spent <strong>searching for answers</strong>.</p>
<p>Since then, AI tools have become part of my daily workflow. Not as a replacement for thinking, but as a <strong>developer assistant that helps me move faster</strong>. In this post, I'll share how I actually use AI while coding, the tools I rely on, and a few prompt techniques that consistently work well.</p>
<blockquote>
<p>AI output is a starting point, not production-ready code. Everything still needs to be reviewed and tested.</p>
</blockquote>
<h2>Why I Started Using AI for Development</h2>
<p>The biggest benefit of AI in development is simple: <strong>it removes friction</strong>. There are many small moments while coding where you lose time:</p>
<ul>
<li><p>forgetting syntax</p>
</li>
<li><p>looking for an example of a library</p>
</li>
<li><p>writing repetitive boilerplate</p>
</li>
<li><p>debugging something trivial</p>
</li>
</ul>
<p>Normally, this means searching documentation or opening multiple forum threads. With AI, I can often get a <strong>working example immediately</strong>, which helps me focus on solving the real problem instead of hunting for information.</p>
<p>That said, I follow one important rule: AI output is a starting point, not production-ready code. Everything still needs to be reviewed and tested.</p>
<h2>Tools I Use</h2>
<p>Two tool types currently play the biggest role in my workflow: inline/code-aware suggestions in the editor, and chat-style assistants for explanations and small design decisions.</p>
<ul>
<li><p>Editor extensions (quick inline help)</p>
<ul>
<li><p>GitHub Copilot: great for small completions, boilerplate, and autocomplete inside VS Code.</p>
</li>
<li><p>Tabnine / Codeium: fast, often lower-latency completions for common patterns.</p>
</li>
</ul>
</li>
<li><p>Chat assistants (conversations and context)</p>
<ul>
<li><p>ChatGPT (or similar): for explaining errors, generating minimal reproducible examples, and creating tests or migration snippets.</p>
</li>
<li><p>Built-in IDE chat (when available): keeps context local to the repo and speeds up iterative fixes.</p>
</li>
</ul>
</li>
<li><p>Local / enterprise models</p>
<ul>
<li>Self-hosted LLMs or private model endpoints when working with sensitive code or closed-source corpuses.</li>
</ul>
</li>
<li><p>Supporting tools</p>
<ul>
<li><p>Linters and formatters (ESLint, Prettier) to keep AI-generated code consistent with project style.</p>
</li>
<li><p>Test frameworks (Jest, Mocha) and E2E tools (Playwright) to verify changes quickly.</p>
</li>
<li><p>Snippet managers and PR templates to speed up review/merge tasks.</p>
</li>
</ul>
</li>
</ul>
<p>When to pick which: use editor extensions for small lines or glue code; use chat assistants when you need explanations, refactors, or to generate unit tests and alternatives.</p>
<h2>Real Before/After Examples</h2>
<p>Below are real, minimal examples that I’ve used as teaching material in my own posts and internal docs. For each: the problem, the prompt I used, the before code, the AI suggestion summary, the after code, why it works, and how I verified it.</p>
<p>Example 1 — Missing await / unhandled rejection (Mongoose-style save)</p>
<blockquote>
<p>Prompt I used: I have this Express handler — it sometimes causes unhandled promise rejections and downstream code reads stale data. Suggest a minimal fix, explain briefly, and add proper error handling.</p>
</blockquote>
<p>Before</p>
<pre><code class="language-javascript">// routes/users.js
app.post('/users', async (req, res) =&gt; {
  const user = new User(req.body);
  user.save(); // missing await
  res.status(201).json({ id: user._id });
});
</code></pre>
<p>AI suggestion (summary)</p>
<ul>
<li>Await the save() call and wrap in try/catch so errors are caught and the response is sent only after the save completes.</li>
</ul>
<p>After</p>
<pre><code class="language-javascript">// routes/users.js
app.post('/users', async (req, res) =&gt; {
  try {
    const user = new User(req.body);
    await user.save(); // wait for DB write to finish
    res.status(201).json({ id: user._id });
  } catch (err) {
    console.error('Failed to create user', err);
    res.status(500).json({ error: 'Could not create user' });
  }
});
</code></pre>
<p>Why this works</p>
<ul>
<li><code>await</code> ensures the DB operation finishes (and any errors surface) before sending a response. <code>try/catch</code> prevents unhandled promise rejections and gives a clear error response for callers.</li>
</ul>
<p>How I verified</p>
<ul>
<li>Hit the endpoint with valid and invalid payloads; confirmed response status codes and no unhandled rejection logs. Also ran a quick integration test for DB write/read.</li>
</ul>
<p>Example 2 — Missing return after early response (headers already sent)</p>
<blockquote>
<p>Prompt I used: This Express route sends a 400 on missing input but crashes with "Cannot set headers after they are sent." Show a minimal fix and explain.</p>
</blockquote>
<p>Before</p>
<pre><code class="language-js">app.post('/login', async (req, res) =&gt; {
  if (!req.body.email) {
    res.status(400).send('Missing email');
  }

  const user = await findUserByEmail(req.body.email);
  // further processing that may call res.json()
  res.json({ id: user.id });
});
</code></pre>
<p>AI suggestion (summary)</p>
<ul>
<li>Return immediately after sending the error response (or use an else), so the rest of the handler doesn't execute.</li>
</ul>
<p>After</p>
<pre><code class="language-js">app.post('/login', async (req, res) =&gt; {
  if (!req.body.email) {
    return res.status(400).send('Missing email'); // return stops execution
  }

  try {
    const user = await findUserByEmail(req.body.email);
    if (!user) return res.status(404).send('User not found');
    res.json({ id: user.id });
  } catch (err) {
    console.error(err);
    res.status(500).send('Server error');
  }
});
</code></pre>
<p>Why this works</p>
<ul>
<li>Returning after <code>res.*</code> ensures the handler stops; adding <code>try/catch</code> and additional guards prevents multiple responses and handles errors gracefully.</li>
</ul>
<p>How I verified</p>
<ul>
<li>Ran tests for missing email and nonexistent user; no header errors and correct status codes returned.</li>
</ul>
<p>Example 3 — Using async map without Promise.all (array of Promises)</p>
<blockquote>
<p>Prompt I used: I map over an array and call an async function inside map, but I see wrong behavior because the responses are not awaited correctly. Suggest a minimal fix and explain.</p>
</blockquote>
<p>Before</p>
<pre><code class="language-js">async function fetchAll(ids) {
  // getDataForId returns a Promise
  return ids.map(id =&gt; getDataForId(id)); // returns array of promises, not awaited
}

const results = await fetchAll([1,2,3]);
console.log(results); // unexpected: array of unresolved promises
</code></pre>
<p>AI suggestion (summary)</p>
<ul>
<li>Use <code>Promise.all</code> to await all Promises returned by <code>map</code>. Alternatively, use <code>for...of</code> with <code>await</code> if you need sequential execution.</li>
</ul>
<p>After (parallel)</p>
<pre><code class="language-js">async function fetchAll(ids) {
  const promises = ids.map(id =&gt; getDataForId(id));
  return Promise.all(promises); // waits for all promises to resolve
}

const results = await fetchAll([1,2,3]);
console.log(results); // array of resolved values
</code></pre>
<p>After (sequential, if order/ratelimiting matters)</p>
<pre><code class="language-js">async function fetchAllSequential(ids) {
  const results = [];
  for (const id of ids) {
    results.push(await getDataForId(id)); // sequential await
  }
  return results;
}
</code></pre>
<p>Why this works</p>
<ul>
<li><code>map</code> returns an array of Promises; <code>Promise.all</code> converts that into a single Promise that resolves when all inner Promises resolve. Use sequential <code>await</code> when you need ordering or rate-limiting.</li>
</ul>
<p>How I verified</p>
<ul>
<li>Added a mock <code>getDataForId</code> with delays and confirmed <code>fetchAll</code> waits for all results; compared timings between parallel and sequential versions.</li>
</ul>
<h2>Prompt Techniques &amp; Patterns That Work for Me</h2>
<p>A few patterns I repeatedly use to get useful, concise results from chat assistants:</p>
<ul>
<li><p>Be explicit about what you want:</p>
<ul>
<li><p>Bad: "Fix this bug"</p>
</li>
<li><p>Better: "This Express handler throws X when Y. Return a minimal fix that preserves the existing API and add a Jest unit test that covers success and the error case."</p>
</li>
</ul>
</li>
<li><p>Ask for three things in order: the fix, a short explanation, and a test/example.</p>
<ul>
<li><p>Example prompt:</p>
<blockquote>
<p>I have this Node.js function: [paste]. It throws "X". Provide (1) a minimal code fix limited to this file, (2) a 2-sentence explanation of root cause, and (3) a Jest unit test.</p>
</blockquote>
</li>
</ul>
</li>
<li><p>Use constraints to limit scope:</p>
<ul>
<li><p>"Keep changes to a single file"</p>
</li>
<li><p>"Prefer built-in Node.js APIs"</p>
</li>
<li><p>"Explain in 2–3 sentences"</p>
</li>
</ul>
</li>
<li><p>Request alternatives and trade-offs:</p>
<ul>
<li>"Give me two different fixes and list the trade-offs (performance, complexity, compatibility)."</li>
</ul>
</li>
<li><p>Ask for verification steps:</p>
<ul>
<li>"Give the minimal steps I can run locally to verify this fix, including example curl commands or test commands."</li>
</ul>
</li>
<li><p>When generating tests:</p>
<ul>
<li><p>Ask for positive, negative, and edge-case tests.</p>
</li>
<li><p>Ask for mocks/stubs for external dependencies.</p>
</li>
</ul>
</li>
</ul>
<h2>Verification &amp; Testing Checklist</h2>
<p>Before merging any AI-assisted change, I run through this checklist:</p>
<ul>
<li><p>Does the change have unit tests that cover expected and error cases?</p>
</li>
<li><p>Do linters/formatters (ESLint, Prettier) pass?</p>
</li>
<li><p>Is behavior covered by integration/E2E tests if it touches external systems?</p>
</li>
<li><p>Any new dependencies? Check license and security implications.</p>
</li>
<li><p>Any secrets accidentally exposed in the prompt or AI output (API keys, internal URLs)? Remove and rotate if needed.</p>
</li>
<li><p>Manual review — ensure readability and alignment with project architecture.</p>
</li>
<li><p>Run CI pipeline locally where possible.</p>
</li>
</ul>
<p>Automate as much of this as you can (pre-commit hooks, CI checks).</p>
<h2>Caveats &amp; Ethics</h2>
<p>AI is helpful, but it has limitations:</p>
<ul>
<li><p>Hallucinations: models can invent APIs, return incorrect code, or make up package names. Always verify.</p>
</li>
<li><p>Licensing: code examples may be influenced by training data. Be cautious when copying complex implementations verbatim into proprietary codebases.</p>
</li>
<li><p>Secrets: never paste API keys, private tokens, or sensitive internal code into public chat services. Prefer local/private models for sensitive work.</p>
</li>
<li><p>Overreliance: AI speeds up many tasks but don't skip core practices like code review, tests, and security audits.</p>
</li>
<li><p>Attribution: attribute examples where appropriate, and confirm license compatibility of any third-party snippets.</p>
</li>
</ul>
<h2>Practical Setup Tips</h2>
<ul>
<li><p>Configure your editor and team with shared settings for linters and formatters so AI-generated code matches style.</p>
</li>
<li><p>Create prompt templates in a snippet manager for common tasks (bug fixes, tests, refactors).</p>
</li>
<li><p>Use small, focused prompts and iterate — give the AI the minimal reproducible example.</p>
</li>
<li><p>Keep a changelog of AI-assisted fixes for future reference and learning.</p>
</li>
</ul>
<h2>Conclusion</h2>
<p>AI hasn't replaced my judgment, but it has removed the busywork that ate minutes and hours every day. The result: more time to think about architecture, design, and the tricky parts of problems that actually require human insight.</p>
<p>If you want to apply this to your workflow:</p>
<ul>
<li><p>Start small: use AI for tests and tiny bug fixes first.</p>
</li>
<li><p>Build a short prompt template for your team.</p>
</li>
<li><p>Add verification steps in CI to guard against hallucinations and regressions.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Securely Saving Passwords in MongoDB Through Node.js]]></title><description><![CDATA[It is important to protect sensitive data stored in web application databases from malicious actors. To do this effectively, it is essential that we use hashing instead of storing the data in plaintex]]></description><link>https://blog.ipseeta.dev/securely-saving-passwords-in-mongodb-through-nodejs</link><guid isPermaLink="true">https://blog.ipseeta.dev/securely-saving-passwords-in-mongodb-through-nodejs</guid><category><![CDATA[MongoDB]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Thu, 23 Feb 2023 11:27:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cijiWIwsMB8/upload/f2cb950db4e3dca957c9754986095ed8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It is important to protect sensitive data stored in web application databases from malicious actors. To do this effectively, it is essential that we use hashing instead of storing the data in plaintext. Hashing is a complex process which converts plaintext into a non-readable string of characters, which cannot be reversed or decrypted to the original text. By using hashing, it makes it much more difficult for malicious actors to gain access to the sensitive data and use it for malicious purposes, helping to ensure the security of that data.</p>
<p>This article covers the use of bcrypt to securely store user passwords in MongoDB through Node.js. It explains the project structure, setting up express web server, configuring MongoDB, creating an auth controller, and testing with postman. In conclusion, bcrypt is a secure algorithm for password hashing and is recommended for safe storage of sensitive data.</p>
<p>In this article, we'll use the npm library bcrypt to store user passwords in MongoDB. To demonstrate this, let's take an example of the sign-in process for a user. To keep things simple, there are just two fields: <code>username</code> and <code>password</code>.</p>
<p>In the end, we will construct the project structure in this way.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620130839164/xPSeylgu_.png" alt="Screenshot 2021-05-04 at 5.49.55 PM.png" />

<p>First, we will install the npm libraries.</p>
<pre><code class="language-plaintext">npm install express mongodb bcryptjs body-parser cors --save
</code></pre>
<p>You can use <code>mongoose</code> instead of <code>mongodb</code>.</p>
<h3>Creating an Express web server</h3>
<p>Let's create a new file called <code>server.js</code> in the root folder, which will be our main file.</p>
<pre><code class="language-plaintext">const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

const corsOptions = {
    origin: 'http://localhost:8081'
}
app.use(cors(corsOptions));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function (req, res, next) {
    res.header(
        "Access-Control-Allow-Headers",
        "x-access-token, Origin, Content-Type, Accept"
    );
    next();
});
app.get('/', (req, res) =&gt; {
    res.json({ message: 'Welcome to Mongodb auth' });
});
require('./app/routes/auth.routes')(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () =&gt; {
    console.log(`Server running at ${PORT}`);
});
</code></pre>
<p>We are using <code>body-parser</code> to create the <code>req.body</code> object by parsing the request.</p>
<h3>Setting up MongoDB</h3>
<p>We will create a file called <code>db.config.js</code> within the config folder of the app, which will store all database-related configurations.</p>
<pre><code class="language-plaintext">module.exports = {
    HOST:"localhost",
    PORT: 27017,
    DB: "bcryptdemo",
    USER: "users"
}
</code></pre>
<p>Let's now create a file called <code>mongodb.js</code> in the root folder for connecting.</p>
<pre><code class="language-plaintext">const dbConfig = require('./config/db.config');
const MongoClient = require('mongodb').MongoClient;
let conn;

exports.getConnection = async () =&gt; {
    if (conn) {
        return conn;
    }

    try {
        conn = await MongoClient.connect(`mongodb://\({dbConfig.HOST}:\){dbConfig.PORT}/`, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });
        if (conn) console.log('Mongodb connected successfully!');
        return conn;
    }
    catch (err) {
        console.log('Error in mongodb connection', err);
        process.exit();
    }
}
</code></pre>
<h3>Creating an Auth Controller</h3>
<p>We have a signup and signin function to demonstrate hashing.</p>
<h4>Signup</h4>
<pre><code class="language-plaintext">const bcrypt = require('bcryptjs');
const dbConfig = require('../config/db.config');
const conn = require('../mongodb');

exports.signup = async (req, res) =&gt; {
    const client = await conn.getConnection();
    const db = client.db(`${dbConfig.DB}`);
    bcrypt.hash(req.body.password, 12)
        .then(function (hashedPass) {
            const user = {
                username: req.body.username,
                password: hashedPass
            }
            db.collection(`${dbConfig.USER}`).insertOne(user);
            res.send({ message: 'Registered user successfully!' });
        }).catch((err) =&gt; {
            return res.status(500).send({ message: err });
        });
}
</code></pre>
<p>The bcrypt hash function takes two parameters - the password to be hashed, and the salt or saltrounds. In this case, it's set to 12, which means the bcrypt module will go through 2^12 iterations in order to hash the data.</p>
<p>The result of hash function looks like \([algorithm]\)[cost]$[salt][hash]</p>
<pre><code class="language-plaintext">\(2a\)12$A1iqBUXMMVEUAIimj9FJmeGLDwaLOz6g2i13WKVHEg3rteKLEYvLy
 |  |  |                     |
 |  |  |                     hash-value = GLDwaLOz6g2i13WKVHEg3rteKLEYvLy
 |  |  |
 |  |  salt = A1iqBUXMMVEUAIimj9FJme (base64 encoded to 22 characters)
 |  |
 |  cost-factor =&gt; 12 = 2^12 rounds
 |
 hash-algorithm identifier =&gt; 2a = BCrypt
</code></pre>
<h4>Signin</h4>
<p>To sign in, we need to find the hashed password from the database and use the <strong>compare</strong> function to compare the plaintext password with the hashed one.</p>
<pre><code class="language-plaintext">exports.signin = async (req, res) =&gt; {
    const client = await conn.getConnection();
    const db = client.db(`${dbConfig.DB}`);
    db.collection(`${dbConfig.USER}`).find({ username: req.body.username }).toArray((err, user) =&gt; {
        if (err) return res.status(500).send({ message: err });
        if (!user[0]) return res.status(404).send({ message: 'User not found' });
        bcrypt.compare(req.body.password, user[0].password).then((isPassValid)=&gt;{
            if (!isPassValid) return res.status(401).send({ message: 'Invalid Password!' });
            res.send({
                id: user[0]._id,
                username: user[0].username,
                message: 'Signed in successfully!'
            });
        }).catch((err) =&gt; {
            return res.status(500).send({ message: err });
        });
    });
}
</code></pre>
<p><strong>compare</strong> function returns a boolean.</p>
<p>We can add middleware to prevent duplicate entries when signing up.</p>
<pre><code class="language-plaintext">app.post("/auth/signup", [verifySignUp.checkDuplicateUsername], AuthController.signup);
</code></pre>
<p>In <code>verifySignUp.js</code>, let's add the below code snippet:</p>
<pre><code class="language-plaintext">checkDuplicateUsername = async (req, res, next) =&gt; {
    const client = await conn.getConnection();
    const db = client.db(`${dbConfig.DB}`);
    db.collection(`${dbConfig.USER}`).find({ username: req.body.username }).toArray((err, user) =&gt; {
        if (err) return res.status(500).send({ message: err });
        if (user[0]) {
            return res.status(400).send({ message: `Username ${user[0].username} already exists` });
        }
        next();
    });
};
</code></pre>
<h3>Testing</h3>
<p>We will use Postman to test the signup and sign-in process and check MongoDB to see if the password was saved.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620389132178/3LHjkWT7p.png" alt="Screenshot 2021-05-07 at 5.34.21 PM.png" />

<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620389171357/AJcyah31b.png" alt="Screenshot 2021-05-07 at 5.36.04 PM.png" />

<p>For some negative test cases:</p>
<p>Let's try adding the same user!</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620389629286/yQQyjz84i.png" alt="Screenshot 2021-05-07 at 5.43.33 PM.png" />

<p>Entering an incorrect password.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620389532374/LvldjKAQi.png" alt="Screenshot 2021-05-07 at 5.42.03 PM.png" />

<p>We can view the password in its hashed form in MongoDB.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620386612254/HjhuL1ezd.png" alt="Screenshot 2021-05-04 at 6.28.13 PM.png" />

<p>In conclusion, bcrypt is a secure algorithm for password hashing and is recommended for safe storage of sensitive data. It is more secure than other methods of password hashing due to its use of a cost factor, which makes it more difficult for attackers to brute force the password. Additionally, it is an easy to use library that is available in Node.js and can be easily integrated into web applications.</p>
]]></content:encoded></item><item><title><![CDATA[Pm2 Cheat Sheet]]></title><description><![CDATA[Here is a quick cheat sheet of pm2 commands:-
Installing pm2
npm install pm2 -g

Start and name a process
pm2 start app.js --name myApp

Start and auto-restart on file change
pm2 start app.js --watch ]]></description><link>https://blog.ipseeta.dev/pm2-cheat-sheet</link><guid isPermaLink="true">https://blog.ipseeta.dev/pm2-cheat-sheet</guid><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Tue, 07 Jul 2020 19:33:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1594151323014/gIFlpfK_P.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here is a quick cheat sheet of pm2 commands:-</p>
<p><strong>Installing pm2</strong></p>
<pre><code class="language-plaintext">npm install pm2 -g
</code></pre>
<p><strong>Start and name a process</strong></p>
<pre><code class="language-plaintext">pm2 start app.js --name myApp
</code></pre>
<p><strong>Start and auto-restart on file change</strong></p>
<pre><code class="language-plaintext">pm2 start app.js --watch 
</code></pre>
<p><strong>List apps</strong></p>
<pre><code class="language-plaintext">pm2 list /*Shows all the processes*/
pm2 prettylist /*Prints process list in beautified JSON*/
pm2 describe 0 /*Display all information about a specific process*/
pm2 monit /*Monitor all processes*/
</code></pre>
<p><strong>Logs</strong></p>
<pre><code class="language-plaintext">pm2 logs  /*Display all processes logs*/
pm2 flush  /*Empty all log files*/
pm2 reloadLogs /*Reload all logs*/
</code></pre>
<p><strong>Misc</strong></p>
<pre><code class="language-plaintext">pm2 status /*Shows process status(online, stopped, errored), restart count, uptime, cpu and memory usage*/
pm2 stop id|name /*Stop a process*/
pm2 restart id|name /*Restart a process*/
pm2 delete id|name /*Delete a process*/
pm2 stop all /*Stop all processes*/
pm2 restart all /*Restarts all processes*/
pm2 delete all /*Removes all processes from pm2 list*/
</code></pre>
<p><strong>Some extras</strong></p>
<pre><code class="language-plaintext">ENV_VARIABLE_NAME="VALUE" pm2 restart &lt;pid&gt; --update-env /*This will add an environment variable to your process*/
pm2 env &lt;pid&gt; /*This will print all the process.env variables*/
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Building a Todo app using ReactJS and Serverless]]></title><description><![CDATA[Lately, I have been experimenting a lot with AWS Lambda and other serverless platforms. To teach myself the concept of serverless I built a simple todo app using AWS Lambda and React. In this article,]]></description><link>https://blog.ipseeta.dev/building-a-todo-app-using-reactjs-and-serverless</link><guid isPermaLink="true">https://blog.ipseeta.dev/building-a-todo-app-using-reactjs-and-serverless</guid><category><![CDATA[serverless]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[React]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Fri, 08 Feb 2019 18:04:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1549632143642/qZ3qKM9IQ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Lately, I have been experimenting a lot with AWS Lambda and other serverless platforms. To teach myself the concept of serverless I built a simple todo app using AWS Lambda and React. In this article, I am going to outline the steps needed to build such a todo app and explain various concepts through code snippets.</p>
<p>The code is available on GitHub. I suggest forking the codebase so that it will be easier for you to follow along.</p>
<p>The repos are:</p>
<ul>
<li><a href="https://github.com/Ipseeta/todoappapi">Serverless code</a></li>
<li><a href="https://github.com/Ipseeta/todoapp">React code</a></li>
</ul>
<p>Also, there is a <a href="https://reverent-yonath-4aa6c3.netlify.com">quick and dirty demo</a> for you, if you are interested.</p>
<p>Let's get started.</p>
<h2>Content</h2>
<ul>
<li><a href="#what-is-serverless-">What is serverless?</a></li>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#dependencies-and-setup">Dependencies and setup</a></li>
<li><a href="#project-structure">Project Structure</a></li>
<li><a href="#some-coding">Some Coding</a></li>
<li><a href="#deployment">Deployment</a></li>
<li><a href="#configuring-with-react">Configuring with React</a></li>
</ul>
<h2>What is serverless?</h2>
<p>Traditionally, when we deploy our web application to a server, we are charged for keeping the server up, even if, there is no request. We are responsible for its uptime and maintenance. <strong>Serverless</strong> is an architecture where you build and run applications and services without worrying about infrastructure management. So, now we can quickly build, configure and deploy resources with a few commands. We only pay for the compute time we consume. There is no charge when our code is not running.</p>
<p>We have many serverless  framework providers such as: </p>
<ul>
<li><a href="https://cloud.google.com/functions/">Google's Cloud Functions</a> </li>
<li><a href="https://aws.amazon.com/lambda/">Amazon's AWS Lambda functions</a> </li>
<li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/">Microsoft's Azure functions</a>,</li>
<li><a href="https://developers.cloudflare.com/workers/deploying-workers/serverless/">Cloudflare</a></li>
</ul>
<p>Here we are going to use AWS Lambda functions as our cloud service provider. Lambda is an event-driven, serverless computing platform that executes your code in response to various events.</p>
<p>Now let's check out some tools needed to build our todo app:</p>
<h2>Prerequisites</h2>
<ol>
<li>AWS account</li>
<li>MongoDB Atlas -- to host our todos</li>
<li>Node.js 8.10 or above</li>
<li>ReactJS</li>
</ol>
<h2>Dependencies and setup</h2>
<p>First of all, create a node.js project with the following dependencies</p>
<p><img src="https://hashnode.imgix.net/res/hashnode/image/upload/v1549617645695/sFuMN_MtC.png?h=300&amp;w=300" alt="Screen Shot 2019-02-08 at 2.50.11 PM.png" /></p>
<p>and install <code>serverless</code> module:</p>
<pre><code>npm install -g serverless
</code></pre>
<p><code>serverless</code> is an application framework to build and deploy functions to different serverless platforms such as AWS Lambda, Google cloud functions etc.</p>
<p>Next, create an IAM(Identity and Access Management) user in your AWS console by following <a href="https://serverless-stack.com/chapters/create-an-iam-user.html">this</a> guide. Note the <code>Access key ID</code> and <code>Secret access key</code>. We'll need them for configuring our app.</p>
<pre><code>serverless config credentials --provider aws --key  your-Access-key-ID --secret your-secret-access-key
</code></pre>
<p>Next, we'll need a database to store our <code>todo</code> items. For the sake of simplicity, let's use <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a>, a hosted MongoDB service to host our MongoDB instance. Create your database cluster using <a href="https://docs.atlas.mongodb.com/getting-started/">this</a> tutorial.</p>
<h2>Project Structure</h2>
<p>After setting up the above dependencies, we are going to write some code for our serverless app. Here is how the directory structure looks like:</p>
<p><img src="https://hashnode.imgix.net/res/hashnode/image/upload/v1549646188860/HJHjcg8ZB.png?h=500&amp;w=500" alt="Screen Shot 2019-02-08 at 3.21.48 PM.png" /></p>
<h2>Some Coding</h2>
<ul>
<li>Let's write <code>server.js</code> where we'll put only the logic for running our lambda function with the <code>serverless-http</code> module.</li>
</ul>
<pre><code>const serverless = require('serverless-http')
const app = require('./lib/app')
module.exports.run = serverless(app)
</code></pre>
<p>Here, you can see we are packing our Express <code>app</code> into a lambda function <code>run</code>. <code>serverless-http</code> module allows us to 'wrap' our API for serverless usage.</p>
<ul>
<li>To connect to our Atlas cluster, we need to pass our connection string as</li>
</ul>
<pre><code>'mongodb://&lt;username&gt;:&lt;password&gt;@&lt;cluster&gt;:27017,&lt;host&gt;.mongodb.net:27017,&lt;host N&gt;.mongodb.net:27017/&lt;database&gt;?ssl=true&amp;replicaSet=&lt;replicasetName&gt;&amp;authSource=admin&amp;retryWrites=true'
</code></pre>
<p>The code looks like following:</p>
<pre><code>mongoose.connect(config.mongoConnectionString, { useNewUrlParser: true });
</code></pre>
<p>Here, we are using <code>mongoose</code> node module to connect to the remote MongoDB cluster.</p>
<ul>
<li>Adding routes in index.js</li>
</ul>
<pre><code>const express = require('express');
const router = express.Router();
const todos = require('../controllers/todos.controller');

router.use('/todos', todos);
module.exports = router;
</code></pre>
<ul>
<li>Writing some logic</li>
</ul>
<p>We have a schema <code>Todo</code> in <code>lib/models</code> which has a single property called <code>title</code>.</p>
<pre><code>const mongoose = require('mongoose');
const TodoSchema = new mongoose.Schema({
  title: String
});
module.exports = mongoose.model('Todo', TodoSchema);
</code></pre>
<p>Moving further, we are going to write some CRUD operations in <code>todo.controller</code>:</p>
<pre><code>const express = require('express')
const router = express.Router()
const Todo = require('../models/todo')

router
    .get('/', async (req, res) =&gt; {
        const todos = await Todo.find().select('title').sort({"_id": -1});
        res.set("Access-Control-Allow-Origin", "*");
        res.json(todos);
    });

router
    .post('/', async (req, res) =&gt; {
        if (!req.body) {
            return res.status(403).end();
        }
        const todo = await Todo.create(req.body)
        res.set("Access-Control-Allow-Origin", "*");
        res.json(todo);
    });

router
    .put('/:id', async (req, res) =&gt; {
        if (!req.body) {
            return res.status(403).end();
        }
        const todo = await Todo.findByIdAndUpdate(req.params.id, {
            $set: req.body
        }, {
            $upsert: true,
            new: true
        })
        res.set("Access-Control-Allow-Origin", "*");
        res.json(todo);
    });

router
    .delete('/:id', async (req, res) =&gt; {
        const todo = await Todo.deleteOne({
            _id: req.params.id
        })
        res.set("Access-Control-Allow-Origin", "*");
        res.json(todo);
    });

module.exports = router;
</code></pre>
<p>In the above snippet we implemented basic CRUD operations using mongoose.</p>
<ul>
<li>Configuring <code>serverless.yml</code> with all the function and general settings.</li>
</ul>
<pre><code>service: todo-app-api

provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-1

functions:
  app:
    handler: server.run
    events:
      - http:
          path: api/todos
          method: any
          cors: 
            allowCredentials: true
            origin: '*'
            headers: 
              - accept
              - Content-Type
              - Origin
              - User-Agent
              - Referer
      - http:
          path: api/todos/{id}
          method: any
          request:
            parameters:
              paths:
                id: true
          cors: 
            allowCredentials: true
            origin: '*'
            headers: 
              - accept
              - Content-Type
              - Origin
              - User-Agent
              - Referer
</code></pre>
<p>As mentioned above, our lambda function is <code>run</code>. We are informing this to serverless through <code>handler</code>. Our path for <code>GET</code> and <code>POST</code> i.e for read and create operations is <code>api/todos</code>. Similarly, for update and delete we have <code>PUT</code> and <code>DELETE</code> requests and the API is <code>api/todos/{id}</code>.</p>
<h2>Deployment</h2>
<p>Now to deploy, we just need to run <code>serverless deploy</code> and it's done! If your deployment is successful, you will see a <code>.serverless</code> folder getting created in your project.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1549622607828/kpGzMY5tg.png" alt="Screen Shot 2019-02-08 at 4.12.58 PM.png" /></p>
<p>You can now use a tool like Postman to test your endpoints.</p>
<h2>Creating a front-end using React</h2>
<p>In this section, we'll build a simple UI using React that interacts with our serverless APIs. The UI will be similar to this:</p>
<p><img src="https://hashnode.imgix.net/res/hashnode/image/upload/v1549623203836/6v1rNHopv.png?h=500&amp;w=500" alt="Screen Shot 2019-02-08 at 3.45.59 PM.png" /></p>
<p>and functionality will be something like this:</p>
<p><a class="embed-card" href="https://www.youtube.com/watch?v=stafuvXwPdU">https://www.youtube.com/watch?v=stafuvXwPdU</a></p>

<p>**Note: ** We are not going to write any CSS here. You can style your component as you want.</p>
<ul>
<li><p>We'll use <code>create-react-app</code> to create the basic structure. Just run <code>create-react-app todoapp</code> to get started. Make sure you have installed <code>create-react-app</code> npm module globally before issuing the above command. The project structure  will look something like this:
<img src="https://hashnode.imgix.net/res/hashnode/image/upload/v1549646061535/mrxjjlRtb.png?h=500&amp;w=500" alt="Screen Shot 2019-02-08 at 10.42.26 PM.png" /></p>
</li>
<li><p>First, let's add an input form to our main component <code>App.js</code>:</p>
</li>
</ul>
<pre><code>&lt;div&gt;
    &lt;input
          placeholder="Enter Task"
          ref={c =&gt; {
                this.inputElement = c;
          }}
          value={this.state.currentItem.text}
          onChange={this.handleInput}
      /&gt;
      &lt;button onClick={this.addItem}&gt;Add Task&lt;/button&gt;
 &lt;/div&gt;
</code></pre>
<p>Our function <code>addItem</code> is called when we want to add a new todo item. This is done by hitting our serverless endpoint using <code>fetch</code>:</p>
<pre><code>addItem = async (e) =&gt; {
    e.preventDefault();
    const newItem = this.state.currentItem;
    if (newItem.title !== '') {
      const response = await fetch('https://b3tcfb1z62.execute-api.us-east-1.amazonaws.com/dev/api/todos', {
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json',
            'User-Agent': 'todo',
          },
          body: JSON.stringify({title: newItem.title}),
          method:'POST'
      });
      const json = await response.json();
      const items = this.state.items;
      items.unshift(json);
      this.setState({ items: items });
      this.inputElement.value = '';
    }
  }
</code></pre>
<ul>
<li>To show the todo items, we need to create a component <code>TodoItems</code> and add it to App.js</li>
</ul>
<pre><code>import React, { Component } from 'react';
import TodoItem from './TodoItem';

class TodoItems extends Component {
  constructor() {
    super()
    this.state = {
      listItems: []
    }
  }
    
  render() {
    const todoEntries = this.props.entries
    const listitems = todoEntries.map((item) =&gt; {
      return (
        &lt;TodoItem key={item._id} item={item} editItem = {this.props.editItem} deleteItem= {this.props.deleteItem}/&gt;
      )
    });

    return &lt;ul&gt;{listitems}&lt;/ul&gt;
  }
}

export default TodoItems
</code></pre>
<p>To fetch the todo entries, we need to call our <code>GET</code> API in <code>componentDidMount()</code> of <code>App.js</code> and set the result in the <code>items</code> state. We'll pass this as <code>entries</code> prop to <code>TodoItems</code></p>
<pre><code>  componentDidMount = async () =&gt; {
    const response = await fetch('https://b3tcfb1z62.execute-api.us-east-1.amazonaws.com/dev/api/todos', {
      headers: {
				accept: 'application/json',
				'Content-Type': 'application/json',
				'User-Agent': 'todo',
			},
      method:'GET'
    });
    const json = await response.json();
    this.setState({items : json});
  }
</code></pre>
<p>Here is how we use <code>TodoItems</code> component inside <code>render</code> function of <code>App.js</code>:</p>
<pre><code>&lt;TodoItems entries={this.state.items} editItem={this.editItem} deleteItem={this.deleteItem}/&gt;
</code></pre>
<p>In <code>TodoItems</code> component, we will iterate over the entries and return a <code>TodoItem</code> component which shows each item's title.</p>
<pre><code>    const todoEntries = this.props.entries
    const listitems = todoEntries.map((item) =&gt; {
      return (
        &lt;TodoItem key={item._id} item={item} editItem = {this.props.editItem} deleteItem= {this.props.deleteItem}/&gt;
      )
    });

    return &lt;ul&gt;{listitems}&lt;/ul&gt;
</code></pre>
<p>Here is how our <code>TodoItem</code> component looks like:</p>
<pre><code>import React, { Component } from 'react';

class TodoItem extends Component {
  constructor() {
    super()
    this.state = {
      editMode: false
    }
  }
  toggleEdit = e =&gt; {
    e.preventDefault();
    this.setState({ editMode: !this.state.editMode });
  }

  callUpdateAPI = (e,title) =&gt; {
      e.preventDefault();
      if (e.keyCode === 13) {
        this.props.editItem(title,this.props.item._id);
        this.toggleEdit(e);
      }
  }
  render() {
      const item = this.props.item;
      return (
        &lt;li key={item._id}&gt;
          {!this.state.editMode ? &lt;span&gt;{item.title}&lt;/span&gt;
          :
            &lt;input
                defaultValue={item.title}
                ref={c =&gt; {
                    this.inputElement = c;
                }}
                onKeyUp = {e =&gt; { this.callUpdateAPI(e,e.target.value) }}
            /&gt;
      }{!this.state.editMode ?&lt;button type='submit' onClick={this.toggleEdit}&gt;Edit Task&lt;/button&gt;: &lt;button type='submit' onClick={e =&gt; { this.props.editItem(this.inputElement.value,this.props.item._id); this.toggleEdit(e); }}&gt;Update&lt;/button&gt;} &lt;button type='submit' onClick={() =&gt; this.props.deleteItem(item._id)}&gt;Delete Task&lt;/button&gt;
        &lt;/li&gt;
      )
    }
}

export default TodoItem
</code></pre>
<ul>
<li>Now coming to <code>update</code> part, when we click on <code>Edit Task</code> our todo item will be converted into an input tag with an <code>update</code> button. To achieve the above, we are using a <code>state</code> variable called <code>editMode</code>.</li>
</ul>
<p>On clicking the <code>Update</code> button, we will call our <code>PUT</code> API,</p>
<pre><code>callUpdateAPI = (e,title) =&gt; {
      e.preventDefault();
      if (e.keyCode === 13) {
        this.props.editItem(title,this.props.item._id);
        this.toggleEdit(e);
      }
  }
</code></pre>
<p>Here is how the <code>fetch</code> call for update looks like:</p>
<pre><code>editItem = async (title,id) =&gt; {
    const response = await fetch(`https://b3tcfb1z62.execute-api.us-east-1.amazonaws.com/dev/api/todos/${id}`, {
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json',
            'User-Agent': 'todo',
          },
          body: JSON.stringify({ title: title }),
          method:'PUT'
        });
    const json = await response.json();
    this.state.items.forEach(item =&gt; {
      if(item._id === json._id) {
        item.title = json.title;
      }
    });
    this.setState({ items: this.state.items});
  }
</code></pre>
<ul>
<li>Similarly, to delete a task we will add a button <code>Delete Task</code> in our <code>TodoItem.js</code>.</li>
</ul>
<pre><code>&lt;button type='submit' onClick={() =&gt; this.props.deleteItem(item._id)}&gt;Delete Task&lt;/button&gt;
</code></pre>
<p>and delete it using <code>DELETE</code> API call</p>
<pre><code>deleteItem = async(id) =&gt; {
    const filteredItems = this.state.items.filter(item =&gt; {
      return item._id !== id
    })
    const response = await fetch(`https://b3tcfb1z62.execute-api.us-east-1.amazonaws.com/dev/api/todos/${id}`, {
          headers: {
            accept: 'application/json',
            'Content-Type': 'application/json',
            'User-Agent': 'todo',
          },
          method:'DELETE'
        })
    const json = await response.json();
    if (json.deletedCount === 1) {
      this.setState({ items: filteredItems});
    }
  }
</code></pre>
<p>The entire code is available in two separate GitHub repos:</p>
<ul>
<li><a href="https://github.com/Ipseeta/todoappapi">Serverless code</a></li>
<li><a href="https://github.com/Ipseeta/todoapp">React code</a></li>
</ul>
<p>Feel free to check them out and play around with the code. <a href="https://reverent-yonath-4aa6c3.netlify.com">Here is a demo</a> of the app in case you want to check out a live version.  I hope you enjoyed reading this. Let me know what you think in comments below! </p>
]]></content:encoded></item><item><title><![CDATA[Frequently asked JavaScript and Node.js interview questions]]></title><description><![CDATA[I have been helping a friend crack preliminary round of JavaScript/Node.js interviews. In the process I have identified a few must-know questions that are asked in almost all interviews. 
So, here is a list of such Node.js interview questions with th...]]></description><link>https://blog.ipseeta.dev/frequently-asked-javascript-and-nodejs-interview-questions</link><guid isPermaLink="true">https://blog.ipseeta.dev/frequently-asked-javascript-and-nodejs-interview-questions</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Fri, 25 Jan 2019 10:51:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1548420076601/HJHxEY_X4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have been helping a friend crack preliminary round of JavaScript/Node.js interviews. In the process I have identified a few must-know questions that are asked in almost all interviews. </p>
<p>So, here is a list of such Node.js interview questions with their answers that will help you crack basic JS interviews.</p>
<h2 id="what-is-nodejs">What is Node.js?</h2>
<p>Node.js is a platform built on Chrome's V8 engine to run JavaScript on the server. It is a single-threaded event-based platform.</p>
<h2 id="why-is-nodejs-single-threaded">Why is Node.js Single-threaded?</h2>
<p>Node.js applications use <strong>"Single Threaded Event Loop Model"</strong> architecture to handle multiple concurrent clients. Node.js works on Event Loop which is single threaded and uses multiple threads internally to execute asynchronous code. Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads ( worker threads ). So, if you make a synchronous call which is CPU intensive it will block the thread. Hence we go for an asynchronous call which has better performance and scalability when they are single-threaded over multi-threaded, making Node.js Single-threaded.</p>
<h2 id="why-do-people-use-nodejs">Why do people use Node.js?</h2>
<p>Node.js allows you to build the entire website only in one programming language i.e JavaScript. Node.js can be used to build different types of applications such as regular web applications, real-time apps, REST API servers etc. It is preferred for the following reasons:</p>
<ul>
<li><strong>Fast:</strong> Node.js library is very fast in code execution.</li>
<li><strong>Scalable:</strong> It is highly scalable because of its event mechanism which helps the server to respond in a non-blocking way.</li>
<li><strong>Full Stack JS:</strong> People who are comfortable with JavaScript get to use the same language across the whole stack (which means more code reuse)</li>
</ul>
<h2 id="what-are-some-of-the-most-popular-modules-of-nodejs">What are some of the most popular modules of Node.js?</h2>
<p>Some libraries/frameworks that are commonly used by Node.js developers:</p>
<ul>
<li>express</li>
<li>fs</li>
<li>moment</li>
<li>lodash</li>
<li>mongoose</li>
<li>async</li>
<li>isomorphic-fetch</li>
<li>passport</li>
<li>cookie-parser</li>
<li>jest/morgan</li>
</ul>
<p>and there are many more. You should ideally keep your own list of favorite npm modules.</p>
<h2 id="explain-callback-in-nodejs">Explain callback in Node.js.</h2>
<p>A callback is simply a function you pass into another function so that it can be called at a later time.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cbExample</span>(<span class="hljs-params">val, callback</span>)</span>{
    <span class="hljs-keyword">if</span>(val == <span class="hljs-number">1</span>){
        callback(<span class="hljs-literal">true</span>);
    }<span class="hljs-keyword">else</span>{
        callback(<span class="hljs-literal">false</span>);
    }
}

cbExample(<span class="hljs-number">0</span>, 
<span class="hljs-comment">//the anonymous function below defines the functionality of the callback</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">bool</span>) {
        <span class="hljs-comment">//do something</span>
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">//do something</span>
    }
});
</code></pre><h2 id="what-is-error-first-callback">What is error-first callback?</h2>
<p>It is a pattern where a callback function takes an <code>Error</code> object as first parameter and result object as second.</p>
<p>Example:</p>
<pre><code>fs.readFile(path, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{  
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-comment">// handle the error</span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.log(err)
  }
  <span class="hljs-comment">// use the data object</span>
  <span class="hljs-built_in">console</span>.log(data)
})
</code></pre><h2 id="what-is-callback-hell-and-how-can-you-avoid-it">What is callback hell and how can you avoid it?</h2>
<p>Callback hell is heavily nested callbacks which make the code unreadable and difficult to maintain. </p>
<pre><code><span class="hljs-keyword">const</span> verifyUser = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">username, password, callback</span>)</span>{
   db.verifyUser(username, password, <span class="hljs-function">(<span class="hljs-params">error, userInfo</span>) =&gt;</span> {
       <span class="hljs-keyword">if</span> (error) {
           callback(error)
       }<span class="hljs-keyword">else</span>{
           db.getRoles(username, <span class="hljs-function">(<span class="hljs-params">error, roles</span>) =&gt;</span> {
               <span class="hljs-keyword">if</span> (error){
                   callback(error)
               }<span class="hljs-keyword">else</span> {
                   db.logAccess(username, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
                       <span class="hljs-keyword">if</span> (error){
                           callback(error);
                       }<span class="hljs-keyword">else</span>{
                           callback(<span class="hljs-literal">null</span>, userInfo, roles);
                       }
                   })
               }
           })
       }
   })
};
</code></pre><p>We can avoid callback hell by :</p>
<ul>
<li>modularization: breaking callbacks into small independent functions</li>
</ul>
<pre><code><span class="hljs-keyword">const</span> verifyUser = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">username, password</span>) </span>{
   db.verifyUser(username, password)
       .then(<span class="hljs-function"><span class="hljs-params">userInfo</span> =&gt;</span> db.getRoles(userInfo))
       .then(<span class="hljs-function"><span class="hljs-params">rolesInfo</span> =&gt;</span> db.logAccess(rolesInfo))
       .then(<span class="hljs-function"><span class="hljs-params">finalResult</span> =&gt;</span> {
           <span class="hljs-comment">//do whatever the 'callback' would do</span>
       })
       .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
           <span class="hljs-comment">//do whatever the error handler needs</span>
       });
};

<span class="hljs-keyword">const</span> getRoles = <span class="hljs-keyword">new</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">userInfo</span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
       db.connect()
           .then(<span class="hljs-function">(<span class="hljs-params">connection</span>) =&gt;</span> connection.query(<span class="hljs-string">'get roles sql'</span>))
           .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> resolve(result))
           .catch(reject)
   });
};
</code></pre><ul>
<li>using <code>async</code> module: async provides straight-forward, powerful functions for working with asynchronous JavaScript</li>
<li>using generators with Promises</li>
</ul>
<pre><code><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readFile</span>(<span class="hljs-params">file, encoding</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    fs.readFile(file, encoding, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

      resolve(data);
    })
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">processFile</span>(<span class="hljs-params">inputFilePath, encoding</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> text = <span class="hljs-keyword">yield</span> readFile(inputFilePath, encoding);
    <span class="hljs-keyword">const</span> processedText = text.toUpperCase();
    <span class="hljs-keyword">return</span> processedText;
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-built_in">String</span>(e));
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">execute</span>(<span class="hljs-params">generator, yeildValue</span>) </span>{
  <span class="hljs-keyword">const</span> next = generator.next(yeildValue);

  <span class="hljs-keyword">if</span> (!next.done) {
    next.value.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> execute(generator, result))
              .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> generator.throw(err));
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(next.value);
  }
}

execute(processFile(<span class="hljs-string">'./input1.txt'</span>, <span class="hljs-string">'utf-8'</span>));
</code></pre><ul>
<li>use async/await</li>
</ul>
<pre><code><span class="hljs-keyword">const</span> verifyUser = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">username, password</span>)</span>{
   <span class="hljs-keyword">try</span> {
       <span class="hljs-keyword">const</span> userInfo = <span class="hljs-keyword">await</span> db.verifyUser(username, password);
       <span class="hljs-keyword">const</span> rolesInfo = <span class="hljs-keyword">await</span> db.getRoles(userInfo);
       <span class="hljs-keyword">const</span> logStatus = <span class="hljs-keyword">await</span> db.logAccess(userInfo);
       <span class="hljs-keyword">return</span> userInfo;
   }<span class="hljs-keyword">catch</span> (e){
       <span class="hljs-comment">//handle errors as needed</span>
   }
};
</code></pre><h2 id="what-is-a-promise">What is a Promise?</h2>
<p>A promise is an object whose value is not available yet but will be available in future. This returned value can be a resolved value or a reason depicting why it is rejected. It will be in one of 3 possible states:</p>
<ul>
<li>Fulfilled: <code>resolve()</code> was called</li>
<li>Rejected: <code>reject()</code> was called</li>
<li>Pending: not yet fulfilled or rejected</li>
</ul>
<pre><code><span class="hljs-keyword">var</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//simulate an async call</span>
    resolve(<span class="hljs-string">'foo'</span>);
  }, <span class="hljs-number">300</span>);
});

promise.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-built_in">console</span>.log(value);
  <span class="hljs-comment">// expected output: "foo"</span>
});
</code></pre><h2 id="what-are-modules-and-what-is-the-purpose-of-moduleexports-in-nodejs">What are modules and what is the purpose of <code>module.exports</code> in Node.js?</h2>
<p>Modules are a reusable block of code whose existence does not impact other code in any way. It encapsulates related code into a single unit of code. Modules are important for maintainability, reusability, and namespacing of code.</p>
<pre><code><span class="hljs-built_in">module</span>.exports = {

    <span class="hljs-attr">sayHelloInEnglish</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
    }
    <span class="hljs-attr">sayHelloInHindi</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Namaste"</span>;
    }
}
</code></pre><p>Here <code>module.exports</code> exposes two functions to the outer world. We can import and use these functions.</p>
<pre><code><span class="hljs-keyword">var</span> greetings = <span class="hljs-keyword">require</span>(<span class="hljs-string">"./greeting.js"</span>);
greetings.sayHelloInHindi(); <span class="hljs-comment">//Namaste</span>
</code></pre><h2 id="explain-in-brief-the-difference-among-setinterval-settimeout-setimmediate-and-processnexttick">Explain in brief the difference among <code>setInterval()</code>, <code>setTimeout()</code>, <code>setImmediate()</code> and <code>process.nextTick()</code>.</h2>
<p><code>setInterval()</code>: As the name suggests it can be used to execute a block of code multiple times in fixed intervals.</p>
<pre><code>const intervalObj = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Execute multiple times'</span>);
}, <span class="hljs-number">500</span>);

<span class="hljs-built_in">clearInterval</span>(intervalObj);
</code></pre><p><code>setTimeout()</code>: It can be used to schedule code execution after a designated amount of milliseconds.</p>
<pre><code>const timeoutObj = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'timeout beyond time'</span>);
}, <span class="hljs-number">1500</span>);

<span class="hljs-built_in">clearTimeout</span>(timeoutObj);
</code></pre><p><code>setImmediate()</code>: It is used to execute code at the end of the current event loop cycle.</p>
<pre><code>const immediateObj = setImmediate(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'immediately executing immediate'</span>);
});

clearImmediate(immediateObj);
</code></pre><p><code>process.nextTick()</code>: It can be used to schedule a callback function to be invoked in the next iteration of the event loop.</p>
<p>It's worth noting that <code>process.nextTick()</code> fires more immediately than <code>setImmediate()</code>.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processed in next iteration'</span>);
}
process.nextTick(cb);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processed in the first iteration'</span>);
<span class="hljs-comment">//Processed in the first iteration'</span>
<span class="hljs-comment">//Processed in next iteration</span>
</code></pre><h2 id="what-are-some-different-ways-to-do-ajax-calls-in-javascript">What are some different ways to do ajax calls in JavaScript?</h2>
<p>In the interviews, interviewers often ask to write different types of ajax calls in JavaScript. Refer to the <a target="_blank" href="https://hashnode.com/post/7-different-ways-to-make-ajax-calls-in-javascript-in-2019-cjr7pi2fl000gdjs2zgssqwhr">article</a> to know more about different ways to do Ajax calls in JavaScript.</p>
<h2 id="what-are-some-interesting-es6-features">What are some interesting ES6 features?</h2>
<h4 id="default-parameters">Default Parameters:</h4>
<p>In ES5, the default value is specified inside a function like this:</p>
<pre><code><span class="hljs-keyword">var</span> link = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">height, color, url</span>) </span>{
    <span class="hljs-keyword">var</span> height = height || <span class="hljs-number">50</span>
    <span class="hljs-keyword">var</span> color = color || <span class="hljs-string">'red'</span>
    <span class="hljs-keyword">var</span> url = url || <span class="hljs-string">'https://hashnode.com'</span>
    ...
}
</code></pre><p>In ES6, we can put the default values in the function params, right next to the passing arguments:</p>
<pre><code><span class="hljs-keyword">var</span> link = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">height = <span class="hljs-number">50</span>, color = <span class="hljs-string">'red'</span>, url = <span class="hljs-string">'http://hashnode.com'</span></span>) </span>{
  ...
}
</code></pre><h4 id="template-literals">Template Literals:</h4>
<p>Template literals or interpolation in other languages is a way to output variables in the string.</p>
<p>In ES5,</p>
<pre><code><span class="hljs-keyword">var</span> name = <span class="hljs-string">'Your name is '</span> + first + <span class="hljs-string">' '</span> + last + <span class="hljs-string">'.'</span>
<span class="hljs-keyword">var</span> url = <span class="hljs-string">'http://localhost:3000/api/messages/'</span> + id
</code></pre><p>In ES6, we can use ticked string as following:</p>
<pre><code><span class="hljs-keyword">var</span> name = <span class="hljs-string">`Your name is <span class="hljs-subst">${first}</span> <span class="hljs-subst">${last}</span>.`</span>
<span class="hljs-keyword">var</span> url = <span class="hljs-string">`http://localhost:3000/api/messages/<span class="hljs-subst">${id}</span>`</span>
</code></pre><h4 id="multi-line-strings">Multi-line Strings:</h4>
<p>In ES5,</p>
<pre><code><span class="hljs-keyword">var</span> books = <span class="hljs-string">'THE MURDER OF ROGER ACKROYD,\n\t'</span>
                          + <span class="hljs-string">'MURDER ON THE ORIENT EXPRESS,\n\t'</span>
                            + <span class="hljs-string">'AND THEN THERE WERE NONE,\n\t'</span>
                              + <span class="hljs-string">'A MURDER IS ANNOUNCED,\n\t'</span>
                                + <span class="hljs-string">'FIVE LITTLE PIGS\n\t'</span>
</code></pre><p>In ES6, backticks come to rescue,</p>
<pre><code>var books = `THE MURDER <span class="hljs-keyword">OF</span> ROGER ACKROYD,
MURDER <span class="hljs-keyword">ON</span> THE ORIENT EXPRESS,
<span class="hljs-keyword">AND</span> <span class="hljs-keyword">THEN</span> THERE WERE <span class="hljs-keyword">NONE</span>,
A MURDER <span class="hljs-keyword">IS</span> ANNOUNCED,
FIVE LITTLE PIGS`
</code></pre><h4 id="arrow-functions">Arrow Functions:</h4>
<p>Arrow functions provide a more concise syntax for writing function expressions. Arrow functions do not have <code>this</code>. If <code>this</code> is accessed, it is taken from the outside (outer scope).</p>
<pre><code><span class="hljs-comment">// (param1, param2, paramN) =&gt; expression</span>

<span class="hljs-comment">// ES5</span>
<span class="hljs-keyword">var</span> addES5 = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x + y;
};

<span class="hljs-comment">// ES6</span>
<span class="hljs-keyword">const</span> addES6 = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> { <span class="hljs-keyword">return</span> x + y };

<span class="hljs-comment">//No parameter</span>

<span class="hljs-comment">//ES5</span>
<span class="hljs-keyword">var</span> functionES5 = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunc</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
};

<span class="hljs-comment">//ES6</span>
<span class="hljs-keyword">var</span> functionES6 = <span class="hljs-function">() =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>); };
functionES6(); <span class="hljs-comment">// Hello</span>
</code></pre><h4 id="let-and-const">Let and Const</h4>
<p>In ES5, variables are declared using <code>var</code> (global scope). In ES6, block scoped <code>let</code> and <code>const</code> is used to declare variables.</p>
<p>Let's see the difference between var, let and const.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">differenceVar</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">var</span> a =<span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(a);  <span class="hljs-comment">// output 10</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
   <span class="hljs-keyword">var</span> a=<span class="hljs-number">20</span>;
   <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// output 20 //overriding an existing value</span>
  }
  <span class="hljs-built_in">console</span>.log(a);  <span class="hljs-comment">// output 20</span>
}

<span class="hljs-comment">//The let statement declares a local variable in a block scope.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">differenceLet</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">let</span> a =<span class="hljs-number">10</span>;
  <span class="hljs-built_in">console</span>.log(a);  <span class="hljs-comment">// output 10</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
   <span class="hljs-keyword">let</span> a=<span class="hljs-number">20</span>;
   <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// output 20</span>
  }
  <span class="hljs-built_in">console</span>.log(a);  <span class="hljs-comment">// output 10</span>
}
</code></pre><p>In case of <code>const</code> the value can be assigned to a variable only once and they can't be changed.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">differenceConst</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">const</span> MY_VARIABLE = <span class="hljs-number">10</span>; <span class="hljs-comment">//declaration and initialization are to be done at the same time</span>
  <span class="hljs-built_in">console</span>.log(MY_VARIABLE);  <span class="hljs-comment">// output 10 </span>
}
</code></pre><p>Variables declared with let and const remain uninitialized at the beginning of execution whilst variables declared with var are initialized with a value of undefined.</p>
<h2 id="what-is-the-difference-between-undefined-and-not-defined-or-reference-error">What is the difference between <code>undefined</code> and <code>not defined</code> or <code>Reference Error</code>?</h2>
<p>In JavaScript, an undeclared variable is assigned the value <code>undefined</code> at execution and is also of type undefined.</p>
<pre><code><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> a); <span class="hljs-regexp">//</span> <span class="hljs-literal">undefined</span>
</code></pre><p>A ReferenceError is thrown when we try to access a previously undeclared variable.</p>
<pre><code>console.log(a); // ReferenceError: variable <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
</code></pre><h2 id="what-do-you-mean-by-hoisting">What do you mean by hoisting?</h2>
<p>Functions and variables that are declared anywhere in the code are moved to the top of the scope due to hoisting.</p>
<p><strong>Note:</strong> Only declarations are moved, assignments are left in place.</p>
<p>We should make a habit to declare and initialize JavaScript variables before use. Using strict mode in JavaScript ES5 can help expose undeclared variables.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> a; <span class="hljs-comment">// a is hoisted at the top of foo()</span>
    <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// undefined</span>
    a=<span class="hljs-number">2</span>;
}
foo();
</code></pre><pre><code>foo(); <span class="hljs-comment">// not Reference Error but TypeError</span>
<span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>) </span>{
....
}
</code></pre><p>Here foo() is attempting to invoke the undefined value, which is <code>TypeError</code>. Function declarations are hoisted but function expressions are not.</p>
<h2 id="what-do-you-mean-by-closure">What do you mean by closure?</h2>
<p>Closure happens when a function is able to access a variable defined in its enclosing (outer) scope.</p>
<p>The closure has access to variables in three scopes:</p>
<ul>
<li>Variables declared in their own scope</li>
<li>Variables declared in a parent function scope</li>
<li>Variables declared in the global namespace</li>
</ul>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">adder</span>(<span class="hljs-params">num</span>) </span>{ 
    <span class="hljs-keyword">var</span> amount = <span class="hljs-number">5</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> amount + num;
    }
}

<span class="hljs-keyword">var</span> sum = adder (<span class="hljs-number">3</span>);
<span class="hljs-keyword">var</span> output = sum();
<span class="hljs-built_in">console</span>.log(output); <span class="hljs-comment">//8</span>
</code></pre><h2 id="what-is-the-difference-between-call-and-apply">What is the difference between .call() and .apply()?</h2>
<p>Both <code>call</code> and <code>apply</code> help execute functions. The difference is that <code>call()</code> accepts an argument list, while <code>apply()</code> accepts a single array of arguments.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Product</span>(<span class="hljs-params">name, price</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.price = price;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Food</span>(<span class="hljs-params">name, price</span>) </span>{
  Product.call(<span class="hljs-built_in">this</span>, name, price);
  <span class="hljs-built_in">this</span>.category = <span class="hljs-string">'food'</span>;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> Food(<span class="hljs-string">'cheese'</span>, <span class="hljs-number">5</span>).name);
<span class="hljs-comment">// expected output: "cheese"</span>
</code></pre><pre><code><span class="hljs-keyword">var</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>];

<span class="hljs-keyword">var</span> <span class="hljs-built_in">max</span> = <span class="hljs-type">Math</span>.<span class="hljs-built_in">max</span>.apply(null, numbers);

console.log(<span class="hljs-built_in">max</span>);
<span class="hljs-comment">// expected output: 7</span>

<span class="hljs-keyword">var</span> <span class="hljs-built_in">min</span> = <span class="hljs-type">Math</span>.<span class="hljs-built_in">min</span>.apply(null, numbers);

console.log(<span class="hljs-built_in">min</span>);
<span class="hljs-comment">// expected output: 2</span>
</code></pre><h2 id="what-is-undefined-x-1-in-javascript">What is <code>undefined x 1</code> in JavaScript?</h2>
<p><code>undefined × 1</code> is just way of displaying an array's uninitialized index in Chrome's developer console.</p>
<pre><code><span class="hljs-keyword">var</span> fruits = [<span class="hljs-string">"Strawberry"</span>, <span class="hljs-string">"Banana"</span>, <span class="hljs-string">"Mango"</span>, <span class="hljs-string">"Kiwi"</span>, <span class="hljs-string">"Orange"</span>]
<span class="hljs-built_in">delete</span> fruits[<span class="hljs-number">3</span>];
</code></pre><p>Output of fruits will be: <code>["Strawberry", "Banana", "Mango", undefined × 1, "Orange"]</code></p>
<h2 id="how-do-you-add-an-element-to-the-beginning-of-an-array-how-do-you-add-one-at-the-end">How do you add an element to the beginning of an array? How do you add one at the end?</h2>
<pre><code>var myArray = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>];
myArray.push(<span class="hljs-string">'end'</span>);
myArray.unshift(<span class="hljs-string">'start'</span>);
console.log(myArray); // ["start", "a", "b", "c", "d", "end"]
</code></pre><p>In ES6, we can use spread operator</p>
<pre><code><span class="hljs-attr">myArray</span> = [<span class="hljs-string">'start'</span>, ...myArray, <span class="hljs-string">'end'</span>]<span class="hljs-comment">;</span>
</code></pre><h2 id="what-are-self-executing-functions-or-iife">What are self-executing functions or IIFE?</h2>
<p>IIFE (Immediately Invoked Function Expressions) functions are executed right after its definition. It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the <code>Grouping Operator ()</code>. This prevents accessing variables within the IIFE idiom as well as polluting the global scope.</p>
<p>The second part creates the immediately executing function expression <code>()</code> through which the JavaScript engine will directly interpret the function.</p>
<p>Example:</p>
<pre><code>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'In IIFE'</span>);
})();
</code></pre><p><strong>Note</strong> : The function becomes a function expression which is immediately executed. The variable within the expression cannot be accessed from outside it.</p>
<hr />
<p>I hope this helps people who are preparing for JavaScript and Node.js interviews. If I have left any basic questions, feel free to comment. I am considering making a part two if this gets traction. :)</p>
]]></content:encoded></item><item><title><![CDATA[7 different ways to make AJAX calls in JavaScript in 2019]]></title><description><![CDATA[Happy New Year 2019! I know I am a bit late but better late than never! 😃
My new year resolution is to write something every day, even if it's something basic. Out of curiosity, I have been revisiting various ways to make API calls in JS in 2019. In...]]></description><link>https://blog.ipseeta.dev/7-different-ways-to-make-ajax-calls-in-javascript-in-2019</link><guid isPermaLink="true">https://blog.ipseeta.dev/7-different-ways-to-make-ajax-calls-in-javascript-in-2019</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Ajax]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Tue, 22 Jan 2019 11:58:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1548164868948/BypbkoN7V.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Happy New Year 2019! I know I am a bit late but better late than never! 😃</p>
<p>My new year resolution is to write something every day, even if it's something basic. Out of curiosity, I have been revisiting various ways to make API calls in JS in 2019. In this post, I'll summarize my findings and list various options to make AJAX calls. To keep it simple, let's focus on what they are, their syntaxes and some pros and cons of each option. </p>
<h2 id="xhr">XHR</h2>
<blockquote>
<p>Ajax is the traditional way to make an asynchronous HTTP request.
The XMLHttpRequest object can be used to exchange data with a web server.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<h4 id="get-request">GET Request</h4>
<pre><code><span class="hljs-keyword">const</span> Http = <span class="hljs-keyword">new</span> XMLHttpRequest();
<span class="hljs-keyword">const</span> url=<span class="hljs-string">'http://example.com/'</span>;
Http.open(<span class="hljs-string">"GET"</span>, url);
Http.send();
Http.onreadystatechange=<span class="hljs-function">(<span class="hljs-params">e</span>)=&gt;</span>{
<span class="hljs-built_in">console</span>.log(Http.responseText)
}
</code></pre><h4 id="post-request">POST Request</h4>
<pre><code><span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.open(<span class="hljs-string">"POST"</span>, <span class="hljs-string">'/user'</span>, <span class="hljs-literal">true</span>);
xhr.setRequestHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/x-www-form-urlencoded"</span>);

xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.readyState === XMLHttpRequest.DONE &amp;&amp; <span class="hljs-built_in">this</span>.status === <span class="hljs-number">200</span>) {
        <span class="hljs-comment">// Request finished. Do processing here.</span>
    }
}
xhr.send(<span class="hljs-string">"name=Ipseeta&amp;id=1"</span>);
</code></pre><h2 id="fetch-api">Fetch API</h2>
<blockquote>
<p>The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<p>The <code>fetch</code> method takes a mandatory request path as argument and returns a <code>Promise</code>.</p>
<h4 id="get-request">GET Request</h4>
<pre><code>fetch(<span class="hljs-string">'https://www.example.com'</span>, {
        <span class="hljs-attr">method</span>: <span class="hljs-string">'get'</span>
    })
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">jsonData</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(jsonData))
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
            <span class="hljs-comment">//error block</span>
        }
</code></pre><h4 id="post-request">POST Request</h4>
<pre><code><span class="hljs-keyword">var</span> url = <span class="hljs-string">'https://example.com/profile'</span>;
<span class="hljs-keyword">var</span> data = {<span class="hljs-attr">username</span>: <span class="hljs-string">'example'</span>};

fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>, <span class="hljs-comment">// or 'PUT'</span>
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data), <span class="hljs-comment">// data can be `string` or {object}!</span>
  <span class="hljs-attr">headers</span>:{
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  }
}).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json())
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Success:'</span>, <span class="hljs-built_in">JSON</span>.stringify(response)))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre><h3 id="pros">Pros</h3>
<ol>
<li>It’s flexible and easy to use</li>
<li>Callback hell is avoided by Promises</li>
<li>Supported by all modern browsers</li>
<li>Follows request-response approach</li>
</ol>
<h3 id="cons">Cons</h3>
<ol>
<li>Doesn't send cookie by default</li>
<li>CORS is disabled by default</li>
</ol>
<h2 id="jquery">jQuery</h2>
<blockquote>
<p>jQuery is a fast, small, and feature-rich JavaScript library.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<p>You’ll need to include the jQuery library in your project to get started.</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre><h4 id="get-request">GET Request</h4>
<pre><code>$.ajax({
    <span class="hljs-attr">url</span>: <span class="hljs-string">'/users'</span>,
    <span class="hljs-attr">type</span>: <span class="hljs-string">"GET"</span>,
    <span class="hljs-attr">dataType</span>: <span class="hljs-string">"json"</span>,
    <span class="hljs-attr">success</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
        <span class="hljs-built_in">console</span>.log(data);
    },
    <span class="hljs-attr">error</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error <span class="hljs-subst">${error}</span>`</span>);
    }
});
</code></pre><h4 id="post-request">POST Request</h4>
<pre><code>$.ajax({
    <span class="hljs-attr">url</span>: <span class="hljs-string">'/users'</span>,
    <span class="hljs-attr">type</span>: <span class="hljs-string">"POST"</span>,
    <span class="hljs-attr">data</span>: {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Ipseeta"</span>,
        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>
    },
    <span class="hljs-attr">dataType</span>: <span class="hljs-string">"json"</span>,
    <span class="hljs-attr">success</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
        <span class="hljs-built_in">console</span>.log(data);
    },
    <span class="hljs-attr">error</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error <span class="hljs-subst">${error}</span>`</span>);
    }
});
</code></pre><h3 id="pros">Pros</h3>
<p>The good thing about jQuery is that you will find tons of support and documentation.</p>
<h3 id="cons">Cons</h3>
<p>If you are already using a state management library like React, Vue etc, then using jQuery just for ajax is overkill.</p>
<h2 id="axios">Axios</h2>
<blockquote>
<p>Promise based HTTP client for the browser and node.js
It lets you make HTTP requests from both the browser and the server.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<p>You can install through <code>npm install axios</code> and import <code>import axios from 'axios'</code> or add through cdn </p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/axios/dist/axios.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre><h4 id="get-request">GET Request</h4>
<pre><code>axios.get(<span class="hljs-string">'/user'</span>, {
    <span class="hljs-attr">params</span>: {
      <span class="hljs-attr">ID</span>: <span class="hljs-number">1</span>
    }
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
    <span class="hljs-built_in">console</span>.log(response);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
    <span class="hljs-built_in">console</span>.log(error);
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// always executed</span>
  });
</code></pre><h4 id="post-request">POST Request</h4>
<pre><code>axios.post(<span class="hljs-string">'/user'</span>, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Ipseeta'</span>,
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
    <span class="hljs-built_in">console</span>.log(response);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
    <span class="hljs-built_in">console</span>.log(error);
  });
</code></pre><h3 id="pros">Pros</h3>
<ol>
<li>It works on both Nodejs and Browser</li>
<li>Supports Promise API</li>
<li>Can set or cancel a request</li>
<li>Can set a response timeout</li>
<li>Client-side support for protecting against XSRF</li>
<li>Can intercept requests or responses before they are carried out.</li>
<li>Automatic transforms for JSON data</li>
</ol>
<h2 id="request">Request</h2>
<blockquote>
<p>Request is designed to be the simplest way possible to make HTTP calls. It supports HTTPS and follows redirects by default.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<pre><code><span class="hljs-keyword">var</span> request = <span class="hljs-built_in">require</span>(<span class="hljs-string">'request'</span>);
request(<span class="hljs-string">'http://www.google.com'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error, response, body</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error:'</span>, error);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'statusCode:'</span>, response &amp;&amp; response.statusCode); 
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'body:'</span>, body);
});
</code></pre><h3 id="pros">Pros</h3>
<p>API is easy to use</p>
<h3 id="cons">Cons</h3>
<p>It is not Promise-based. If you'd like <code>request</code> to return a Promise instead, you can use an alternative interface wrapper for <code>request</code>.</p>
<h2 id="superagent">SuperAgent</h2>
<blockquote>
<p>SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs.</p>
</blockquote>
<h3 id="syntax">Syntax</h3>
<p>SuperAgent has a request object that accepts methods such as GET, POST, PUT, DELETE, and HEAD and then calling .then() (or .end() or await) to send the request.</p>
<h4 id="get-request">GET Request</h4>
<p>The .query() method accepts objects, which when used with the GET method will form a query-string.</p>
<pre><code><span class="hljs-selector-tag">request</span>
   <span class="hljs-selector-class">.get</span>(<span class="hljs-string">'/user'</span>)
   <span class="hljs-selector-class">.query</span>({ <span class="hljs-attribute">id</span>: <span class="hljs-number">1</span> })
   <span class="hljs-selector-class">.then</span>(res =&gt; {

   });
</code></pre><h4 id="post-request">POST Request</h4>
<pre><code><span class="hljs-selector-tag">request</span><span class="hljs-selector-class">.post</span>(<span class="hljs-string">'/user'</span>)
    <span class="hljs-selector-class">.set</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>)
    <span class="hljs-selector-class">.send</span>(<span class="hljs-string">'{"name":"Ipseeta","id":1}'</span>)
    <span class="hljs-selector-class">.then</span>(callback)
    <span class="hljs-selector-class">.catch</span>(errorCallback)
</code></pre><h3 id="pros">Pros</h3>
<ol>
<li>Nice interface for making HTTP requests.</li>
<li>Works in both Browser and Node.</li>
<li>Multiple functions chaining to send requests.</li>
<li>Supports abortion of requests</li>
</ol>
<h2 id="qwest">Qwest</h2>
<blockquote>
<p>Qwest is a simple ajax library based on <code>promises</code> and that supports <code>XmlHttpRequest2</code> special data like ArrayBuffer, <code>Blob</code> and <code>FormData</code>.</p>
<h3 id="syntax"><strong>Syntax</strong></h3>
<p>You can use qwest using <code>npm install qwest</code> or via cdnjs <code>https://cdnjs.com/libraries/qwest</code></p>
</blockquote>
<h4 id="get-request">GET request</h4>
<pre><code><span class="hljs-selector-tag">qwest</span><span class="hljs-selector-class">.get</span>(<span class="hljs-string">'example.com'</span>)
     <span class="hljs-selector-class">.then</span>(function(xhr, response) {

     });
</code></pre><h4 id="post-request">POST request</h4>
<pre><code>qwest.post(<span class="hljs-string">'/user'</span>, {
        name: <span class="hljs-string">'Ipseeta'</span>,
        id: <span class="hljs-number">1</span>
     })
     .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">xhr, response</span>) </span>{
     })
     .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e, xhr, response</span>) </span>{
     });
</code></pre><h3 id="pros">Pros</h3>
<p>It supports request cancellation</p>
<pre><code><span class="hljs-keyword">var</span> request = qwest.get(<span class="hljs-string">'example.com'</span>)
                   .then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">xhr, response</span>) </span>{
                       <span class="hljs-comment">// Won't be called</span>
                   })
                   .<span class="hljs-keyword">catch</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">xhr, response</span>) </span>{
                       <span class="hljs-comment">// Won't be called either</span>
                   });

request.abort();
</code></pre><h3 id="cons">Cons</h3>
<p>XHR2 is not available on every browser. So if needed, you need to verify XHR version</p>
<pre><code><span class="hljs-selector-tag">if</span>(qwest.xhr2) {
    <span class="hljs-comment">// Actions for XHR2</span>
}
<span class="hljs-selector-tag">else</span> {
    <span class="hljs-comment">// Actions for XHR1</span>
}
</code></pre><p>So, we looked at the most popular JS libraries for AJAX calls in this post. Did I miss anything? Feel free to comment below! 🙌</p>
]]></content:encoded></item><item><title><![CDATA[Revisiting REST with Java (JAX-RS) using Jersey]]></title><description><![CDATA[RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a]]></description><link>https://blog.ipseeta.dev/revisiting-rest-with-java-jax-rs-using-jersey</link><guid isPermaLink="true">https://blog.ipseeta.dev/revisiting-rest-with-java-jax-rs-using-jersey</guid><category><![CDATA[Java]]></category><category><![CDATA[REST]]></category><category><![CDATA[restful]]></category><category><![CDATA[Kotlin]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Tue, 20 Jun 2017 15:55:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/58e3733b3b44892f8fa99997/48d26169-efea-442b-991e-7ed0224707d6.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p><strong>RESTful web services</strong> are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using <strong>Uniform Resource Identifiers (URIs)</strong>, typically links on the Web.</p>
</blockquote>
<p>In simple words, <strong>REST</strong> stands for Representational State Transfer and it’s an architecture style for creating network based applications. <strong>JAX-RS</strong> is the Java API specification and <strong>Jersey</strong> is its reference implementation.</p>
<p>Our goal is to create a RESTful service that can retrieve product and price details by ID. Our app (myRetail RESTful service) should be able to do the following:-</p>
<ul>
<li><p>Responds to an HTTP GET request at <code>/products/{id}</code> and delivers product data as JSON (where {id} will be a number.</p>
</li>
<li><p>Reads pricing information from a NoSQL data store and combines it with the product id and name from the HTTP request into a single response.</p>
</li>
<li><p>Accepts an HTTP PUT request at the same path (<code>/products/{id}</code> ), containing a JSON request body similar to the GET response, and updates the product’s price in the data store.</p>
</li>
<li><p>Delete a product price entry from db.</p>
</li>
</ul>
<p>Example response: {"id":13860428,"name":"The Big Lebowski (Blu-ray) (Widescreen)","current_price":{"value": 13.49,"currency_code":"USD"}}</p>
<p>Okay, lets start with this simple CRUD Restful apis.</p>
<p><strong>Step 1</strong>: We will create a <code>dynamic web project</code> in Eclipse.</p>
<p><strong>Step 2</strong>: Add <code>web.xml</code> through <code>Generate Deployment Descriptor Stub</code> in Java EE tools.</p>
<p><strong>Step 3</strong>: Convert it to a <code>Maven</code> Project.</p>
<p><strong>Step 4</strong>: In <code>pom.xml</code> add the following dependencies:-</p>
<pre><code class="language-xml">&lt;!-- https://mvnrepository.com/artifact/asm/asm --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;asm&lt;/groupId&gt;
    &lt;artifactId&gt;asm&lt;/artifactId&gt;
    &lt;version&gt;3.3.1&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
    &lt;artifactId&gt;jersey-bundle&lt;/artifactId&gt;
    &lt;version&gt;1.19&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;org.json&lt;/groupId&gt;
    &lt;artifactId&gt;json&lt;/artifactId&gt;
    &lt;version&gt;20160810&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-server --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
    &lt;artifactId&gt;jersey-server&lt;/artifactId&gt;
    &lt;version&gt;1.19.3&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
    &lt;artifactId&gt;jersey-core&lt;/artifactId&gt;
    &lt;version&gt;1.19.3&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;org.mongodb&lt;/groupId&gt;
    &lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
    &lt;version&gt;3.4.2&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-json --&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
    &lt;artifactId&gt;jersey-json&lt;/artifactId&gt;
    &lt;version&gt;1.19&lt;/version&gt;
 &lt;/dependency&gt;
</code></pre>
<p><strong>Step 5</strong>: Update <code>web.xml</code> with the following mapping:-</p>
<pre><code class="language-xml">&lt;servlet&gt;
    &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/myRetail/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</code></pre>
<p><strong>Step 6</strong>: Creating our POJO classes with <code>@XmlRootElement</code> to define the root element for an XML tree.</p>
<pre><code class="language-java">@XmlRootElement
public class Product{
    private int id;
    private String name;
    private Price current_price;
...
}
</code></pre>
<img src="https://res.cloudinary.com/hashnode/image/upload/w_800/v1497937740/tuihwjldloiitn6kcsbk.png" alt="" style="display:block;margin:0 auto" />

<p><strong>Step 7</strong>: We will create a class named <code>MyRetailService</code> with <code>/products</code> as its <code>@Path</code> as per the requirements. Read <a href="http://www.restapitutorial.com/lessons/restfulresourcenaming.html">this</a> for guidelines on resource URI naming conventions. This class will have all our api calls.</p>
<p>a) To create pricing information in Product, we will do a <code>POST</code> request consuming a json/xml of Price type.</p>
<pre><code class="language-plaintext">@POST @Path("/create")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createPriceData(Price price){
    String success = dao.createPriceData(price);
    return Response.status(201).entity(success).build(); 
}
</code></pre>
<p>b) To retrieve all the details of products in myRetail app, we will go for a <code>GET</code> call.</p>
<pre><code class="language-plaintext">@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response findAll() {
    List&lt;Product&gt; product = dao.createDummyProducts();
    GenericEntity&lt;List&lt;Product&gt;&gt; entity = new GenericEntity&lt;List&lt;Product&gt;&gt;(product) {};
    return Response.ok(entity).build(); 
}
</code></pre>
<p>This is the case when we need to return parameterized types from a JAXRS resource method in the <code>Response</code> . Due to type erasure, it requires special handling in Jersey runtime to determine the generic type that is required to select a suitable <code>MessageBodyWriter</code>. <code>GenericEntity</code> can be used to represent a response entity of a generic type.</p>
<img src="https://res.cloudinary.com/hashnode/image/upload/v1497951778/mlucwwh7kcw0zgssrkn7.png" alt="" style="display:block;margin:0 auto" />

<p>c) To update a price value, we will go for <code>PUT</code></p>
<pre><code class="language-plaintext">@PUT @Path("{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updatePrice(@PathParam("id") String id,Product product) {
    Product updatedProduct = dao.update(Integer.parseInt(id),product);
    return Response.status(200).entity(updatedProduct).build(); 
}
</code></pre>
<img src="https://res.cloudinary.com/hashnode/image/upload/v1497952252/wgufurwm7bnszn0oxaqh.png" alt="" style="display:block;margin:0 auto" />

<p>d) <code>Delete</code> a price entry from product.</p>
<pre><code class="language-plaintext">@DELETE @Path("{id}")
public Response delete(@PathParam("id") String id) {
    String response = dao.delete(Integer.parseInt(id));
    return Response.status(202).entity(response).build();
}
</code></pre>
<p>We have handled the exceptions by throwing <code>GenericException</code>. However, we still need to create a Handler object to convert this exception into an actual JSON response so we get a nice friendly error message, which is implemented through <code>GenericExceptionMapper</code>.</p>
<pre><code class="language-plaintext">@Provider
public class GenericExceptionMapper implements ExceptionMapper&lt;Throwable&gt;{
public Response toResponse(Throwable ex){
    if(ex instanceof ProductSearchException){
        return Response.status(Status.NOT_FOUND)
        .entity(new ErrorProps("404", ex.getMessage()))
        .build();
    }else{
        return Response.status(Status.INTERNAL_SERVER_ERROR)
        .entity(new ErrorProps("Some error code, 500 or somthing", ex.getMessage()))
        .build();
    }
  }
}
</code></pre>
<p><strong>Step 8</strong>: To test, we can use postman or <code>jersey.api.client</code></p>
<pre><code class="language-plaintext">private static final String webServiceURI = "http://localhost:8080/myRetail-0.0.1-SNAPSHOT/myRetail/products/";
public static void main(String[] args) {
    Client client = Client.create();
    WebResource webResource = client.resource(webServiceURI);
    createDummyPriceTest(webResource);
}
private static void createDummyPriceTest(WebResource webResource){
    Price price = new Price();
    price.set_id(16483589);
    price.setCurrency_code("USD");
    price.setValue(13.49);
    //or String input = "{\"currency_code\":\"USD\",\"_id\":\"16483589\",\"value\":\"13.49\"}";
    ClientResponse response = webResource.path("create").type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,price);
    if (response.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }
    String output = response.getEntity(String.class);
    System.out.println(output);
}
</code></pre>
<p><strong>Summary of JAX-RS Annotations used</strong></p>
<table>
<thead>
<tr>
<th>Annotations</th>
<th>Usage</th>
</tr>
</thead>
<tbody><tr>
<td>Path</td>
<td>It identifies the URI path</td>
</tr>
<tr>
<td>PathParam</td>
<td>Represents the parameter of the URI path.</td>
</tr>
<tr>
<td>GET</td>
<td>Specifies method responds to GET request.</td>
</tr>
<tr>
<td>POST</td>
<td>Specifies method responds to POST request.</td>
</tr>
<tr>
<td>PUT</td>
<td>Specifies method responds to PUT request.</td>
</tr>
<tr>
<td>DELETE</td>
<td>Specifies method responds to DELETE request.</td>
</tr>
<tr>
<td>Produces</td>
<td>Defines media type for the response such as XML, PLAIN, JSON etc. It defines the media type that the methods of a resource class or MessageBodyWriter can produce.</td>
</tr>
<tr>
<td>Consumes</td>
<td>It defines the media type that the methods of a resource class or MessageBodyReader can produce.</td>
</tr>
<tr>
<td>Provider</td>
<td>The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity and that can be built using Response.ResponseBuilder.</td>
</tr>
</tbody></table>
<p>This is a very simple example of a RESTful service that uses JAX-RS annotations. You can check the <a href="https://github.com/Ipseeta/target">repo</a> for the DAO layer implementation with the usage of <code>MongoClient</code>. Find the same <a href="https://github.com/Ipseeta/RESTful-JAXRS-Kotlin">repo</a> in Kotlin.</p>
]]></content:encoded></item><item><title><![CDATA[Anonymous functions in Java - Explained!]]></title><description><![CDATA[If you mean anonymous function (function literal, lambda abstraction) then you are using a Java 8 version. 
What is an anonymous function?
Anonymous function is a function definition that is not bound to an identifier. These are a form of nested func...]]></description><link>https://blog.ipseeta.dev/anonymous-functions-in-java-explained</link><guid isPermaLink="true">https://blog.ipseeta.dev/anonymous-functions-in-java-explained</guid><category><![CDATA[Java]]></category><dc:creator><![CDATA[Ipseeta Priyadarshini]]></dc:creator><pubDate>Wed, 19 Apr 2017 08:20:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1545135538519/HkshHw8eN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you mean <strong>anonymous function</strong> (<strong>function literal</strong>, <strong>lambda abstraction</strong>) then you are using a Java 8 version. </p>
<h2 id="what-is-an-anonymous-function">What is an anonymous function?</h2>
<p>Anonymous function is a function definition that is not bound to an identifier. These are a form of nested function, in allowing access to variables in the scope of the containing function (non-local functions). This means anonymous functions need to be implemented using closures. Simply, lambda is an anonymous function which can be passed around in a concise way.</p>
<p>A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (-&gt;) and a function body.</p>
<h2 id="return-type">Return Type</h2>
<ol>
<li>When there is a single statement, the return type of the anonymous function is the same as that of the body expression.</li>
<li>When there is more than one statement enclosed in curly brackets then the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.</li>
</ol>
<h2 id="examples">Examples</h2>
<ul>
<li><strong>Zero parameter </strong></li>
</ul>
<blockquote>
<p>() -&gt; System.out.println("No Params");</p>
</blockquote>
<ul>
<li><strong>One Parameter</strong></li>
</ul>
<blockquote>
<p>(param) -&gt; System.out.println("One parameter: " + param);</p>
</blockquote>
<p>or without parenthesis;</p>
<blockquote>
<p>param -&gt; param (Identity function example)</p>
</blockquote>
<ul>
<li><strong>Multiple parameters</strong></li>
</ul>
<blockquote>
<p>(param1, param2) -&gt; param1 + param2;</p>
</blockquote>
<ul>
<li><strong>Parameter Types</strong></li>
</ul>
<blockquote>
<p>(int i, String name) -&gt; System.out.println("id:" + i + " name:" + name);</p>
</blockquote>
<ul>
<li><strong>Code block</strong></li>
</ul>
<blockquote>
<p>(param1, param2) -&gt; { return param1 + param2; }</p>
</blockquote>
<ul>
<li><strong>Nested lambda expression</strong> :Two nested expressions with the first one as closure</li>
</ul>
<pre><code>(id, defaultPrice) -&gt; {
  Optional&lt;Product&gt; product = productList.stream().filter(p -&gt; p.getId() == id).findFirst();
  <span class="hljs-keyword">return</span> product.map(p -&gt; p.getPrice()).orElse(defaultPrice);
}
</code></pre><ul>
<li><strong>As objects</strong> : the lambda expression is assigned to variable, and finally it is invoked by invoking the interface method it implements</li>
</ul>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">MyComparator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">compare</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a1, <span class="hljs-keyword">int</span> a2)</span></span>;
}

MyComparator myComparator = (a1, a2) -&gt; <span class="hljs-keyword">return</span> a1 &gt; a2;
<span class="hljs-keyword">boolean</span> result = myComparator.compare(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>);
</code></pre><p>Simply we can relate,</p>
<pre><code><span class="hljs-selector-tag">Arrays</span><span class="hljs-selector-class">.sort</span>(personArray, new Comparator(&lt;Person&gt;(){
    <span class="hljs-variable">@Override</span>
    public int compare(Person p1, Person p2){
        return p1.getAge() - p2.getAge();
    }
});
</code></pre><p>becomes -&gt;</p>
<pre><code><span class="hljs-attribute">Arrays</span>.sort(personArray, (p<span class="hljs-number">1</span>,p<span class="hljs-number">2</span>) -&gt; p<span class="hljs-number">1</span>.getAge() - p<span class="hljs-number">2</span>.getAge());
</code></pre><h2 id="lambda-expressions-as-functional-interfaces">Lambda expressions as functional interfaces</h2>
<p>Interfaces that contain only one abstract method in addition to one or more default or static methods.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> {
    <span class="hljs-keyword">interface</span> <span class="hljs-title">IntegerMath</span> {
        <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">operation</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span>;

        <span class="hljs-function"><span class="hljs-keyword">default</span> IntegerMath <span class="hljs-title">swap</span>(<span class="hljs-params"></span>)</span> {
          <span class="hljs-keyword">return</span> (a, b) -&gt; operation(b, a);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">apply</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b, IntegerMath op</span>)</span> {
        <span class="hljs-keyword">return</span> op.operation(a, b);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(<span class="hljs-params">String... args</span>)</span> {
        IntegerMath addition = (a, b) -&gt; a + b;
        IntegerMath subtraction = (a, b) -&gt; a - b;
        System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"40 + 2 = "</span> + apply(<span class="hljs-number">40</span>, <span class="hljs-number">2</span>, addition));
        System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"20 - 10 = "</span> + apply(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, subtraction));
        System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"10 - 20 = "</span> + apply(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, subtraction.swap()));    
    }
</code></pre><p>Here <code>IntegerMath</code> is a functional interface with default method <code>swap</code>. Lambda expressions that implement <code>IntegerMath</code> are passed to the <code>apply()</code> method to be executed.</p>
]]></content:encoded></item></channel></rss>