NextJS 앱에서 Hashnode API 사용

Hashnode은 튜토리얼, 개발자 기사 및 뉴스를 볼 수 있는 첫 번째 장소 중 하나입니다. API를 사용하는 것이 가장 멋진 일이라는 것은 의심의 여지가 없습니다.

If you haven't created an account with Hashnode, don't hesitate to do so



데모 및 소스 코드



https://github.com/ChrisAchinga/hashnode-api

https://hashnode-api-self.vercel.app/

코딩하자



이 기사에서는 Next JS 웹 사이트에서 hashnode의 블로그 기사 표시를 안내합니다.

그렇게 하려면 다음을 확인해야 합니다.
  • 해시노드 계정
  • NodeJS
  • 텍스트 편집기(비주얼 스튜디오 코드)

  • NextJS에서 데이터 쿼리를 돕기 위해 Apollo graphQL을 사용할 것입니다.

    해시노드 API



    Hashnode API는 graphQL을 사용했습니다. 그것은 데이터를 얻는 데 예쁘고 빠릅니다.

    Hashnode API Playground



    데이터 가져오기 쿼리에 대해 자세히 알아보려면 브라우저 오른쪽의 문서 서랍에서 찾을 수 있습니다.



    블로그 게시물 발행물을 가져오기 위한 몇 가지 쿼리를 테스트해 보겠습니다.

    {
      user(username: "chrisdevcode") {
        publication {
          posts(page: 0) {
            _id
            coverImage
            slug
            title
            brief
            dateAdded
            dateUpdated
          }
        }
      }
    }
    
    

    chrisdevcode를 해시노드 사용자 이름으로 변경합니다.

    user(username: "hashnode_user_name")
    
    


    게시 쿼리 개체에서 페이지 번호를 지정해야 합니다. 0은 누군가 귀하의 블로그 홈을 방문할 때 가장 먼저 로드되는 페이지입니다. 즉, 가장 최근 기사가 표시되는 위치입니다.

     publication {
          posts(page: 0) {
           //
          }
        }
    
    


    플레이그라운드로 돌아가서 쿼리를 붙여넣고 실행합니다.

    {
      user(username: "chrisdevcode") {
        publication {
          posts(page: 0) {
            _id
            coverImage
            slug
            title
            brief
            dateAdded
            dateUpdated
          }
        }
      }
    }
    
    




    가져온 데이터:

    {
      "data": {
        "user": {
          "publication": {
            "posts": [
              {
                "_id": "60c313ef1e145957d5af691a",
                "coverImage": "https://cdn.hashnode.com/res/hashnode/image/upload/v1623247532659/tqLf2R120.png",
                "slug": "using-markdown-in-hashnode-beginners-guide",
                "title": "Using Markdown In Hashnode: Beginners Guide",
                "brief": "Hashnode is by far my best Developer blogging platform. One of the things making me love it is the use of markdown in writing and editing articles. \nIf you just created a Hashnode blog or thinking of creating one, then this is the best article for yo...",
                "dateAdded": "2021-06-11T07:42:39.715Z",
                "dateUpdated": null
              }
            ]
          }
        }
      }
    }
    
    


    이제 다음 웹사이트/앱에서 이 작업을 수행해 보겠습니다.

    다음 앱



    다음 앱 만들기:



    터미널/CMD를 열고 다음 앱을 만듭니다.

    npx create-next-app hashnode-api
    
    


    Apollo 및 GraphQL 설치

    npm install @apollo/client graphql
    
    


    애플리케이션 테스트:

    npm run dev
    
    


    브라우저를 열고 다음으로 이동하십시오. http://localhost:3000/



    We will only edit one file for the purpose of demonstration i.e index.js



    인덱스 파일pages/index.js을 열고 코드를 다음과 같이 정리합니다.

    export default function Home() {
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    


    Follow this commit

    데이터를 가져 오는 중



    graphQL을 사용하여 해시노드 API에서 데이터를 가져오기 위해 타사를 사용할 것입니다.

    NextJS는 내장된 데이터 가져오기 방법을 제공합니다. 저는 getStaticProps "

    export async function getStaticProps(context) {
      return {
        props: {}, // will be passed to the page component as props
      }
    }
    
    


    https://nextjs.org/docs/basic-features/data-fetching

    현재 파일에서 파일 맨 아래에 getStaticProps()를 추가합니다.

    export default function Home() {
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    export async function getStaticProps(context) {
      return {
        props: {}, // will be passed to the page component as props
      }
    }
    
    


    getStaticProps 함수 내에서 궁극적으로 페이지에 props를 반환할 것입니다. 이 경우 게시물을 반환하므로 props는 posts
    export async function getStaticProps(context) {
      return {
        props: {
          posts: []
        }, 
      }
    }
    
    


    페이지에 소품으로 posts를 전달합니다.

    export default function Home({ posts }) {
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    


    콘솔에 소품을 기록하여 결과를 테스트할 수 있습니다.

    console.log('POSTS', posts)
    
    


    지금 파일:

    export default function Home({ posts }) {
      console.log('POSTS', posts)
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    export async function getStaticProps(context) {
      return {
        props: {
          posts: [],
        },
      }
    }
    
    


    웹 콘솔을 열면 다음이 표시되어야 합니다.



    Follow along with commit

    GraphQL을 사용한 가져오기 및 쿼리



    이제 모든 것이 설정되었으므로 해시노드 API에서 편안하게 데이터를 가져올 수 있습니다.

    먼저 apollo 클라이언트를 가져옵니다.

    import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
    
    


    GraphQL 쿼리를 생성하는 데 사용할 캐시와 gql에서 apollo 읽기를 최적화하는 Apollo 클라이언트와 InMemoryCache를 가져오고 있습니다.

    getStaticProps() 함수의 상단에서 Hashnode API 엔드포인트를 사용하여 apollo의 인스턴스를 생성해 보겠습니다.

      const client = new ApolloClient({
        uri: 'https://api.hashnode.com/',
        cache: new InMemoryCache(),
      })
    
    


    getStaticProps() 함수는 이제 다음과 같아야 합니다.

    export async function getStaticProps(context) {
      const client = new ApolloClient({
        uri: 'https://api.hashnode.com/',
        cache: new InMemoryCache(),
      })
    
      return {
        props: {
          posts: [],
        },
      }
    }
    
    


    이제 쿼리를 만들어 보겠습니다. 쿼리 구문은 다음과 같습니다.

    const { data } = await client.query({
      query: gql`
        query GetPosts {
          // write query here
        }
      `,
    })
    
    


    API 플레이그라운드에서 다음 쿼리를 가져옵니다.

    const { data } = await client.query({
        query: gql`
          query GetPosts {
            user(username: "chrisdevcode") {
              publication {
                posts(page: 0) {
                  _id
                  coverImage
                  slug
                  title
                  brief
                }
              }
            }
          }
        `,
      })
    
    


    그런 다음 getStaticProp()의 prop에 데이터를 추가합니다.

    return {
        props: {
          posts: data.user.publication.posts,
        },
      }
    
    


    You can just pass in data, but I have the long tree in the array, so I just used data.user.publication.posts, either way, you'll get the same results.



    서버가 계속 실행 중인 상태에서 웹 콘솔을 빠르게 살펴보겠습니다.



    여기요! 터미널도 확인하십시오.



    업데이트된 전체 파일:

    import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
    
    export default function Home({ posts }) {
      console.log('POSTS', posts)
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    export async function getStaticProps(context) {
      const client = new ApolloClient({
        uri: 'https://api.hashnode.com/',
        cache: new InMemoryCache(),
      })
    
      const { data } = await client.query({
        query: gql`
          query GetPosts {
            user(username: "chrisdevcode") {
              publication {
                posts(page: 0) {
                  _id
                  coverImage
                  slug
                  title
                  brief
                }
              }
            }
          }
        `,
      })
    
      return {
        props: {
          posts: data.user.publication.posts,
        },
      }
    }
    
    


    Follow along with commit

    웹페이지에 데이터 추가:



    마지막 부분:

    API의 게시물을 표시하려면 데이터를 매핑하고 각 게시물을 표시하기만 하면 됩니다.

    {posts.map((post) => {
      return (
        // output here
      )
    })}
    
    


    데이터를 반복하고 모든 게시물에 대해 제목과 전체 게시물에 대한 링크를 표시합니다.

    {posts.map((post) => {
            return (
              <div key={post._id}>
                <h1>{post.title}</h1>
                <a href={`https://chrisdevcode.hashnode.dev/${post.slug}`}>Read</a>
              </div>
            )
    })}
    
    


    따라서 전체 파일:

    import { ApolloClient, InMemoryCache, gql } from '@apollo/client'
    
    export default function Home({ posts }) {
      console.log('POSTS', posts)
      return (
        <div>
          <h1>My Hashnode Articles</h1>
    
          {posts.map((post) => {
            return (
              <div key={post._id}>
                <h2>{post.title}</h2>
                <a href={`https://chrisdevcode.hashnode.dev/${post.slug}`}>Read</a>
              </div>
            )
          })}
        </div>
      )
    }
    
    export async function getStaticProps(context) {
      const client = new ApolloClient({
        uri: 'https://api.hashnode.com/',
        cache: new InMemoryCache(),
      })
    
      const { data } = await client.query({
        query: gql`
          query GetPosts {
            user(username: "chrisdevcode") {
              publication {
                posts(page: 0) {
                  _id
                  coverImage
                  slug
                  title
                  brief
                }
              }
            }
          }
        `,
      })
    
      return {
        props: {
          posts: data.user.publication.posts,
        },
      }
    }
    
    


    이제 게시물이 웹페이지에 표시됩니다.



    ONE-SHOT의 모든 것!





    결론



    아래 링크에서 데모 및 소스 코드를 보는 것처럼 간단합니다.

    https://github.com/ChrisAchinga/hashnode-api

    https://hashnode-api-self.vercel.app/

    Thanks to Colby Fayock who wrote an article on using graphQL on NextJS, and Catalin Pit on How on use hashnode API

    좋은 웹페이지 즐겨찾기