DEV Community

Cover image for API and Database Playing Together
Jackson Reeves
Jackson Reeves

Posted on

API and Database Playing Together

I was in Promises Hell for about three days until I finally came up with this code. The problem: I needed to query my local database, then use the result from that query to make an API call, then render the results of both the database query and the API call on an EJS views page. This did not go as smoothly as I would have liked. The main hurdle was that my original code required making multiple API calls before moving on to the render stage, which landed me in Promises Hell. My solution was to parse some info from my database query to create a single string that I could feed into my API call, so I only needed to make one call instead of multiple (potentially hundreds) of calls each time. Then I was able to neatly package it all up and send it to my rated EJS views page. Oh, complicated routes, you certainly can be fun.

router.get('/rated', (req, res) => {
db.rating
.findAll({
where: { userId: res.locals.currentUser.id }
})
.then(responses => {
let books = []
for (let i = 0; i < responses.length; i++) {
books[i] = {
id: responses[i].bookId,
rating: responses[i].value
}
}
let ids = []
for (let i = 0; i < books.length; i++) {
ids[i] = books[i].id
}
axios
.get(url + `&ids=${ids.toString()}`)
.then(outputs => {
let materials = outputs.data.results
for (let i = 0; i < books.length; i++) {
for (let j = 0; j < materials.length; j++) {
if (books[i].id === materials[j].id) {
books[i].materials = materials[j]
}
}
}
res.render('books/rated', {
books
})
})
.catch(problem => res.send(problem))
})
.catch(error => res.send(error))
})

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs