2.2.0 • Published 8 months ago

@rtd/use-suggestions v2.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

use-suggestions

A React hook for fetching search suggestions securely through a Next.js proxy. This package includes a custom hook, helper functions for creating proxy routes, types, and constants to simplify integration with your React/TypeScript projects.

Note: The createSuggestionsProxyHandler helper is now deprecated as of v2.2.0. Please use the new forwardProxyRequest utility for creating your proxy routes. In addition to the suggestions endpoint, you can now also target the retrieval endpoint (used, for example, to complete partial location data).

Installation

You can install the package using Yarn or npm:

yarn add @rtd/use-suggestions

or

npm install @rtd/use-suggestions

Setup

Create the Proxy Route in Next.js

To protect your API key, you must create a Next.js API route that acts as a proxy to the external API. Use the new forwardProxyRequest utility (import it from @rtd/use-suggestions/server for server-only code).

The utility accepts a configuration object of type ProxyHandlerConfig, which now includes an endpoint property. Use: • endpoint: 'suggest' – to forward requests to the suggestions endpoint • endpoint: 'retrieve' – to forward requests to the lookup/retrieve endpoint

For Next.js 12 (pages/api/suggestions.ts):

import type { NextApiRequest, NextApiResponse } from 'next'
import {
  forwardProxyRequest,
  ProxyHandlerConfig,
  GenericRequest,
} from '@rtd/use-suggestions/server'

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  // Use 'suggest' to forward to "/api/v1/suggestions"
  // or 'retrieve' to forward to "/api/v1/lookup/retrieve"
  endpoint: 'suggest',
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // Create a GenericRequest; req.url includes any query parameters.
  const genericRequest: GenericRequest = {
    originalUrl: req.url,
  }

  try {
    const { status, data } = await forwardProxyRequest(genericRequest, config)
    res.status(status).json(data)
  } catch (error: any) {
    console.error('Proxy error:', error)
    res.status(500).json({ error: error.message || 'Internal Server Error' })
  }
}

For Next.js 13 (app/api/suggestions/route.ts):

import { NextResponse } from 'next/server'
import {
  forwardProxyRequest,
  ProxyHandlerConfig,
  GenericRequest,
} from '@rtd/use-suggestions/server'

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  endpoint: 'suggest', // or 'retrieve' for the retrieval endpoint
}

export async function GET(request: Request) {
  // Create a URL object to extract the query string.
  const url = new URL(request.url)
  const genericRequest: GenericRequest = {
    originalUrl: url.search, // Only the query string (e.g., "?q=term&foo=bar")
  }

  try {
    const { status, data } = await forwardProxyRequest(genericRequest, config)
    return NextResponse.json(data, { status })
  } catch (error: any) {
    console.error('Proxy error:', error)
    return NextResponse.json(
      { error: error.message || 'Internal Server Error' },
      { status: 500 }
    )
  }
}

Usage

Using the Retrieve Endpoint

If you need to complete partial suggestion data (for example, when locations return with null coordinates), you can target the retrieve endpoint by setting the endpoint value in your configuration:

const config: ProxyHandlerConfig = {
  apiKey: process.env.API_KEY || '',
  baseUrl: 'https://api.suggestions.com/endpoint',
  endpoint: 'retrieve', // This will forward to "/api/v1/lookup/retrieve"
}

Usage in React

Importing the Hook

Import the useSuggestions hook, types, and constants in your React component:

import React, { useState } from 'react'
import useSuggestions, { SuggestionsOptions } from '@rtd/use-suggestions'

Example Component

Here’s an example of how to use the useSuggestions hook in a React component:

const SuggestionComponent: React.FC = () => {
  const [query, setQuery] = useState('')

  const options: SuggestionsOptions = {
    includeStops: true,
    includeConcerts: true,
    location: { lat: 39.7392, lng: -104.9903 },
    debounceTime: 400,
  }

  const { suggestions, isLoading, error } = useSuggestions(query, options)

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search for suggestions"
      />
      {isLoading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      <ul>
        {suggestions.map((suggestion) => (
          <li key={suggestion.slug}>{suggestion.name}</li>
        ))}
      </ul>
    </div>
  )
}

export default SuggestionComponent

Hook API

useSuggestions

Fetches search suggestions from the API.

Parameters:

  • rawQuery: string - The search query string.
  • options: SuggestionsOptions - Configuration options for the suggestions.
  • proxyPath?: string - (Optional) Relative path to the proxy route. Defaults to /api/suggestions.

Returns:

  • suggestions: SearchableSuggestion[] - An array of suggestions.
  • isLoading: boolean - Loading state.
  • error: Error | null - Error state.

Types

The package includes several types to help with type safety in your project:

SuggestionsOptions

Configuration options for the suggestions.

interface SuggestionsOptions {
  includeStops?: boolean
  includeRoutes?: boolean
  includeLocations?: boolean
  includeDestinations?: boolean
  includeConcerts?: boolean
  location?: {
    lat: number
    lng: number
  }
  debounceTime?: number
}

SearchableSuggestion

Base interface for a searchable suggestion.

/**
 * Suggestion Types Returned by the Server
 */
export type SuggestionType =
  | 'location'
  | 'concert'
  | 'stop'
  | 'station'
  | 'route'
  | 'destination'

/**
 * Point Coordinates
 */
export interface Point {
  lat: number
  lng: number
}

/**
 * Base Suggestion with Common Fields
 */
export interface BaseSuggestion extends Point {
  suggestionType: SuggestionType
  name: string
  label: string
  slug: string
  score: number
}

Constants

The package includes the following constants:

DEBOUNCE_TIME_IN_MS

Default debounce time for the search query.

export const DEBOUNCE_TIME_IN_MS = 432

Common Errors

1. Proxy Route Not Configured

If you attempt to use the hook without first creating a proxy route, you will see the following error:

Proxy route not found: "/api/suggestions".
Ensure the proxy route exists and is set up using the 'forwardProxyRequest' utility.

Solution: Follow the Setup section to create the API route.

2. Invalid Proxy Path

If a developer attempts to pass an external API URL instead of a relative path to the hook:

useSuggestions('query', options, 'https://api.suggestions.com');

The hook throws a validation error:

Invalid proxyPath: "https://api.suggestions.com".
The proxyPath must be a relative path starting with "/".

Solution: Use a relative path, such as /api/suggestions.

Building the Package

To build the package, run:

yarn build

This will compile the TypeScript files and output the results in the dist directory.

License

This project is licensed under the MIT License.

1.1.1

12 months ago

1.1.0

12 months ago

2.2.0-beta2

8 months ago

2.2.0-beta4

8 months ago

2.2.0-beta3

8 months ago

1.1.3

12 months ago

1.1.2

12 months ago

2.0.3

11 months ago

2.2.0

8 months ago

2.0.2

11 months ago

2.0.5

11 months ago

2.2.0-rc

8 months ago

2.0.4

11 months ago

2.2.0-beta

8 months ago

2.0.7

11 months ago

2.0.6

11 months ago

2.2.0-alpha1

9 months ago

2.2.0-alpha2

8 months ago

2.0.1

11 months ago

2.0.0

11 months ago

1.0.2

1 year ago

1.0.0

1 year ago