How to implement a set of GraphQL...
How to implement a set of GraphQL...
To implement a set of GraphQL mutations in a single transaction, you need to ensure that all the mutations are executed as part of a single atomic operation. This means that either all the mutations succeed, or if any one of them fails, all the changes are rolled back. Here are several approaches to achieve this, based on different GraphQL implementations and frameworks:
Dgraph supports atomic mutations through the use of the @transaction
directive. This directive allows you to bundle multiple mutations into a single transaction. If any mutation within the transaction fails, the entire transaction is aborted and rolled back.
Example:
mutation @transaction(commit: true) {
addReview(input: [{comment: "reviewComment1"}]) {
review {
id
comment
}
}
addRegion(input: [{name: "regName1"}]) {
region {
id
name
}
}
}
In this example, both addReview
and addRegion
are part of a single transaction. If either mutation fails, the transaction is aborted, and all changes are rolled back[1].
Contember provides a transaction
mutation wrapper that allows you to execute multiple mutations in a single transaction. If any mutation fails, the entire transaction is rolled back.
Example:
mutation {
transaction {
post1: createPost(data: {
title: "Hello world"
tags: [{create: {name: "graphql"}}]
}) {
ok
}
post2: createPost(data: {
title: "Lorem ipsum"
tags: [{create: {name: "contember"}}]
}) {
ok
}
}
}
Here, post1
and post2
are executed within a single transaction. If any mutation fails, the transaction is rolled back[2].
Ent provides a Transactioner
handler that wraps all GraphQL mutations within a transaction. This ensures that either all mutations succeed or all are rolled back in case of an error.
Steps:
Transactioner
handler to your GraphQL server initialization.Example:
srv := handler.NewDefaultServer(todo.NewSchema(client))
srv.Use(entgql.Transactioner{TxOpener: client})
func (mutationResolver) CreateTodo(ctx context.Context, input ent.CreateTodoInput) (*ent.Todo, error) {
client := ent.FromContext(ctx)
return client.Todo.Create().SetInput(input).Save(ctx)
}
This setup ensures that all mutations within a request are executed in a single transaction[3].
Hasura executes multiple mutations in a single request sequentially within a single transaction. If any mutation fails, all previous mutations are rolled back.
Example:
mutation {
delete_articles(where: {author_id: {_eq: 1}}) {
affected_rows
}
update_author(where: {id: {_eq: 1}}, _set: {name: "New Name"}) {
affected_row...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào