Skip to content

Instantly share code, notes, and snippets.

@squashfold
Last active June 9, 2023 13:01
Show Gist options
  • Save squashfold/ad3612c7907b8c05e2e735756829af06 to your computer and use it in GitHub Desktop.
Save squashfold/ad3612c7907b8c05e2e735756829af06 to your computer and use it in GitHub Desktop.
Search cached items in NextJS
import type { NextApiRequest, NextApiResponse } from 'next'
import type Post from '../../interfaces/post'
const posts = require('../../cache/data/posts').data
export default (req: NextApiRequest, res: NextApiResponse) => {
const query = req.query.query ? req.query.query.toString().toLowerCase() : ''
const results: Post[] = query.length ? posts.filter(post => {
const titleMatch = post.title.toLowerCase().includes(query);
const excerptMatch = post.excerpt.toLowerCase().includes(query);
return titleMatch || excerptMatch;
}) : posts;
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