Skip to content

bryanpinheiro/go-graphql-todoapi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Graphql on GO

gqlgen getting started

mkdir go-graphql-todoapi
cd go-graphql-todoapi
go mod init github.com/bryanpinheiro/go-graphql-todoapi
go get gorm.io/gorm
go get gorm.io/driver/sqlite

Setup gqlgen

  • create a tools.go file

    //go:build tools
    // +build tools
    
    package tools
    
    import (
      _ "github.com/99designs/gqlgen"
    )
  • add the dependency automatically:

    go mod tidy

Create gqlgen project structure

go run github.com/99designs/gqlgen init

Change schema.graphql and resolver.go

  • schema.graphqls:

    type Todo {
        id: Int!
        title: String!
        completed: Boolean!
    }
    
    type Query {
        todo(id: Int!): Todo
    }
    
    schema {
        query: Query
    }
  • resolver.go:

    package graph
    
    import (
      "context"
    
      "github.com/bryanpinheiro/go-graphql-todoapi/database"
      "github.com/bryanpinheiro/go-graphql-todoapi/models"
    )
    
    type Resolver struct{}
    
    func (r *Resolver) Todos(ctx context.Context) ([]*models.Todo, error) {
      // Access the DB instance from the database package
      db := database.DB
    
      var todos []*models.Todo
      if err := db.Find(&todos).Error; err != nil {
        return nil, err
      }
    
      return todos, nil
    }
  • fix some dependencies:

    go get github.com/99designs/gqlgen/graphql/handler

Generate auto code using gqlgen

go run github.com/99designs/gqlgen generate

Run project

go run server.go

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages