Created
November 14, 2016 20:26
-
-
Save jchris/6a6756f97b94e9cdac963ffa617150fb to your computer and use it in GitHub Desktop.
Executable example for FaunaDB Go release blog post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
f "github.com/faunadb/faunadb-go/faunadb" | |
) | |
// I guess we can blog about how easy is to integrate your data structures with fauna using the go driver | |
// which, in my opinion, is one of the easiest so far. | |
// A todo example was the simples I could find, although it has been used a lot already. | |
var ( | |
client *f.FaunaClient | |
dataField = f.ObjKey("data") | |
) | |
func init() { | |
secret := setupDB() // We should ignore this function call and hardcode a fake secret. DB setup is tedious and should not make to blog posts i think. | |
client = f.NewFaunaClient(secret, f.Endpoint("http://localhost:8443")) | |
} | |
// This is the cool stuff. You can mark the fields and let the driver decode from fauna values to your own type. | |
type Pet struct { | |
Name string `fauna:"name"` | |
Age int `fauna:"age"` | |
} | |
func main() { | |
// Create | |
bob := Pet{ | |
Name: "bob the cat", | |
Age: 5, | |
} | |
client.Query( | |
f.Create( | |
f.Class("pets"), | |
f.Obj{"data": bob}, | |
), | |
) | |
// Find | |
res, _ := client.Query( | |
f.Get( | |
f.MatchTerm( | |
f.Index("pet_by_name"), | |
"bob the cat", | |
), | |
), | |
) | |
var pet Pet | |
res.At(dataField).Get(&pet) | |
fmt.Println(pet) // Prints: {bob the cat, 5} | |
} | |
func setupDB() (secret string) { // paste your secret here | |
adminClient := f.NewFaunaClient("secret", f.Endpoint("http://localhost:8443")) | |
adminClient.Query(f.Delete(f.Ref("databases/db-test"))) | |
adminClient.Query(f.CreateDatabase(f.Obj{"name": "db-test"})) | |
res, _ := adminClient.Query(f.CreateKey(f.Obj{"role": "server", "database": f.Database("db-test")})) | |
res.At(f.ObjKey("secret")).Get(&secret) | |
client := adminClient.NewSessionClient(secret) | |
client.Query(f.CreateClass(f.Obj{"name": "pets"})) | |
client.Query(f.CreateIndex(f.Obj{ | |
"name": "pet_by_name", | |
"source": f.Class("pets"), | |
"terms": f.Arr{f.Obj{"field": f.Arr{"data", "name"}}}, | |
"unique": true, | |
})) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment