将Gatsby与Postgres连接

4
3个回答

3
您需要做的是按照此链接实现一个源插件。
Gatsby仓库中有很多使用源API的示例。可以看看这些以获取灵感!基本上,您需要将Postgres数据库的内容转换为Gatsby可以理解的格式。Gatsby将此格式称为“节点”。
您可以实现一个插件来直接与您的数据库或与您的节点服务器公开的任何API(graphql、REST等)进行交互。

3

gatsby-source-pg 模块可以直接连接到您的数据库,并将表/视图/函数等内容添加到 Gatsby 的 GraphQL API 中。要使用它,请安装该模块:

yarn add gatsby-source-pg

然后在gatsby-config.js中将其添加到插件列表中:

module.exports = {
  plugins: [
    /* ... */
    {
      resolve: "gatsby-source-pg",
      options: {
        connectionString: "postgres://localhost/my_db",
      },
    },
  ],
};

连接字符串还可以包括用户名/密码、主机、端口和SSL,如果您需要连接到远程数据库;例如:postgres://pg_user:pg_pass@pg_host:5432/pg_db?ssl=1

您可以在组件中使用根postgres字段进行查询,例如:

{
  postgres {
    allPosts {
      nodes {
        id
        title
        authorId
        userByAuthorId {
          id
          username
        }
      }
    }
  }
}

1

Gatsby现在支持任意GraphQL端点作为源,这将有助于:https://www.gatsbyjs.org/packages/gatsby-source-graphql/


你也可以使用Hasura,在Postgres上提供即时的GraphQL API,并从Gatsby应用程序中查询。你可以在这里查看教程
第一步:根据现有的Postgres数据库部署Hasura:https://docs.hasura.io/1.0/graphql/manual/getting-started/using-existing-database.html 第二步:为gatsby安装gatsby-source-graphql插件:https://www.gatsbyjs.org/packages/gatsby-source-graphql/ 第三步:配置插件
{
  plugins: [
    {
      resolve: 'gatsby-source-graphql', // <- Configure plugin
      options: {
        typeName: 'HASURA',
        fieldName: 'hasura', // <- fieldName under which schema will be stitched
        createLink: () =>
          createHttpLink({
            uri: `https://my-graphql.herokuapp.com/v1alpha1/graphql`, // <- Configure connection GraphQL url
            headers: {},
            fetch,
          }),
        refetchInterval: 10, // Refresh every 10 seconds for new data
      },
    },
  ]
}

步骤4:在你的组件中进行GraphQL查询。
const Index = ({ data }) => (
  <div>
    <h1>My Authors </h1>
    <AuthorList authors={data.hasura.author} />
  </div>
)
export const query = graphql`
  query AuthorQuery {
    hasura {        # <- fieldName as configured in the gatsby-config
      author {      # Normal GraphQL query
        id
        name
      }
    }
  }

其他链接:

注意:我在 Hasura 工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接