Igor Shvets
Igor Shvets

Reputation: 547

How to solve the problem of finding item by id?

When I follow the route: '/gallery' I get all the items from the file './posts.json' and display them on screen. But when I turn the route: '/gallery/:id' I want to receive one item by its id.

But I get an error: const pictureId = this.formatePicture.findIndex(p => p.id == parseInt(id)); TypeError: this.formatePicture.findIndex is not a function. I tried to do for in by data, but after the cycle there are no object properties.

Tell me what I'm doing wrong and how to solve this problem so that I get the item by id when I go to the route '/gallery/:id'

app.js:

const express = require('express');
const Database = require('./db');

const app = express();
const port = 3000;
const db = new Database();

app.use(express.json());

app.get('/gallery', (req, res) => {
    if (req.query.id) {
        const picture = db.read(req.query.id);
        picture.then(data => {
            res.send(data);
        })
    } else {
        const pictures = db.read();
        pictures.then(data => {
            res.send(data);
        })
    }
});

app.get('/gallery/:id', (req, res) => {
    const picture = db.read(req.params.id);
    if (!picture) {
        res.status(404);
        res.send();
    } else {
        picture.then(data => {
            res.send(data);
        })
    }
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
});

db.js:

const fs = require('fs');
class Database {
constructor() {
     this.formatePicture = [];
}
    read (id) {
        return new Promise((resolve, reject) => {
            fs.readFile('./posts.json', 'utf-8', (err, data) => {
                if (err) {
                    reject(err)
                }else if(id) {
                    this.formatePicture = JSON.parse(data);
                    const pictureId = this.formatePicture.findIndex(p => p.id == parseInt(id));
                    resolve(pictureId)
                }
                else {
                    resolve(data)
                }
            })
        })
    }
}

module.exports = Database;

posts.json:

{
  "posts": [
    {
      "id": 1,
      "date": "2018-10-22T14:10:37.578Z",
      "title": "accusamus beatae ad facilis cum similique qui sunt",
      "url": "https://i.pinimg.com/originals/90/39/16/903916b9f0db6992f1a4b66ae3129fbe.jpg"
    },
    {
      "id": 2,
      "date": "2018-10-22T14:10:37.578Z",
      "title": "reprehenderit est deserunt velit ipsam",
      "url": "https://vignette.wikia.nocookie.net/okup/images/d/da/C683c20a5b0ae062b2325653f2fd3bdf.jpg/revision/latest?cb=20170131193210&path-prefix=da"
    }
      ]
}

Upvotes: 1

Views: 276

Answers (1)

axelduch
axelduch

Reputation: 10849

The data parsed is an object, the array you need to target is in the field posts

this.formatePicture.posts.findIndex(...)

Another way to achieve this without modifying your db code, would be to change the structure in posts.json so that it looks like this

[
    {
      "id": 1,
      "date": "2018-10-22T14:10:37.578Z",
      "title": "accusamus beatae ad facilis cum similique qui sunt",
      "url": "https://i.pinimg.com/originals/90/39/16/903916b9f0db6992f1a4b66ae3129fbe.jpg"
    },
    {
      "id": 2,
      "date": "2018-10-22T14:10:37.578Z",
      "title": "reprehenderit est deserunt velit ipsam",
      "url": "https://vignette.wikia.nocookie.net/okup/images/d/da/C683c20a5b0ae062b2325653f2fd3bdf.jpg/revision/latest?cb=20170131193210&path-prefix=da"
    }
]

As a side note:

You might want to use find instead of findIndex because pictureIdis an index with the initial code you shared

It could look like that

const picture = this.formatePicture.find(p => p.id == parseInt(id));

// checking if we found an entry first
if (picture) {
    resolve(picture.id);
} else {
    reject(/* some error about resource not being found */)
}

Upvotes: 1

Related Questions