Create a getting started document and example

This commit is contained in:
sunboyy 2021-02-04 22:08:04 +07:00
parent 7cdff6dcc0
commit 1319114071
6 changed files with 397 additions and 4 deletions
examples/getting-started

View file

@ -0,0 +1,95 @@
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Replace these values with your own connection option. This connection option is hard-coded for easy
// demonstration. Make sure not to hard-code the credentials in the production code.
const (
connectionString = "mongodb://lineman:lineman@localhost:27017"
databaseName = "repogen_examples"
collectionName = "gettingstarted_user"
)
var (
userRepository UserRepository
userID primitive.ObjectID
)
func init() {
// create a connection to the database
client, err := mongo.NewClient(options.Client().ApplyURI(connectionString))
if err != nil {
panic(err)
}
err = client.Connect(context.TODO())
if err != nil {
panic(err)
}
// instantiate a user repository from the user collection
userRepository = NewUserRepository(client.Database(databaseName).Collection(collectionName))
}
func main() {
demonstrateInsertion()
demonstrateFind()
demonstrateUpdate()
demonstrateDelete()
}
// demonstrateInsertion shows how insert method of repogen works. It receives a model struct and returns
// an insertedID.
func demonstrateInsertion() {
userModel := &UserModel{
Username: "sunboyy",
DisplayName: "SB",
City: "Bangkok, Thailand",
}
insertedID, err := userRepository.InsertOne(context.Background(), userModel)
if err != nil {
panic(err)
}
userID = insertedID.(primitive.ObjectID)
fmt.Printf("Insert (one): inserted id = %v\n", insertedID)
}
// demonstrateFind shows how find method in repogen works. It receives query parameters through method
// arguments and returns matched result
func demonstrateFind() {
userModel, err := userRepository.FindByUsername(context.Background(), "sunboyy")
if err != nil {
panic(err)
}
fmt.Printf("Find (one): found user = %+v\n", userModel)
}
// demonstrateUpdate shows how update method in repogen works. It receives updates and query parameters
// through method arguments and returns true/false whether there is a matched query.
func demonstrateUpdate() {
matched, err := userRepository.UpdateDisplayNameByID(context.Background(), "Sunboy", userID)
if err != nil {
panic(err)
}
fmt.Printf("Update (one): matched = %v\n", matched)
}
// demonstrateDelete shows how delete method in repogen works. It receives query parameters through
// method arguments and returns matched count.
func demonstrateDelete() {
matchedCount, err := userRepository.DeleteByCity(context.Background(), "Bangkok, Thailand")
if err != nil {
panic(err)
}
fmt.Printf("Delete (many): matched count = %d\n", matchedCount)
}

View file

@ -0,0 +1,38 @@
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// UserModel is a model of user that is stored in the database
type UserModel struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
Username string `bson:"username" json:"username"`
DisplayName string `bson:"display_name" json:"displayName"`
City string `bson:"city" json:"city"`
}
//go:generate repogen -src=user.go -dest=user_repo.go -model=UserModel -repo=UserRepository
// UserRepository is an interface that describes the specification of querying user data in the database
type UserRepository interface {
// InsertOne stores userModel into the database and returns inserted ID if insertion succeeds
// and returns error if insertion fails.
InsertOne(ctx context.Context, userModel *UserModel) (interface{}, error)
// FindByUsername queries user by username. If a user with specified username exists, the user will be
// returned. If no user exists or error occurs while querying, error will be returned.
FindByUsername(ctx context.Context, username string) (*UserModel, error)
// UpdateDisplayNameByID updates a user with the specified ID with a new display name. If there is a user
// matches the query, it will return true. Error will be returned only when error occurs while accessing
// the database. This is a ONE mode because the first return type is a boolean.
UpdateDisplayNameByID(ctx context.Context, displayName string, id primitive.ObjectID) (bool, error)
// DeleteByCity deletes users that have `city` value match the parameter and returns the match count.
// The error will be returned only when error occurs while accessing the database. This is a MANY mode
// because the first return type is an integer.
DeleteByCity(ctx context.Context, city string) (int, error)
}

View file

@ -0,0 +1,62 @@
// Code generated by repogen. DO NOT EDIT.
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
func NewUserRepository(collection *mongo.Collection) UserRepository {
return &UserRepositoryMongo{
collection: collection,
}
}
type UserRepositoryMongo struct {
collection *mongo.Collection
}
func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *UserModel) (interface{}, error) {
result, err := r.collection.InsertOne(arg0, arg1)
if err != nil {
return nil, err
}
return result.InsertedID, nil
}
func (r *UserRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*UserModel, error) {
var entity UserModel
if err := r.collection.FindOne(arg0, bson.M{
"username": arg1,
}).Decode(&entity); err != nil {
return nil, err
}
return &entity, nil
}
func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 string, arg2 primitive.ObjectID) (bool, error) {
result, err := r.collection.UpdateOne(arg0, bson.M{
"_id": arg2,
}, bson.M{
"$set": bson.M{
"display_name": arg1,
},
})
if err != nil {
return false, err
}
return result.MatchedCount > 0, err
}
func (r *UserRepositoryMongo) DeleteByCity(arg0 context.Context, arg1 string) (int, error) {
result, err := r.collection.DeleteMany(arg0, bson.M{
"city": arg1,
})
if err != nil {
return 0, err
}
return int(result.DeletedCount), nil
}