mongo

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 5, 2019 License: MIT Imports: 10 Imported by: 1

README

REST Layer MongoDB Backend

godoc license build

This REST Layer resource storage backend stores data in a MongoDB cluster using mgo.

Usage

import "github.com/rs/rest-layer-mongo"

Create a mgo master session:

session, err := mgo.Dial(url)

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

s := mongo.NewHandler(session, "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 mgo session 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.

Documentation

Overview

Package mongo is a REST Layer resource storage handler for MongoDB using mgo

Example
package main

import (
	"log"
	"net/http"

	"github.com/rs/cors"
	"github.com/rs/rest-layer/resource"
	"github.com/rs/rest-layer/rest"
	"github.com/rs/rest-layer/schema"
	mgo "gopkg.in/mgo.v2"

	mongo "github.com/rs/rest-layer-mongo"
)

var (
	user = schema.Schema{
		Fields: schema.Fields{
			"id":      schema.IDField,
			"created": schema.CreatedField,
			"updated": schema.UpdatedField,
			"name": {
				Required:   true,
				Filterable: true,
				Sortable:   true,
				Validator: &schema.String{
					MaxLen: 150,
				},
			},
		},
	}

	// Define a post resource schema
	post = schema.Schema{
		Fields: schema.Fields{
			"id":      schema.IDField,
			"created": schema.CreatedField,
			"updated": schema.UpdatedField,
			"user": {
				Required:   true,
				Filterable: true,
				Validator: &schema.Reference{
					Path: "users",
				},
			},
			"public": {
				Filterable: true,
				Validator:  &schema.Bool{},
			},
			"meta": {
				Schema: &schema.Schema{
					Fields: schema.Fields{
						"title": {
							Required: true,
							Validator: &schema.String{
								MaxLen: 150,
							},
						},
						"body": {
							Validator: &schema.String{
								MaxLen: 100000,
							},
						},
					},
				},
			},
		},
	}
)

func main() {
	session, err := mgo.Dial("")
	if err != nil {
		log.Fatalf("Can't connect to MongoDB: %s", err)
	}
	db := "test_rest_layer"

	index := resource.NewIndex()

	users := index.Bind("users", user, mongo.NewHandler(session, db, "users"), resource.Conf{
		AllowedModes: resource.ReadWrite,
	})

	users.Bind("posts", "user", post, mongo.NewHandler(session, db, "posts"), resource.Conf{
		AllowedModes: resource.ReadWrite,
	})

	api, err := rest.NewHandler(index)
	if err != nil {
		log.Fatalf("Invalid API configuration: %s", err)
	}

	http.Handle("/", cors.New(cors.Options{OptionsPassthrough: true}).Handler(api))

	log.Print("Serving API on http://localhost:8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// NewObjectID is a field hook handler that generates a new Mongo ObjectID hex if
	// value is nil to be used in schema with OnInit.
	NewObjectID = func(ctx context.Context, value interface{}) interface{} {
		if value == nil {
			value = bson.NewObjectId().Hex()
		}
		return value
	}

	// ObjectIDField is a common schema field configuration that generate an Object ID
	// for new item id.
	ObjectIDField = schema.Field{
		Required:   true,
		ReadOnly:   true,
		OnInit:     NewObjectID,
		Filterable: true,
		Sortable:   true,
		Validator:  &ObjectID{},
	}
)

Functions

This section is empty.

Types

type Handler

type Handler func(ctx context.Context) (*mgo.Collection, error)

Handler handles resource storage in a MongoDB collection.

func NewHandler

func NewHandler(s *mgo.Session, db, collection string) Handler

NewHandler creates an new mongo handler

func (Handler) Clear

func (m Handler) Clear(ctx context.Context, q *query.Query) (int, error)

Clear clears all items from the mongo collection matching the query. Note that when q.Window != nil, the current implementation may error if the BSON encoding of all matching IDs according to the q.Window length gets close to the maximum document size in MongDB (usually 16MiB): https://docs.mongodb.com/manual/reference/limits/#bson-documents

func (Handler) Count

func (m Handler) Count(ctx context.Context, query *query.Query) (int, error)

Count counts the number items matching the lookup filter

func (Handler) Delete

func (m Handler) Delete(ctx context.Context, item *resource.Item) error

Delete deletes an item from the mongo collection.

func (Handler) Find

func (m Handler) Find(ctx context.Context, q *query.Query) (*resource.ItemList, error)

Find items from the mongo collection matching the provided query.

func (Handler) Insert

func (m Handler) Insert(ctx context.Context, items []*resource.Item) error

Insert inserts new items in the mongo collection.

func (Handler) Update

func (m Handler) Update(ctx context.Context, item *resource.Item, original *resource.Item) error

Update replace an item by a new one in the mongo collection.

type ObjectID

type ObjectID struct{}

ObjectID validates and serialize unique id

func (ObjectID) BuildJSONSchema

func (v ObjectID) BuildJSONSchema() (map[string]interface{}, error)

BuildJSONSchema implements the jsonschema.Builder interface.

func (ObjectID) Serialize

func (v ObjectID) Serialize(value interface{}) (interface{}, error)

Serialize implements FieldSerializer interface

func (ObjectID) Validate

func (v ObjectID) Validate(value interface{}) (interface{}, error)

Validate implements FieldValidator interface

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL