-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
68 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import axios from "axios"; | ||
import dotenv from 'dotenv'; | ||
import { BlogModel } from "../models/blogModel"; | ||
|
||
|
||
dotenv.config(); | ||
interface articleDef { | ||
image: string; | ||
title: string; | ||
url: string; | ||
source: { name: string; }; | ||
description: string; | ||
publishedAt: String; | ||
} | ||
export const blogRelatedResolvers = { | ||
Query: { | ||
blogRelatedArticles: async (_: any,{ blogId }: { blogId: string }) => { | ||
try{ | ||
const blog = await BlogModel.findById(blogId); | ||
const tags = blog?.tags; | ||
|
||
if (!tags || tags.length === 0) { | ||
throw new Error('Blog tags are missing.'); | ||
} | ||
const keywords = tags[Math.floor(Math.random() * tags.length)]; | ||
const response = await axios.get('https://gnews.io/api/v4/search', { | ||
params: { | ||
q: keywords, | ||
token: process.env.Gnews_Api_Key, | ||
lang: 'en', | ||
},}); | ||
return response.data.articles.map((article:articleDef ) => ({ | ||
title: article.title, | ||
url: article.url, | ||
source: article.source.name, | ||
description: article.description, | ||
image: article.image, | ||
publishedAt: article.publishedAt | ||
})); | ||
} catch (error: any) { | ||
throw new Error("Failed to fetch related articles. Please try again later."); | ||
} | ||
}, | ||
}, | ||
}; | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { gql } from "apollo-server-express"; | ||
|
||
export const blogRelatedArticlesSchema = gql` | ||
type Article { | ||
title: String | ||
url: String | ||
source: String | ||
description: String | ||
image: String | ||
publishedAt: String | ||
} | ||
type Query { | ||
blogRelatedArticles(blogId: String!): [Article] | ||
} | ||
`; |