Created
February 3, 2017 14:59
-
-
Save thewraven/3969e4e624c60bc5809d5ae8d236f012 to your computer and use it in GitHub Desktop.
Example of a filter using a function to access nested fields
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" | |
r "gopkg.in/dancannon/gorethink.v3" | |
) | |
type User struct { | |
ID string `json:"id,omitempty"` | |
FirstName string `json:"firstName,omitempty"` | |
LastName string `json:"lastName,omitempty"` | |
Email string `json:"email,omitempty"` | |
Password string `json:"password,omitempty"` | |
Salt string `json:"salt,omitempty"` | |
} | |
type UnverifiedUserRequest struct { | |
ID string `json:"id,omitempty"` | |
Token string `json:"token,omitempty"` | |
User User `json:"user,omitempty"` | |
} | |
func main() { | |
//initializing the connection and creating the required table | |
session, err := r.Connect(r.ConnectOpts{ | |
Database: "test", | |
}) | |
if err != nil { | |
panic(err) | |
} | |
tableUnverifiedUsers := "unverified_user" | |
r.TableDrop(tableUnverifiedUsers).RunWrite(session) | |
_, err = r.TableCreate(tableUnverifiedUsers).RunWrite(session) | |
if err != nil { | |
panic(err) | |
} | |
//inserting an unverified account | |
email := "[email protected]" | |
unverifiedAccount := UnverifiedUserRequest{ | |
Token: "affed-0efa", | |
User: User{ | |
ID: "afed-01ff", | |
FirstName: "Juan Carlos", | |
LastName: "García", | |
Email: email, | |
}, | |
} | |
_, err = r.Table(tableUnverifiedUsers).Insert(unverifiedAccount).RunWrite(session) | |
if err != nil { | |
panic(err) | |
} | |
//querying the unverified account by email | |
cursor, err := r.Table(tableUnverifiedUsers). | |
Filter(func(unverified r.Term) r.Term { | |
//the equivalent in javascript would be unverified("User")("Email").eq(email) | |
return unverified.Field("User").Field("Email").Eq(email) | |
}).Run(session) | |
if err != nil { | |
panic(err) | |
} | |
//dump the query result onto a new struct | |
var retrievedUser UnverifiedUserRequest | |
err = cursor.One(&retrievedUser) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(retrievedUser) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment