Categorygithub.com/Dragomir-Ivanov/rest-layer-mongo-driver
modulepackage
0.0.0-20240306073735-a1de650f19b6
Repository: https://github.com/dragomir-ivanov/rest-layer-mongo-driver.git
Documentation: pkg.go.dev

# README

REST Layer MongoDB Backend

godoc license

This REST Layer resource storage backend stores data in a MongoDB cluster using mongo-driver.

Usage

import (
  "context"
  "reflect"

  "go.mongodb.org/mongo-driver/bson"
  "go.mongodb.org/mongo-driver/bson/bsontype"
  "go.mongodb.org/mongo-driver/mongo"
  "go.mongodb.org/mongo-driver/mongo/options"
  rsmongo "github.com/Dragomir-Ivanov/rest-layer-mongo-driver"
)

Create a mongo master session:

	reg := bson.NewRegistry()
	reg.RegisterTypeMapEntry(bson.TypeDateTime, reflect.TypeOf(time.Time{}))
	reg.RegisterTypeMapEntry(bson.TypeInt32, reflect.TypeOf(1))
	reg.RegisterTypeMapEntry(bson.TypeArray, reflect.TypeOf([]interface{}{}))

  clientOptions := options.Client().SetRegistry(reg).ApplyURI("mongodb://localhost/")
  s, err := mongo.Connect(context.Background(), clientOptions)

Create a resource storage handler with a given DB/collection:

s := rsmongo.NewHandler(client, "the_db", "the_collection")

Use this handler with a resource:

index.Bind("foo", foo, s, resource.DefaultConf)

You may want to create a many mongo handlers as you have resources as long as you want each resources in a different collection. You can share the same client across all you handlers.

Object ID

This package also provides a REST Layer schema.Validator for MongoDB ObjectIDs. This validator ensures proper binary serialization of the Object ID in the database for space efficiency.

You may reference this validator using mongo.ObjectID as schema.Field.

A mongo.NewObjectID field hook and mongo.ObjectIDField helper are also provided.

# Functions

NewHandler creates an new mongo handler.

# Variables

NewObjectID is a field hook handler that generates a new Mongo ObjectID hex if value is nil to be used in schema with OnInit.
ObjectIDField is a common schema field configuration that generate an Object ID for new item id.

# Structs

ObjectID validates and serialize unique id.

# Type aliases

Handler handles resource storage in a MongoDB collection.