iTranslated by AI
Building a simple web application using Facebook's ent
Introduction
This article is a tutorial-style guide on how easily you can build an application using ent, an ORM developed by Facebook. It is a user-friendly library equipped with a full set of features for manipulating entities.
The characteristics of ent are as follows:
- Schema as Code: Models are treated as Go objects.
- Easy Graph Traversal: Easily run queries, aggregations, and traverse graph structures.
- Static Typing and Explicit API: Provides a clear API using code generation with 100% static typing.
- Multiple Storage Drivers: Supports MySQL, PostgreSQL, SQLite, and Gremlin.
- Extensibility: Easily extendable using Go templates.
In this article, I will try to create a simple one-line message board using ent.
Preparation
To use ent, you first need to install the CLI tool entc. Install it with the following steps:
$ go get github.com/facebook/ent/cmd/entc
Prepare an empty Go project directory in advance. Since we are making a one-line message board this time, I executed it as follows:
$ go mod init github.com/mattn/entgo-bbs
First, Initialization
First, create a schema. Since we will treat one line of the message board as an entity, let's create an Entry first.
$ entc init Entry
Several files will be generated as follows:
├── ent
│ ├── generate.go
│ └── schema
│ └── entry.go
├── go.mod
└── go.sum
ent/schema/entry.go is the generated schema (code). The content of the file looks like this:
package schema
import "github.com/facebook/ent"
// Entry holds the schema definition for the Entry entity.
type Entry struct {
ent.Schema
}
// Fields of the Entry.
func (Entry) Fields() []ent.Field {
return nil
}
// Edges of the Entry.
func (Entry) Edges() []ent.Edge {
return nil
}
Adding Fields
By default, the fields of Entry are empty. Let's add a content field to represent the message content and a created_at field for the creation date.
package schema
import (
"time"
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
)
// Entry holds the schema definition for the Entry entity.
type Entry struct {
ent.Schema
}
// Fields of the Entry.
func (Entry) Fields() []ent.Field {
return []ent.Field{
field.String("content").
Default(""),
field.Time("created_at").
Default(func() time.Time {
return time.Now()
}),
}
}
// Edges of the Entry.
func (Entry) Edges() []ent.Edge {
return nil
}
Model Generation
Once you have come this far, run go generate ./ent. The files will be generated as follows:
├── ent
│ ├── client.go
│ ├── config.go
│ ├── context.go
│ ├── ent.go
│ ├── entry
│ │ ├── entry.go
│ │ └── where.go
│ ├── entry.go
│ ├── entry_create.go
│ ├── entry_delete.go
│ ├── entry_query.go
│ ├── entry_update.go
│ ├── enttest
│ │ └── enttest.go
│ ├── generate.go
│ ├── hook
│ │ └── hook.go
│ ├── migrate
│ │ ├── migrate.go
│ │ └── schema.go
│ ├── mutation.go
│ ├── predicate
│ │ └── predicate.go
│ ├── privacy
│ │ └── privacy.go
│ ├── runtime
│ │ └── runtime.go
│ ├── runtime.go
│ ├── schema
│ │ └── entry.go
│ └── tx.go
├── go.mod
└── go.sum
Many files were generated, but developers do not need to look at or modify most of them. Now the models for handling Entry have been generated.
Implementing the Application
Now let's build the application. First, here is the code for the migration.
package main
import (
"context"
"log"
"github.com/mattn/entgo-bbs/ent"
_ "github.com/mattn/go-sqlite3"
)
func main() {
client, err := ent.Open("sqlite3", "file:bbs.sqlite?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
// Run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
}
By writing this code, even if you modify ent/schema/entry.go later, the tables will be handled appropriately. Next, let's build the web application. I like Echo, so I will use it. Add a handler like the following:
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "")
})
e.POST("/add", func(c echo.Context) error {
return c.String(http.StatusOK, "")
})
e.Logger.Fatal(e.Start(":8989"))
Manipulating Entities
Now we finally need to manipulate the Entry. Operations on the Entry are performed via the client. For selection, use Query. Here we get 10 entries, sorted in ascending order using created_at as the sort key.
eq := client.Entry.Query().Order(ent.Asc(entry.FieldCreatedAt)).Limit(10)
entries := eq.AllX(context.Background())
To add an Entry, use Create.
e := client.Entry.Create()
e.SetContent("Isn't Zenn interesting?")
e.Save(context.Background())
Leave the Rest to Us
Now you just need to integrate this into the app side, pass entries to the template engine, and in the add handler, add an Entry and perform a redirect to complete the simple one-line message board. For the template engine, I used the Go version of the Slim template engine.
package main
import (
"context"
"log"
"net/http"
"github.com/labstack/echo"
"github.com/mattn/entgo-bbs/ent"
"github.com/mattn/entgo-bbs/ent/entry"
"github.com/mattn/go-slim"
_ "github.com/mattn/go-sqlite3"
)
type Payload struct {
Content string `json:"content"`
}
func main() {
client, err := ent.Open("sqlite3", "file:bbs.sqlite?cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
// Run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
t, err := slim.ParseFile("template/index.slim")
if err != nil {
log.Fatal(err)
}
e := echo.New()
e.GET("/", func(c echo.Context) error {
eq := client.Entry.Query().Order(ent.Desc(entry.FieldCreatedAt)).Limit(10)
entries := eq.AllX(context.Background())
c.Request().Header.Set("content-type", "text/html")
return t.Execute(c.Response(), map[string]interface{}{
"entries": entries,
})
})
e.POST("/add", func(c echo.Context) error {
e := client.Entry.Create()
e.SetContent(c.FormValue("content"))
if _, err := e.Save(context.Background()); err != nil {
log.Println(err.Error())
return c.String(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
}
return c.Redirect(http.StatusFound, "/")
})
e.Logger.Fatal(e.Start(":8989"))
}
The template is as follows:
doctype 5
html lang="ja"
head
meta charset="UTF-8"
title
body
form method=post action=add
input type=text name=content
input type=submit
ul
- for x in entries
li = x.Content
Start it up and confirm it functions as a one-line message board.
The code I made is available in the following repository. Feel free to modify it and play around.
Conclusion
I implemented a simple application using the ORM library ent, developed by Facebook. As you've seen, it has a relatively easy-to-understand interface. By following the same steps, most people should be able to implement an application easily. Give it a try and build something!
Discussion