Câu hỏi phỏng vấn GraphQL
Câu hỏi

What is difference between Mutation and Query ?

Câu trả lời

The difference between a Mutation and a Query in GraphQL lies primarily in their purpose and execution behavior.

Purpose

  • Query: A Query is used to fetch data from the server. It is analogous to a GET request in REST APIs. Queries are read-only operations and do not modify the server's state. They are used when you need to retrieve specific data from the server without making any changes to it[2][4][7][14].

  • Mutation: A Mutation is used to modify data on the server. This includes creating, updating, or deleting data. Mutations are analogous to POST, PUT, PATCH, and DELETE requests in REST APIs. They are used when you need to change the state of the server or persist new data[1][2][5][6].

Syntax

  • Query: The syntax for a query typically starts with the query keyword, although this keyword is optional. Queries specify the fields to be fetched and can include arguments to filter or customize the data retrieval.

    graphql Copy
    query {
      user(id: "1") {
        name
        email
      }
    }

    This query fetches the name and email of a user with a specific id[4][7][14].

  • Mutation: The syntax for a mutation starts with the mutation keyword. Mutations specify the operation to be performed and the data to be modified. They often include arguments to specify the data to be changed.

    graphql Copy
    mutation {
      createUser(name: "John Doe", email: "john.doe@example.com") {
        id
        name
      }
    }

    This mutation creates a new user and returns the id and name of the newly created user[1][5][10].

Execution Behavior

  • Query: Queries can be executed in parallel. This means that multiple query fields can be resolved simultaneously, which can improve performance when fetching data[3][9].

  • Mutation: Mutations are executed serially, one after the other. This ensures that each mutation is completed before the next one begins, preventing race conditions and ensuring data consistency[3][9].

Return Data

  • Query: Queries return the data specified in the request. The structure of the response mirrors the structure of the query, ensuring that clients receive exactly what they asked for[4][7][14].

  • Mutation: Mutations also return data, typically the new or updated st...

junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Are there any disadvantages to GraphQL?

senior

How to implement a set of GraphQL mutations in single transaction?

junior

Where is GraphQL useful?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào