gqlgen初体验(三)

2021-05-12  本文已影响0人  戈壁堂

继续Building a GraphQL API in Go using gqlgen中的第五步

接口定义与实现

type ToDoItem struct {
    Id        string
    Text      string
    IsDone    bool
    CreatedOn time.Time
    UpdatedOn *time.Time
}

type ToDo interface {
    Initialise() error
    Create(text string, isDone bool) (*string, error)
    Update(id string, text string, isDone bool) error
    List() ([]ToDoItem, error)
}

type ToDoImpl struct {
    DbUserName string
    DbPassword string
    DbURL      string
    DbName     string
}

func (t *ToDoImpl) Initialise() error {...}

func (t *ToDoImpl) Create(text string, isDone bool) (*string, error) {...}

func (t *ToDoImpl) Update(id string, text string, isDone bool) error {...}

func (t *ToDoImpl) List() ([]todo.ToDoItem, error) {...}

graphql请求与响应

schema {
    query: MyQuery
    mutation: MyMutation
}

type MyQuery {
    todos: [Todo!]!
}

type MyMutation {
    createTodo(todo: TodoInput!): Todo!
}
// MyMutation returns generated.MyMutationResolver implementation.
func (r *Resolver) MyMutation() generated.MyMutationResolver { return &myMutationResolver{r} }

// MyQuery returns generated.MyQueryResolver implementation.
func (r *Resolver) MyQuery() generated.MyQueryResolver { return &myQueryResolver{r} }

type myMutationResolver struct{ *Resolver }
type myQueryResolver struct{ *Resolver }

func (r *myQueryResolver) Todo(ctx context.Context, id string) (*model.Todo, error) {...}
func (r *myMutationResolver) CreateTodo(ctx context.Context, todo model.TodoInput) (*model.Todo, error) {...}

在对应resolver具体的方法实现中调用上述“接口方法”。完成对请求的最终响应。

最终对graphql的请求处理,gqlgen会最终生成generated.go(具体名称有配置文件定义)作为运行时响应

上一篇 下一篇

猜你喜欢

热点阅读