Open24

go+graphql+next.jsのベストプラクティスを考える

edegpedegp

フロントとユーザー認証はあらかた出来たが,バックエンド構築をしたことがないので少しメモが必要そう

edegpedegp

まず,user情報をfirebaseで管理しているのだが,
自作のバックエンドでもuserの固有idを取得したい。
そうすると,mutationを作る必要があるのだが,その作り方がわからない

edegpedegp

ent+gqlgenで簡単に構築できるみたいで
フィールドの作り方までわかった。
https://blog.arthur1.dev/entry/2023/01/04/163643

go run -mod=mod entgo.io/ent/cmd/ent new User

でUserのスキーマを定義できるのだが

schema/user.go
....
type User struct {
	ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
	return return []ent.Field{
        field.Time("create_at").
            Default(time.Now),
        field.Time("create_at")
	}
}

// Edges of the User.
func (User) Edges() []ent.Edge {
	return nil
}

edgeっていうのが出てきて
graphql少し使ったことがあるけど,初見でわからないので少しまとめる

edegpedegp

多分relational な関係を示したfieldsをedgeとして定義するっぽい

edegpedegp

とりあえずusertableを作るだけだったら必要ないので一旦無視して
userの情報をバックエンドに保存できるようになったら考える

edegpedegp

goってjavascriptとかと違ってregulationが厳しいからクソコード書いてたらすぐ気づけるのいいね

edegpedegp

なかなかcompileが通らないので,linterを入れた
https://staticcheck.io/docs/configuration#configuration-files
現状このlinterが一強っぽい
vscodeで使うには
公式Extensionを入れて
https://marketplace.visualstudio.com/items?itemName=golang.Go
vscodeのcommand palleteで

goplsをインストール

vscode settingで
go.useLanguageServerをtrueに設定して

go install honnef.co/go/tools/cmd/staticcheck@latest

vscode.setting.jsonで

  "gopls": {
      // 下記はおすすめ設定なので調べてみて
    "analyses": {
      "inherit": true,
      "ST1003": true,
      "ST1016": true,
      "ST1020": true,
      "ST1021": true,
      "ST1022": true
    }
  }
edegpedegp

なんか謎のファイルがたくさん生成された。
どれをさわれば良いかわからん
user_updateとか
user_deleteとかあるからそれかな

edegpedegp
printf '// +build tools\npackage tools\nimport (_ "github.com/99designs/gqlgen"\n _ "github.com/99designs/gqlgen/graphql/introspection")' | gofmt > tools.go
go mod tidy
go run github.com/99designs/gqlgen init

を先にやったら

validation failed: packages.Load: -: build constraints exclude all Go files
validation failed: packages.Load: -: package fooder is not in GOROOT

みたいなerrorを回避できた

edegpedegp

mutationを追加

ent/schema/user.go
// Mutation of the User.
func (User) Annotations()  []schema.Annotation {
    return  []schema.Annotation{
        entgql.QueryField(),
        entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()),
    }
}

edegpedegp

めっちゃ基礎的だけどdata migrationってなに?

edegpedegp

あれかgraphql serverからbackendのdatabaseにデータを移行することをdata migrationって言ってるみたい。
graphql serverがあるっていうことを知らなかったので,わからなかった。

edegpedegp

mysql serverを立ててからそれに接続してdatamigrationする必要がありそう。
サーバーを何個か立てるのでdocker-composeを使うと便利そう(よくわかってないが)

edegpedegp


きたぜ!
わからなすぎて全然投稿していなかった

edegpedegp

問題が山積みすぎてやばい

  • firebase emulator authが使えない
  • フロントのmutationからmysqlのデータが更新できない
edegpedegp

firebase emulator authが使えない解決!!
credentialsの情報がないとプロジェクト名が取得できないのが問題っぽい

	if credentials == "" {
		config = &firebase.Config{ProjectID: projectID}
	}
	app, err := firebase.NewApp(ctx,config)
edegpedegp

次はmysqlに保存できない問題を解決する

edegpedegp

gcp認証まわり複雑だなAWSと同じ匂いがする