【问题标题】:GraphQL Custom directive enforcing value restrictionsGraphQL 自定义指令强制执行值限制
【发布时间】:2022-01-13 19:52:54
【问题描述】:

我需要在 INPUT_FIELD_DEFINITION 上创建一个自定义指令,以检查提供的枚举值是否未更改为先前的“状态”(业务逻辑是状态必须变为 UNAPPROVED -> APPROVED -> CANCELED -> FULFILLED ) 但不能完全弄清楚如何在枚举类型的构造函数中映射值。

我的所有代码都可以在github获得

我正在将 nextJs 后端功能与 neo4j 数据库一起使用,该数据库为整个架构生成解析器。

// order Schema

export const order = gql`
  type Order {
    id: ID! @id
    state: OrderState!
    user: User! @relationship(type: "MADE", direction: IN)
    createdAt: DateTime! @timestamp(operations: [CREATE])
    products: [Product!] @relationship(type: "INCLUDE", direction: OUT)
  }

  enum OrderState {
    UNAPPROVED
    APPROVED
    CANCELLED
    FULFILLED
  }
`;

export const extendOrder = gql`
  extend input OrderCreateInput {
    state: OrderState!
  }
`;

我想创建 @checkState 指令来检查更新 state 是否有效

我使用了GraphQL Tools docs 的基本示例,但它使用的是字符串值。非常感谢任何帮助。

【问题讨论】:

    标签: neo4j graphql next.js


    【解决方案1】:

    我没有使用自定义指令,而是使用graphql-middleware lib 来创建仅在使用 updateOrders 突变时触发的中间件。

    Middleware
    
    import { ValidationError } from "apollo-server-micro";
    import { IMiddleware } from "graphql-middleware";
    import { Order } from "pages/api/graphql";
    
    export const checkStateMiddleware: IMiddleware = {
      Mutation: {
        updateOrders: async (resolve, parent, args, ctx, info) => {
          const { where, update } = args;
    
          const [existing] = await Order.find({
            ...where,
          });
    
          const states = ["UNAPPROVED", "APPROVED", "CANCELLED", "FULLFIELD"];
    
          const currentState = states.indexOf(existing.state);
          const toBeUpdatedState = states.indexOf(update.state);
    
          if (toBeUpdatedState < currentState) {
            throw new ValidationError("Can't update value with previous state.");
          }
    
          return resolve(parent, args);
        },
      },
    };
    

    然后我在 pages/api/graphql.ts 中应用它

    //...
    import { applyMiddleware } from "graphql-middleware";
    //...
    const schemaWithMiddleware = applyMiddleware(schema, checkStateMiddleware);
    
    const apolloServer = new ApolloServer({ schema: schemaWithMiddleware });
    //...
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 2014-03-08
      • 2018-01-20
      • 1970-01-01
      • 2020-06-07
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多