I have built a simple Nuxt 3 app and have some custom api endpoints.
I am currently tracking the user query and response statuses to have some insight when something goes wrong and that the app is working as expected.
Running steps
- User will call the endpoint
api/searchwith query parameters - Endpoint will set up the process
- Call a third-party api from the server
- If the response is ok, the data will be transformed and returned.
- in case of error, an error message (and status code) will be returned to the user
- Tracking of the user's status code and search query.
Code (simplified)
// api/search.js
const URL = '...'
const buildDataset = items => items.map(...)
// STEP 1: client calls endpoint
export default defineEventHandler(async (event) => {
// STEP 2: setup
const param = useQuery(event)
const query = param.query
const URL = '...'
const res = {
items: [],
status: null,
msg: ''
}
// STEP 3: get data
try {
const response = await fetch(URL, {
headers: {
mode: 'cors',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
})
if (!response.ok) {
// will this be executed if anything goes wrong? is step 5 here?
res.status = response.status
res.msg = response.statusText
return res
}
// STEP 4: transform and return data
const results = await response.json()
res.status = response.status
res.items = buildDataset(results.collection)
return res
// STEP 5: handle error
} catch (err) {
// res.status = err.response.status // do I got a validate status code here?
res.msg = 'An error occurred'
return res
// STEP 6: track status code and user search query
} finally {
const data = { query, status: res.status }
fetch(SUPABASE_URL, {
method: 'POST',
headers: {
'apikey': SUPABASE_KEY,
'Authorization': 'Bearer ' + SUPABASE_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
}
})
Questions
- Am I mixing some concepts with my
!response.ok? I feel like the line don't get triggered if there is an error getting the data. - Will my data be returned to the client immediately when the data arrives, and will my
finallybe executed at the end? or will this block the return of the data? - Where can I set the
error statusin my code to notify the user and my tracking to get insight on what went wrong. - Is there anything else I'm missing?