Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS without frameworks: findById

I’m beginner and trying to make a function findByID with NodeJS and JSON file as a database without frameworks, code:

const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
    const server = http.createServer((req, res) => {
        const urlparse = url.parse(req.url, true);
      if (urlparse.pathname == "/todos" && req.method == "GET") {
          const search = urlparse.search;
          if (search) { 
            const [, query] = urlparse.search.split("?");
            const data = querystring.parse(query);
            todos = todos.filter((todo) =>  todo.id === data.id);
            res.end(JSON.stringify(todos, null, 2));
          }
        }})

When I check with postman for the first time everything is fine.
1st request

When I check the second time in the response window there is an empty array.2nd request

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Each request used a different id.

>Solution :

I dont see todos defined so I assume it’s global, this line is then mutating it every request:

todos = todos.filter((todo) =>  todo.id === data.id);

Another thing is if id is unique you could use todos.find to just get the first match.

So instead use a new variable and find:

const todoMatch = todos.find((todo) =>  todo.id === data.id);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading