Home > Net >  How to get an entire User by searching for his ID - NODE.JS
How to get an entire User by searching for his ID - NODE.JS

Time:12-15

I'm using a json file like this: { id: 1, username: janedoe, firstName: jane, ... } { id: 2, username: welele, firstName; Welele, ... }

I want a GET method that doing this route "/user/janedoe" (/user/username) returns to me this json: { id: 1, username: janedoe, firstName: jane, ... }

CodePudding user response:

At first parse, the JSON then use the JS array build-in method to find the result.

const data = JSON.parse(yourjsondata);
const result = data.find(user => user.username == 'janedoe');

CodePudding user response:

Supposing your user is inside an array named: data.

You could use find method:

You would have to do something like:

getUser(req, res) {
    const data = // import your file here if necessary
    const username = req.username;
    res.send({user: data.find(user => user.username === username})
}

CodePudding user response:

Let's say that you provided all required information, here is example how it works.

import { readFile } from 'fs/promises';
// Add try/catch if needed
let data = JSON.parse(await readFile("filename.json", "utf8"));

router.get('/users/:username', (req, res) => {
    const userName = req.params.username;
    if (data.length > 0) {
       const user = data.find(u => u.username === userName);
       if (typeof user === 'undefined') {
         res.status(404).send({
             error: "User not found"
         });
       } else {
          res.status(200).send(user);
       }
    }
});

You can choose any other option to read file. To find specific user by username you need to get username from request params. Than here us native js function how to get it from array By default if item was not found this return undefined (you can read more here) So you're returning 404 with not found message or 200 with user object.

  • Related