Answer the question
In order to leave comments, you need to log in
How to correctly implement get by id?
When I go to the route: '/gallery' I get all the items from the ./posts.json file and display them on the screen. When I go to route : '/gallery/:id' I want to get one element 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 on data after the loop, there are no object properties, the iterator displayed letters from the contents of the posts.json file to the console
Tell me what I'm doing wrong and how to solve this problem
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}`)
});
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": [
{
"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"
}
]
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question