Skip to content

Instantly share code, notes, and snippets.

@squashfold
Last active June 9, 2023 13:11
Show Gist options
  • Save squashfold/90350049e7547c32f1fabb7585fd4e06 to your computer and use it in GitHub Desktop.
Save squashfold/90350049e7547c32f1fabb7585fd4e06 to your computer and use it in GitHub Desktop.
NextJS Fuzzy search API
import type { NextApiRequest, NextApiResponse } from 'next'
import type Post from '../../interfaces/post'
import Fuse from 'fuse.js'
const posts = require('../../cache/data/posts').data
export default (req: NextApiRequest, res: NextApiResponse) => {
const fuse = new Fuse(posts, {keys: ['title', 'excerpt']}) // Specify which fields from the cache we should check for matches against
const query = req.query.query ? req.query.query.toString().toLowerCase() : '' // Convert the query to lower case so matches aren't case sensitive
const results: Post[] = query.length ? fuse.search(query) : posts // Find posts which match, or return all of them
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ results }))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment