使用PostGraphile过滤GraphQL

时间:2018-04-23 13:06:25

标签: graphql postgraphql postgraphile

我正试图围绕GraphQL,我使用PostGraphile轻松快速地映射我的PostgreSQL数据库并使用GraphQL公开它。但是,我在很长一段时间内都遇到过一些简单的SQL需要花费几分钟才能完成的事情 -

首先,我试图在定义的日期之后从我的数据库中获取所有记录,到目前为止无法执行此操作,并且最终得到所有记录,这些记录非常低效。

其次,我想得到所有记录,其中可以为空的字段不为空(意思是,只有当它有内容时,它才会显示在GraphQL结果中)

如果有人能说明如何做到这一点,或者指出一个很好的教程,以简单的方式解释如何编写自定义过滤功能,那将是很棒的。

2 个答案:

答案 0 :(得分:4)

PostGraphile有一个很小但不断增长的community plugins列表;根据您的需要,您可能需要 postgraphile-plugin-connection-filter ,这会为您期望的PostGraphile连接添加一些过滤器(小于,大于,在列表中,而不是在列表中,和/或/不,像,包含等)。您也可以实现自己的插件,或通过custom queries实现此目标。

答案 1 :(得分:1)

要扩展@Benjie的答案,请先安装插件:

yarn add postgraphile-plugin-connection-filter

然后您可以从控制台运行postgraphile:

postgraphile --append-plugins <plugin path> --connection <dbname>

例如在Linux上:

postgraphile --append-plugins `pwd`/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb

或在Windows上:

postgraphile --append-plugins /users/bburns/desktop/moveto/site/node_modules/postgraphile-plugin-connection-filter/index.js --connection mydb

然后,您可以使用http://localhost:5000/graphiql处的graphiql端点尝试新的过滤器。您可以运行

之类的查询
{
  allProperties(first: 5, filter: {
    appraisedValue: {lessThan: 100000}
  }) {
    nodes {
      propertyId
      appraisedValue
      acres
    }
  }
}

注意:https://www.graphile.org/postgraphile/extending/上的文档说,您只能提供npm软件包的名称,但这似乎不适用于Windows。