NextJSアプリでのHashNode APIの使用


Hashnodeは、チュートリアル、開発者記事とニュースのために行く最初の場所のうちの1つです.そのAPIを使用することは、1つがこれまでにすることができる最もクールなことであるという疑いなしです.

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/

コードしましょう
この記事では、次のJSのウェブサイトでhashnodeからブログ記事を表示することによってあなたを連れて行きます.
そのためには、次のチェックを行う必要があります.
  • HashNodeアカウント
  • Nodejs
  • テキストエディタ(Visual Studioコード)
  • 私は、nextjsでデータを問い合わせるのを助けるために、Apollo graphQLを使います

    ハッシュノードAPI
    グラフィカルに使用するハッシュノードAPI.それはかなり高速でデータを取得することです.
    Hashnode API Playground

    データを取得するクエリについての詳細を知るには、ブラウザの右側にあるdocsドロワーにあります.

    あなたのブログポスト出版物を得るためのいくつかの質問をテストしましょう.
    {
      user(username: "chrisdevcode") {
        publication {
          posts(page: 0) {
            _id
            coverImage
            slug
            title
            brief
            dateAdded
            dateUpdated
          }
        }
      }
    }
    
    
    chrisdevcodeをHashNodeユーザー名に変更します.
    user(username: "hashnode_user_name")
    
    
    Publicationクエリオブジェクトでは、ページ番号を指定する必要があります.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
    
    
    アポロとグラフのインストール
    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


    インデックスファイルを開きます.
    export default function Home() {
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    

    Follow this commit
    データの取得
    私は、3番目のパーティーを使用して、HashNode APIからGraphSQLを使用してデータを取得します.
    nextjsは組み込みデータ取得メソッドを提供します.
    export async function getStaticProps(context) {
      return {
        props: {}, // will be passed to the page component as props
      }
    }
    
    

    現在のファイルで、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機能の中で、我々は最終的に我々の小道具をページに返すつもりです、この場合、我々はポストを返します、それで、我々の小道具はpages/index.jsです
    export async function getStaticProps(context) {
      return {
        props: {
          posts: []
        }, 
      }
    }
    
    
    我々は、我々のページへの支柱としてgetStaticPropsで通過します:
    export default function Home({ posts }) {
      return (
        <div>
          <h1>My Hashnode Articles</h1>
        </div>
      )
    }
    
    
    コンソールでpropをログ出力することで結果をテストできます.
    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: [],
        },
      }
    }
    
    
    Webコンソールを開くと、次のようになります.
    https://nextjs.org/docs/basic-features/data-fetching

    Follow along with commit
    グラフの取得とクエリ
    すべてが設定されているので、HashNode APIから快適にデータを取得できます.
    まず、アポロクライアントをインポートします.
    import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
    
    
    私たちは、アポロクライアントとInmemoryCacheをインポートしています.これは、GraphSQLのクエリを作成するために使用されるキャッシュとGQLからアポロの読み込みを最適化します.
    getStaticProps ()関数の先頭に、HashNode APIエンドポイントでアポロのインスタンスを作成します.
      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
                }
              }
            }
          }
        `,
      })
    
    
    次に、getstaticpro ()のプロップにデータを追加します.
    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.


    サーバがまだ動作しているので、Webコンソールに簡単に調べましょう.

    おい!端末もチェックしてください.

    完全なファイル更新
    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
    Webページへのデータの追加
    最後に
    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,
        },
      }
    }
    
    
    ページが表示されるはずです


    オールインワンショット!


    結論
    これは、以下のリンクから簡単に、デモとソースコードを表示します

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

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