serpapi / google-search-results-nodejs

SerpApi client library for Node.js. Previously: Google Search Results Node.js.
https://serpapi.com
MIT License
78 stars 22 forks source link

Support Promise-based operations in addition to callbacks #4

Open ilyazub opened 3 years ago

ilyazub commented 3 years ago

Now only callbacks are supported for SerpApiSearch#json.

const { GoogleSearch } = require('google-search-results-nodejs')
const search = new GoogleSearch(process.env.API_KEY)

const params = {
  engine: 'google_maps',
  q: 'pizza',
  ll: '@40.7455096,-74.0083012,15.1z',
  type: 'search'
}

search.json(params, data => {
  console.log(data.local_results)
})

The workaround is to promisify functions, but out-of-the-box support would be great. Test with the workaround here.

const { GoogleSearch } = require('google-search-results-nodejs')
const search = new GoogleSearch(process.env.API_KEY)

function promisifiedGetJson(params) {
  return new Promise((resolve, reject) => {
    try {
      search.json(params, resolve)
    } catch (e) {
      reject(e)
    }
  })
}

const params = {
  engine: 'google_maps',
  q: 'pizza',
  ll: '@40.7455096,-74.0083012,15.1z',
  type: 'search'
}

async function main(params) {
  try {
    const data = await promisifiedGetJson(params)

    console.log('Local results\n')

    for (const localResult of data.local_results) {
      const { title, position, reviews } = localResult
      console.log(`Position: ${position}\nTitle: ${title}\nReviews: ${reviews}\n`)
    }
  } catch (error) {
    console.error('there was an error:', error)
  }
}

main(params)

PS. Node.js HTTPS module is used to send requests. got has a simpler API and the response stream is handled by the library.

https://github.com/serpapi/google-search-results-nodejs/blob/cbadec5122a4362774fce66e219adcc872d71ead/lib/SerpApiSearch.js#L72-L95

ilyazub commented 3 years ago

@jvmvik @hartator What do you think?

alanwilter commented 2 years ago

I don't know if it helps but here I have two ways of implementing an endpoint to be used with https://shields.io/endpoint. A big thanks to @ilyazub for helping me with that.

Certainly a promise api version would make the code there much more elegant and succinct.