#Correct way to use getQuery?

5 messages · Page 1 of 1 (latest)

winged gulch
#

I'm trying to process this url...
http://localhost:3000/api/search?term=stuff

I want to use getQuery to retrieve the search term. The below code works fine but it is massively clumsy. Is there a more elegant way to just get a string out of the query string and have it be type safe?

server/api/search.ts

export default defineEventHandler(async (event: H3Event) => {
  const queryParams = getQuery(event)
  let term: string = '';
  if(queryParams.term){
    if (Array.isArray( queryParams.term)) {
      term = queryParams.term[0];
    } else {
      term = queryParams.term.toString();
    }
  }
  //.... use the term variable to do stuff...


});
charred mountain
#

const {term} = getQuery(event)

#

getQuery<possibleTypeMaybe> not sure

#

i mean pass an interface or type which them what you expect to be have

#

but i think they work on something