うさぎ小屋(仮)

📅  2021-11-20

gqlgen generateで新しくqueryとmutationを作成してみる


前回の続き

Userの作成と取得を実装します。

また、作成したTodoの取得でユーザー情報を取得、存在しないユーザーIDでタスクを作成しようとしたらエラーを返すようにします。

まずは `presentation/graphql/schema.graphqls` に以下を作成します。

type Query {
   todos: [Todo!]!
   users: [User!]! # <-これ
}

input NewUser { # <-これ
  name: String!
}

type Mutation {
   createTodo(input: NewTodo!): Todo!
   createUser(input: NewUser!): User! # <-これ
}

そしてその後、下記コマンドを実行します。

gqlgen generate

以下のファイルが更新されます。

app/presentation/graphql/generated/generated.go
app/presentation/graphql/model/models_gen.go

リゾルバの実装をしていきます。

app/presentation/graphql/resolver.go

type Resolver struct {
        todos []*model.Todo
+       users []*model.User
}

app/presentation/graphql/schema.resolvers.go

func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
+       var findUser *model.User
+       for _, user := range r.users {
+               if user.ID == input.UserID {
+                       findUser = user
+                       break
+               }
+       }
+
+       if findUser == nil {
+               return nil, fmt.Errorf("not found user_id: %s", input.UserID)
+       }
        todo := &model.Todo{
                Text: input.Text,
                ID:   fmt.Sprintf("T%d", rand.Int()),
-               User: &model.User{ID: input.UserID, Name: "user " + input.UserID},
+               User: findUser,
        }
        r.todos = append(r.todos, todo)
        return todo, nil
 }

+func (r *mutationResolver) CreateUser(ctx context.Context, input model.NewUser) (*model.User, error) {
+       user := &model.User{
+               ID:   fmt.Sprintf("T%d", rand.Int()),
+               Name: input.Name,
+       }
+       r.users = append(r.users, user)
+       return user, nil
+}
+
 func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {
        return r.todos, nil
 }

+func (r *queryResolver) Users(ctx context.Context) ([]*model.User, error) {
+       return r.users, nil
+}

実装完了です。

ユーザーの作成

image in the content

ユーザーの取得

image in the content

タスクの作成(成功)

image in the content

タスクの作成(ユーザーが見つからないエラー)

image in the content

タスクの取得

image in the content

↑タスクの取得時にユーザー名も取得できました。

今回はここまで、ユーザーができたので認証認可の実装も試していこうと思います。

ミドルウェア導入やserver.goの配置先など考えることが多ければ記事を分けます。