Golang

Golang

2021-03-20
go

Model

簡単なモデル

package links

import (
    "graphqlgo/internal/users"
    "graphqlgo/internal/pkg/db/mysql"
    "log"
)

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

// DBにSave
func (link Link)Save() int64 {
    stmt, _:= database.Db.Prepare("INSERT INTO Links(Title, Address) VALUES(?, ?)")
    res, _:= stmt.Exec(link.Title, link.Address)
    id, _:= res.LastInsertId()
    return id
}

// DBから取得
func (link Link)Save() int64 {
    stmt, _:= database.Db.Prepare("INSERT INTO Links(Title, Address) VALUES(?, ?)")
    res, _:= stmt.Exec(link.Title, link.Address)
    id, _:= res.LastInsertId()
    return id
}

Ref. https://www.howtographql.com/graphql-go/4-database/

Variables

変数定義をvarで

func (r *queryResolver) Links(ctx context.Context) ([]*model.Link, error) {
    // dbLinks := links.GetAll()ともできるが、先頭でvarで定義
    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
}