If you want the articles or vlogs you write on Hashnode to show on your personal site or portfolio through the API, then you need to follow the steps below.
First of all, you need to add the following HTML code to your site. You can edit it as per your requirement.
.html code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Jubair's Blog Articles</title> </head> <body> <div class="app"> <h1 class="app-heading">Jubair's Articles</h1> <div id="articles"></div> </div> <script type="text/javascript" src="app.js"></script> </body> </html>
Create a new file called app.js. Place it in the same folder as your .html file.
app.js code
async function gql(query, variables = {}) {
const data = await fetch('https://api.hashnode.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer XXXXXXXXXXXXXXXXX' // Your API Token
},
body: JSON.stringify({
query,
variables
})
});
return data.json();
}
const GET_USER_ARTICLES = `
query GetUserArticles($page: Int!) {
user(username: "jubair71") {
publication {
posts(page: $page) {
title
brief
slug
}
}
}
}
`;
// ... rest of the code ...
gql(GET_USER_ARTICLES, { page: 0 })
.then(result => {
const articles = result.data.user.publication.posts;
let container = document.getElementById('articles');
articles.forEach(article => {
let listItem = document.createElement('li');
listItem.className = "article";
let title = document.createElement('h4');
title.innerText = article.title;
title.style.fontSize = '18px';
let dateAdded = document.createElement('small');
dateAdded.innerText = new Date(article.dateAdded).toDateString(); // Formatting the date
let brief = document.createElement('p');
brief.innerText = article.brief;
brief.style.color = '#6d819a';
let link = document.createElement('a');
link.innerText = 'Read more...';
link.href = `https://blog.jubairmoaj.com/${article.slug}`;
link.style.color = 'blue';
listItem.appendChild(title);
listItem.appendChild(brief);
listItem.appendChild(link);
container.appendChild(listItem);
});
});
This code appears to fetch and display articles written by a user on Hashnode, a blogging platform. Here's a step-by-step explanation of the code:
The gql Function:
This is an async function (meaning it returns a Promise) named gql that accepts two parameters: query and variables.
It uses the Fetch API to make a POST request to the Hashnode API endpoint.
It specifies the headers to set the content type to JSON and provides an authorization token for authentication.
The request body is the stringified JSON of the query and the variables.
After fetching, it returns the parsed JSON response.
The GET_USER_ARTICLES Template String:
This is a GraphQL query string that fetches a user's articles.
It expects a variable $page (which indicates the page number) and fetches the title, brief, and slug of the posts of a specific user (in this case, "jubair71").
Fetching and Displaying Articles:
The gql function is invoked with the GET_USER_ARTICLES query and the variable { page: 0 } (indicating we want the first page of results).
Once the Promise resolves (i.e., the data is fetched successfully), the callback inside .then() executes.
The articles are extracted from the response object and iterated over using a forEach loop.
For each article:
An <li> element with a class of "article" is created.
A <h4> element for the title, a <small> element for the date (note: the code doesn't actually provide a dateAdded property in the GraphQL query, so this part would throw an error), a <p> element for the brief description, and an <a> link to the full article are created and appended to the <li> element.
The populated <li> element is appended to a container, which is presumably an <ul> or <ol> element with the id "articles" in the HTML document.
A couple of things to note:
The code seems to have a slight error. It's trying to format article.dateAdded into a readable string, but dateAdded is not fetched in the GraphQL query. Therefore, it would be undefined and throw an error when attempting to create a new Date object.
The 'Authorization' header value is hard-coded as 'Bearer XXXXXXXXXXXXXXXXX'. In a real-world scenario, you'd replace 'XXXXXXXXXXXXXXXXX' with your actual API token, and for security reasons, you wouldn't want to hard-code it in your client-side code.
The styling (e.g., brief.style.color = '#6d819a') could be better handled using CSS classes, rather than directly setting styles in JavaScript. This would help separate the styling logic from the functional logic and keep the code cleaner and more maintainable.
In this part of app.js you need to put your username.
const GET_USER_ARTICLES = ` query GetUserArticles($page: Int!) { user(username: "jubair71") // Enter your hashnode username in here
- A token must be generated from Developer Settings.
5. Place the token here.
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer XXXXXXXXXXXXXXXXX' // Your API Token },