首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在nodeJS中使用Postgraphile,如何启用日期字段的聚合最大值?

在nodeJS中使用Postgraphile,如何启用日期字段的聚合最大值?
EN

Stack Overflow用户
提问于 2022-04-21 14:54:24
回答 1查看 211关注 0票数 0

基于Postgresql数据库,我在NodeJS中使用postgraphile作为graphql。我需要获取max(date_field),但是postgraphile在默认情况下不提供该选项。

如何在日期字段上启用max聚合?

我想要下面的东西。但是inspection_Date字段在max下不可用。

代码语言:javascript
复制
query Query {
  allRooms {
    aggregates {
      max {
        inspection_date
      }
    }
  }
}
EN

回答 1

Stack Overflow用户

发布于 2022-04-23 19:15:10

使用pg聚合自述的定义您自己的聚合部分中概述的方法的稍微修改的版本,您可以创建一个新的图形文件插件,该插件使用钩子来修改现有的"min“和"max”聚合规范,以使用包含时态类型和数值类型的不同isSuitableType函数:

代码语言:javascript
复制
import type { Plugin } from "graphile-build";
import type { AggregateSpec } from "@graphile/pg-aggregates/dist/interfaces";
import type { PgType } from "graphile-build-pg";

const addTemporalAggregatesPlugin: Plugin = (builder) => {
  builder.hook(
    "build",
    (build) => {
      const { pgAggregateSpecs } = build;

      const isNumberLikeOrTemporal = (pgType: PgType): boolean =>
        pgType.category === "N" || pgType.category === "D";

      // modify isSuitableType for max and min aggregates
      // to include temporal types see: https://www.postgresql.org/docs/current/catalog-pg-type.html
      const specs = (pgAggregateSpecs as AggregateSpec[] | undefined)?.map(
        (spec) => {
          if (spec.id === "min" || spec.id === "max") {
            return {
              ...spec,
              isSuitableType: isNumberLikeOrTemporal,
            };
          }
          return spec;
        }
      );

      if (!specs) {
        throw Error(
          "Please that the pg-aggregates plugin is present and that AddTemporalAggregatesPlugin is appended AFTER it!"
        );
      }

      const newBuild = build.extend(build, {});
      // add modified aggregate specs to the build
      newBuild.pgAggregateSpecs = specs;
      return newBuild;
    },
    ["AddTemporalAggregatesPlugin"],
    // ensure this hook fires before other hooks in the pg-aggregates plugin
    // that may depend on the "pgAggregatesSpecs" extension.
    ["AddGroupByAggregateEnumsPlugin"],
    []
  );
};

export default addTemporalAggregatesPlugin;

然后,只需在pg-聚合插件之后追加这个新插件:

代码语言:javascript
复制
postgraphile(pool, "my_schema", {
    pluginHook,
    appendPlugins: [
      PgAggregatesPlugin,
      AddTemporalAggregatesPlugin,
    ],
    // ...
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71956567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档