Skip to content

Commit

Permalink
creating news api
Browse files Browse the repository at this point in the history
  • Loading branch information
josephsintum committed Aug 6, 2020
1 parent a786dd6 commit 3ee2383
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 5 deletions.
58 changes: 58 additions & 0 deletions pages/api/news/index.ts
Original file line number Diff line number Diff line change
@@ -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
7 changes: 2 additions & 5 deletions rest.http
Original file line number Diff line number Diff line change
@@ -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
GET http://localhost:3000/api/news

1 comment on commit 3ee2383

@vercel
Copy link

@vercel vercel bot commented on 3ee2383 Aug 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.