我想使用graphql从Postgres将数据拉取到Gatsby中。我已经编写了node.js服务器,但我找不到在gatsby中使用它的方法。
(https://github.com/gstuczynski/graphql-postgres-test)
你有什么想法吗?
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
}
}
}
}
}
Gatsby现在支持任意GraphQL端点作为源,这将有助于:https://www.gatsbyjs.org/packages/gatsby-source-graphql/
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
},
},
]
}
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
}
}
}