Last active
June 9, 2023 13:01
-
-
Save squashfold/ad3612c7907b8c05e2e735756829af06 to your computer and use it in GitHub Desktop.
Search cached items in NextJS
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' | |
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