/ clis / google / suggest.js
suggest.js
 1  /**
 2   * Google Search Suggestions via public JSON API.
 3   * Uses suggestqueries.google.com with client=firefox for pure JSON (not JSONP).
 4   */
 5  import { cli, Strategy } from '@jackwener/opencli/registry';
 6  import { CliError } from '@jackwener/opencli/errors';
 7  cli({
 8      site: 'google',
 9      name: 'suggest',
10      description: 'Get Google search suggestions',
11      strategy: Strategy.PUBLIC,
12      browser: false,
13      args: [
14          { name: 'keyword', positional: true, required: true, help: 'Search query' },
15          { name: 'lang', default: 'zh-CN', help: 'Language code' },
16      ],
17      columns: ['suggestion'],
18      func: async (_page, args) => {
19          const keyword = encodeURIComponent(args.keyword);
20          const lang = encodeURIComponent(args.lang);
21          const url = `https://suggestqueries.google.com/complete/search?client=firefox&q=${keyword}&hl=${lang}`;
22          const resp = await fetch(url);
23          if (!resp.ok) {
24              throw new CliError('FETCH_ERROR', `HTTP ${resp.status}`, 'Check your network connection');
25          }
26          const data = await resp.json();
27          // Response format: ["query", ["suggestion1", "suggestion2", ...]]
28          const suggestions = Array.isArray(data) && Array.isArray(data[1]) ? data[1] : [];
29          if (!suggestions.length) {
30              throw new CliError('NOT_FOUND', 'No suggestions found', 'Try a different keyword');
31          }
32          return suggestions.map(s => ({ suggestion: s }));
33      },
34  });