gomongoapi

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2023 License: MIT Imports: 10 Imported by: 0

README

gomongoapi

Go Reference

gomongoapi allows for easy creation of a server that connects to a mongodb, creates routes to query it with the intent to easily create Grafana Dashboards.

Recommended Grafana plugins JSON API and Infinity

Documentation

Overview

Package gomongoapi is a pure go client that allows for easy creation of a server that creates routes to query a MongoDB. The intent of these routes is to be used alongside either the JSON API or Infinity plugin with Grafana to allow for MongoDB dashboards within Grafana.

Package is using gin for the server and can be heavily customized as a custom gin engine can be set in the options.

Available default routes:

+----------------------------------+-----------+-------+------------------------------------------------------------------------------------------------------+
| Path                             | HTTP Verb | Body  | Result                                                                                               |
+----------------------------------+-----------+-------+------------------------------------------------------------------------------------------------------+
| /                                |    GET    | Empty | Always 200, test connection.                                                                         |
| /api/databases                   |    GET    | Empty | Returns list of available databases, unless a default is set.                                        |
| /api/collections                 |    GET    | Empty | Returns a list collections to the default db or the one passed in url param.                         |
| /api/collections/:name/find      |    POST   | JSON  | Returns result of find on the collection name. DB is either default or one passed in url param.      |
| /api/collections/:name/aggregate |    POST   | JSON  | Returns result of aggregate on the collection name. DB is either default or one passed in url param. |
| /custom/<Custom Route>           |    GET    | N/A   | Users can create custom GET route, they control everything.                                          |
| /custom/<Custom Route>           |    POST   | N/A   | Users can create custom POST route, they control everything.                                         |
+----------------------------------+-----------+-------+------------------------------------------------------------------------------------------------------+

To use the package, user must create the server options and at the minimum set the mongodb client options to connect to the db. Once the options are made, they can be passed to create a new server. Server Start() function will run the server and block until it encounters an error.

Example

// Set server options
serverOpts := gomongoapi.ServerOptions()
serverOpts.SetMongoClientOpts(options.Client().ApplyURI("mongodb://localhost:27017"))
serverOpts.SetDefaultDB("app")
serverOpts.SetAddress(":8080")

// Create server and set values
server := gomongoapi.NewServer(serverOpts)

// Add custom route
// Route will always return the count of the number of records in users collection
server.AddCustomGET("/appUsersCount", func(ctx *gin.Context) {
	client := server.GetMongoClient()

	count, err := client.Database("app").Collection("users").CountDocuments(ctx.Request.Context(), bson.M{})
	if err != nil {
		ctx.String(http.StatusInternalServerError, "Error running count: "+err.Error())
		return
	}

	ctx.JSON(http.StatusOK, bson.M{"Count": count})
})

// Start server
server.Start()

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidCustomRouteName = errors.New("invalid custom route name")
)

Functions

This section is empty.

Types

type Options

type Options struct {
	// Gin engine that server will use, gin.Default() is the default value.
	Router *gin.Engine

	// Server address that the gin router with use. Default is :8080
	Address string

	// Optional field to set custom route group name which will be used if user adds custom routes. Default is 'custom'.
	CustomRouteName string

	// Mongo Client options. Default is an empty set of options.
	MongoClientOpts *options.ClientOptions

	// Default value of number of records find will return if one is not passed in url.
	FindLimit int

	// An upper limit of the number of records that find can return. Default is 0 which means no limit.
	FindMaxLimit int

	// Optional field if user wants to set a default database to use. If none is set then all databases will be queryable.
	DefaultDB string
}

Options contains options to configure the mongo api server

func ServerOptions

func ServerOptions() *Options

Returns server options with default values

func (*Options) SetAddress

func (o *Options) SetAddress(address string)

SetAddress sets the server address.

func (*Options) SetCustomRouteName added in v1.0.2

func (o *Options) SetCustomRouteName(customRouteName string) error

SetCustomRouteName sets custom route name.

func (*Options) SetDefaultDB

func (o *Options) SetDefaultDB(defaultDB string)

SetDefaultDB sets the default db to be used in the collection routes. This value is option as a db name can be passed to the routes.

func (*Options) SetFindLimit

func (o *Options) SetFindLimit(findLimit int)

SetFindLimit sets the default limit when running find.

func (*Options) SetFindMaxLimit

func (o *Options) SetFindMaxLimit(findMaxLimit int)

SetFindMaxLimit sets the upper limit for find results.

func (*Options) SetMongoClientOpts

func (o *Options) SetMongoClientOpts(mongoClientOpts *options.ClientOptions)

SetAddress sets the server address.

func (*Options) SetRouter

func (o *Options) SetRouter(router *gin.Engine)

SetRouter sets the gin engine that will be used.

type Server

type Server interface {

	// Start new server
	// This function will block unless an error occurs
	Start() error

	// Add custom middleware in the /api router group.
	// This allows custom additions like logging, auth, etc
	SetAPIMiddleware(middleware ...gin.HandlerFunc)

	// Add custom middleware in the /custom router group.
	// This allows custom additions like logging, auth, etc
	SetCustomMiddleware(middleware ...gin.HandlerFunc)

	// Add custom GET request, path will be under the /custom route group
	AddCustomGET(relativePath string, handlers ...gin.HandlerFunc)

	// Add custom POST request, path will be under the /custom route group
	AddCustomPOST(relativePath string, handlers ...gin.HandlerFunc)

	// Returns server mongo client.
	// This can be used along side AddCustomGET() and AddCustomPost() to make custom routes that use the db.
	GetMongoClient() *mongo.Client
}

Server interface for mongo api server

func NewServer

func NewServer(opts *Options) Server

Create a new server Must pass in Mongo Client Options

Jump to

Keyboard shortcuts

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