GraphQL: How to restrict fields server-side across queries?

后端 未结 1 2024
自闭症患者
自闭症患者 2021-02-15 04:39

Let\'s say I have a User type that contains the following fields:

type User {
  name: String
  username: String
  someOtherField1: String
  someOtherField2: Stri         


        
1条回答
  •  不知归路
    2021-02-15 05:35

    By default, GraphQL types are maybe types, which means you can return null to any field.

    Which means, inside the resolve function of your creditCardNumber field, you could check if the current user is the user being fetched, and if so, you return the number. Otherwise, you return null.

    To access "contexted" data such as the current user, GraphQL let you pass an object context when executing the graphql function:

    graphql(schema, query, rootValue, context) // <-- the last parameter
    

    And you will find this object in each field resolve function signature:

    ...
    resolve: (object, args, context) => {
      // Third argument is your object
    },
    ....
    

    So what you can do, is pass the current logged user in the context:

    graphql(schema, query, rootValue, { user: getCurrentLoggedUser() })
    

    And in your User type, inside the creditCardNumber field resolve function:

    creditCardNumber: {
      ...
      resolve: (user, args, context) => {
        if (user.id === context.user.id)
          return user.creditCardNumber;
    
        return null;
      },
      ...
    }
    

    If you are using graphql-express, the context is by default the request, and you can customize it.

    0 讨论(0)
提交回复
热议问题