iT邦幫忙

0

Golang - GraphQL - Create and Retrieve Links

  • 分享至 

  • xImage
  •  

Introduction

上一篇已經利用了 Docker & third party package 初始化 Database
接下來就要改寫程式從 Database 讀寫資料

Sample Code

完成後的資料夾階層
https://ithelp.ithome.com.tw/upload/images/20230508/20118878fm8AoGreBl.png

CreateLinks

internal/users/users.go 新增程式碼

package users

type User struct {
	ID       string `json:"id"`
	Username string `json:"name"`
	Password string `json:"password"`
}

internal/links/links.go 新增程式碼,這段要注意 import 即可
這段主要是在使用 Database 插入資料後返回插入後的 ID

package links

import (
	mig "Go-GraphQL/internal/pkg/db/migrations/mysql"
	"Go-GraphQL/internal/users"
	"log"
)

// #1
type Link struct {
	ID      string
	Title   string
	Address string
	User    *users.User
}

// #2
func (link Link) Save() int64 {
	//#3
	stmt, err := mig.Db.Prepare("INSERT INTO Links(Title,Address) VALUES(?,?)")
	if err != nil {
		log.Fatal(err)
	}
	//#4
	res, err := stmt.Exec(link.Title, link.Address)
	if err != nil {
		log.Fatal(err)
	}
	//#5
	id, err := res.LastInsertId()
	if err != nil {
		log.Fatal("Error:", err.Error())
	}
	log.Print("Row inserted!")
	return id
}

schema.resolvers.go 改寫 CreateLink function

func (r *mutationResolver) CreateLink(ctx context.Context, input model.NewLink) (*model.Link, error) {
	var link links.Link
	link.Title = input.Title
	link.Address = input.Address
	linkID := link.Save()
	return &model.Link{ID: strconv.FormatInt(linkID, 10), Title:link.Title, Address:link.Address}, nil
}

$ go run server.go 執行後到 http://localhost:8080/ 輸入

mutation create{
  createLink(input: {title: "something", address: "somewhere"}){
    title,
    address,
    id,
  }
}

接著會得到結果

{
  "data": {
    "createLink": {
      "title": "something",
      "address": "somewhere",
      "id": "1"
    }
  }
}

links Query

前面已經完成 CreateLinks 了,接下來要實現查詢
internal/links/links.go 新增程式碼

func GetAll() []Link {
	stmt, err := database.Db.Prepare("select id, title, address from Links")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var links []Link
	for rows.Next() {
		var link Link
		err := rows.Scan(&link.ID, &link.Title, &link.Address)
		if err != nil{
			log.Fatal(err)
		}
		links = append(links, link)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return links
}

schema.resolvers.go 改寫 Links funciton

func (r *queryResolver) Links(ctx context.Context) ([]*model.Link, error) {
	var resultLinks []*model.Link
	var dbLinks []links.Link
	dbLinks = links.GetAll()
	for _, link := range dbLinks{
		resultLinks = append(resultLinks, &model.Link{ID:link.ID, Title:link.Title, Address:link.Address})
	}
	return resultLinks, nil
}

$ go run server.go 重新執行後到 http://localhost:8080/ 輸入

query {
  links {
    title
    address
    id
  }
}

得到結果

{
  "data": {
    "links": [
      {
        "title": "something",
        "address": "somewhere",
        "id": "1"
      }
    ]
  }
}

Reference


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言