From 3ee2383ebf90e539789d0e5f6dfae7221e2c8803 Mon Sep 17 00:00:00 2001 From: josephsintum Date: Wed, 5 Aug 2020 18:11:54 -0700 Subject: [PATCH] creating news api --- pages/api/news/index.ts | 58 +++++++++++++++++++++++++++++++++++++++++ rest.http | 7 ++--- 2 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 pages/api/news/index.ts diff --git a/pages/api/news/index.ts b/pages/api/news/index.ts new file mode 100644 index 0000000..ab4fc7d --- /dev/null +++ b/pages/api/news/index.ts @@ -0,0 +1,58 @@ +import nextConnect from 'next-connect' +// @ts-ignore +import NewsAPI from 'newsapi' + +import middleware, { MiddlewareRequest } from '../../../middleware/middleware' +import { NewsModel } from '../../../models/news.model' +import { NextApiResponse } from 'next' +import wordCounter from '../../../utils/wordCounter' +import { NewsAPIResponse } from '../../../utils/newsAPITypes' + +const newsapi = new NewsAPI(process.env.API_KEY) + +const handler = nextConnect() +handler.use(middleware) + +handler + .get((req: MiddlewareRequest, res: NextApiResponse) => { + NewsModel.find() + .then((data) => { + res.json(data) + }) + .catch((err) => { + console.error(err) + res.status(500).json(err) + }) + }) + .post(async (req: MiddlewareRequest, res: NextApiResponse) => { + // fetching top headlines from newsAPI + // todo: handle error + await newsapi.v2 + .topHeadlines({ + language: 'en', + pageSize: 100, + }) + .then((newsData: NewsAPIResponse) => { + let newsStats = wordCounter(newsData.articles) + + // adding news data to the database + NewsModel.create({ + sources: 'all', + articles: newsData.articles, + stats: newsStats, + version: 1, + }) + .then((data) => { + res.json(data) + }) + .catch((err) => { + console.error(err) + res.status(500).json(err) + }) + }) + .catch((err: any) => { + console.error(err) + }) + }) + +export default handler diff --git a/rest.http b/rest.http index 717e1e6..cd2c6ce 100644 --- a/rest.http +++ b/rest.http @@ -1,9 +1,6 @@ ### -GET http://localhost:3000/api/news/topHeadlines - -### -POST http://localhost:3000/api/news/topHeadlines +POST http://localhost:3000/api/news Content-Type: application/json ### -GET http://localhost:3000/api/stats/topHeadlines \ No newline at end of file +GET http://localhost:3000/api/news \ No newline at end of file