Skip to content

Commit

Permalink
feat(couchbase) Add example
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmetcanozcan committed Sep 11, 2024
1 parent 60807fb commit 41f949c
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 0 deletions.
3 changes: 3 additions & 0 deletions example/withcouchbase/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
couchbase:
host: "<cb_host>"
bucketname: "foo_bucket"
34 changes: 34 additions & 0 deletions example/withcouchbase/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"context"

"github.com/Trendyol/chaki/modules/server/controller"
"github.com/Trendyol/chaki/modules/server/route"
)

type getFooRequest struct {
ID string `param:"id" validate:"required"`
}

type fooController struct {
controller.Controller
repo FooRepository
}

func newController(repo FooRepository) controller.Controller {
return &fooController{
Controller: controller.New("foo-controller").SetPrefix("/foo"),
repo: repo,
}
}

func (ct *fooController) getFoo(ctx context.Context, req getFooRequest) (*Foo, error) {
return ct.repo.Get(ctx, req.ID)
}

func (ct *fooController) Routes() []route.Route {
return []route.Route{
route.Get("/:id", ct.getFoo),
}
}
28 changes: 28 additions & 0 deletions example/withcouchbase/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"github.com/Trendyol/chaki"
"github.com/Trendyol/chaki/logger"
"github.com/Trendyol/chaki/modules/couchbase"
"github.com/Trendyol/chaki/modules/server"
)

func main() {
app := chaki.New()

app.WithOption(
chaki.WithConfigPath("config.yaml"),
)

app.Use(
server.Module(),
couchbase.Module(),
)

app.Provide(
NewRepository,
newController,
)

logger.Fatal(app.Start())
}
45 changes: 45 additions & 0 deletions example/withcouchbase/repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
"context"

"github.com/Trendyol/chaki/config"
"github.com/Trendyol/chaki/modules/couchbase"
"github.com/couchbase/gocb/v2"
)

type Foo struct {
ID string
Bar string
}

type FooRepository interface {
Get(ctx context.Context, id string) (*Foo, error)
}

type fooRepository struct {
coll *gocb.Collection
}

func NewRepository(cluster *gocb.Cluster, cfg *config.Config) FooRepository {
return &fooRepository{
coll: cluster.Bucket(cfg.GetString("couchbase.bucketname")).DefaultCollection(),
}
}

func (r *fooRepository) Get(ctx context.Context, id string) (*Foo, error) {
result := new(Foo)
resp, err := r.coll.Get(id, &gocb.GetOptions{
// Enable tracing
ParentSpan: couchbase.ParentSpan(ctx),
})
if err != nil {
return nil, err
}

if err := resp.Content(result); err != nil {
return nil, err
}

return result, nil
}

0 comments on commit 41f949c

Please sign in to comment.