Skip to content

Instantly share code, notes, and snippets.

@Dhaiwat10
Created June 25, 2022 15:14
Show Gist options
  • Save Dhaiwat10/ec188011cbb6173fa3e7b22c094dfbcc to your computer and use it in GitHub Desktop.
Save Dhaiwat10/ec188011cbb6173fa3e7b22c094dfbcc to your computer and use it in GitHub Desktop.
import type { NextApiRequest, NextApiResponse } from 'next';
import Parser from 'rss-parser';
import { HashnodePost } from '../../utils/types';
import { RSS_FEED_URL } from '../../utils/utils';
import { prisma } from '../../lib/prisma';
import { Post } from '@prisma/client';
export default async function handler(
_req: NextApiRequest,
res: NextApiResponse
) {
const parser = new Parser();
const feed = await parser.parseURL(RSS_FEED_URL);
const posts = feed.items as HashnodePost[];
const addedPosts: Post[] = [];
for (const post of posts) {
// find if the post already exists in the db
const existingPost = await prisma.post.findFirst({
where: {
link: post.link,
},
});
if (existingPost) {
// if it does, skip it
continue;
} else {
// if it doesn't, create it
const addedPost = await prisma.post.create({
data: {
title: post.title,
link: post.link,
author: post.creator,
pubDate: '05-20-2022',
},
});
addedPosts.push(addedPost);
}
}
res.status(200).json({ count: addedPosts.length, posts: addedPosts });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment