I am a newcomer to working with express and currently dealing with thedogapi for backend development. I am facing difficulties in retrieving specific information (temperaments) from the API. The example data from the API is as follows:
},
"id": 1,
"name": "Affenpinscher",
"bred_for": "Small rodent hunting, lapdog",
"breed_group": "Toy",
"life_span": "10 - 12 years",
"temperament": "Stubborn, Curious, Playful, Adventurous, Active, Fun-loving",
"origin": "Germany, France",
"reference_image_id": "BJa4kxc4X",
"image": {
"id": "BJa4kxc4X",
"width": 1600,
"height": 1199,
"url": "https://cdn2.thedogapi.com/images/BJa4kxc4X.jpg"
}
I need help extracting only the temperaments from this data so that I can save them in my database. Despite trying different approaches, I haven't been successful so far. Here's an attempt I made:
const getTemp = await Temperament.findAll()
if (getTemp.length === 0){
const apiAxios = await axios.get(`https://api.thedogapi.com/v1/breeds?api_key=${API_KEY}`)
const infoToGet = await apiAxios.data?.map(el => {
console.log(el.temperament?.split(",").map(el => el.trim()).toString())
return {
temperament: [el.temperament]?.join().split(",").map(el => el.trim()).toString()
}
})
const dbSave = await
Temperament.bulkCreate(infoToGet)
}
The above code did not yield the desired results, even though it partially worked for extracting temperaments. I sought advice, but the suggested solution involving array methods also did not work. Here's the code snippet using array methods:
router.get("/temperaments", async (req, res) => {
const temperamentsApi = await axios.get(`https://api.thedogapi.com/v1/breeds?api_key=${API_KEY}`)
const temperaments = temperamentsApi.data.map( el => el.temperament)
const tempEach = temperaments.map(el => {
for (let i = 0; i < el.length; i++) return el[i]})
console.log(tempEach)
tempEach.forEach(el => {
Temperament.findOrCreate({
where: { temperament: el }
})
})
const allTemperaments = await Temperament.findAll()
res.send(allTemperaments)
})
I'm seeking guidance on how to make the last code snippet work specifically for the TEMPERAMENT part. Apologies for the lengthy explanation, I am new to this and truly stuck at this point :s