Last active
June 9, 2023 13:11
-
-
Save squashfold/90350049e7547c32f1fabb7585fd4e06 to your computer and use it in GitHub Desktop.
NextJS Fuzzy search API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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