Skip to content

coze-cloud/clerk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

32 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

clerk

๐Ÿ“’ A minimalistic library for abstracting database operations

Installation

Adding clerk to your Go module is as easy as calling this command in your project

go get github.com/coze-cloud/clerk

Supported databases

clerk has builtin support for the following database/search engines:

  • MongoDB - MongoDB is a document-oriented database
  • Meilisearch - Meilisearch is a powerful and fast search engine

Usage

Being a minimalistic library, clerk only provides the basics. The rest is up to your specific need.

Creating a connection

connection, err := mongodb.NewMongoConnection("mongodb://root:root@localhost:27017")
if err != nil {
	panic(err)
}

defer connection.Close(func(err error) {
	if err != nil {
		panic(err)
	}
})

Defining a database operator instance

operator := mongodb.NewMongodbOperator[T](connection)

The generic parameter T defines the data type which the operator can interact with. An operator has to be defined for each data type in use with clerk.

Defining a database & collection

collection := clerk.NewDatabase("foo").Collection("bar")

Certain operators only work with collections and don't need a database:

collection := clerk.NewCollection("foo")

Persisting a data in a collection

type Message struct {
    Id   string `bson:"_id"`
    Body string
}

createCtx, createCancel := context.WithTimeout(
    context.Background(),
    time.Second * 5,
)
defer createCancel()

create := clerk.NewCreate(collection, Message{
    Id:   "0",
    Body: "Hello World",
})
if err := create.Execute(createCtx, operator); err != nil {
    panic(err)
}

Querying the collection

type Message struct {
    Id   string `bson:"_id"`
    Body string
}

results := []Message{}

queryCtx, queryCancel := context.WithTimeout(
    context.Background(),
    time.Second * 5,
)
defer queryCancel()

query := clerk.NewQuery[Message](collection).Where("_id", "0")
queryChan, err := query.Execute(queryCtx, operator)
if err != nil {
    panic(err)
}

for result := range queryChan {
    results := append(results, result)
}

fmt.Println(results...)

Copyright ยฉ 2022 - The cozy team & contributors