filterbuilder

package module
v0.0.0-...-aed8f38 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2022 License: GPL-3.0 Imports: 3 Imported by: 0

README

MongoDB-Filter-Struct

Test workflow

Introduction

mongo-filter-struct is a library for creating filtration bson for MongoDB using golang's native struct type. It is inspired by django-rest-framework-filters

Installation

go get github.com/Kamran151199/mongo-filter-struct

Usage

package main

import (
	"fmt"
	filterbuilder "github.com/Kamran151199/mongo-filter-struct"
	"go.mongodb.org/mongo-driver/bson"
	"reflect"
)

type SampleFilter struct {
	Name  string `lookup:"name" operator:"$regex"`
	Age   int    `lookup:"age" operator:"$gt"`
	Adult bool   `lookup:"adult" operator:"$eq"`
}

func main() {
	filter := SampleFilter{
		Name:  "John",
		Age:   30,
		Adult: true,
	}
	builder := filterbuilder.NewBuilder()
	query, err := builder.BuildQuery(filter)
	if err != nil {
		fmt.Println(err)
	}
	expected := bson.M{
		"name":  bson.M{"$regex": "John"},
		"age":   bson.M{"$gt": 30},
		"adult": bson.M{"$eq": true},
	}
	fmt.Printf("Expected is equal to res: %v\n", reflect.DeepEqual(expected, query))
}

License


GNU License Version 3, see LICENSE

Copyright (c) 2022 Kamran

Documentation

Index

Constants

View Source
const (
	Regex                = "$regex"
	Equals               = "$eq"
	GreaterThan          = "$gt"
	LessThan             = "$lt"
	GreaterThanOrEqualTo = "$gte"
	LessThanOrEqualTo    = "$lte"
	In                   = "$in"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is a helper struct for building query strings.

func NewBuilder

func NewBuilder() *Builder

NewBuilder returns a new Builder with empty Output.

func (*Builder) AddParam

func (b *Builder) AddParam(query *Param) *Builder

AddParam adds a param to the resulting query - Output.

func (*Builder) BuildQuery

func (b *Builder) BuildQuery(filterStruct interface{}) (bson.M, error)

BuildQuery composes a query string from provided args for the specified storage type.

func (*Builder) GetOutput

func (b *Builder) GetOutput() (bson.M, error)

GetOutput returns the output of the builder if there are no errors

type Param

type Param struct {
	FieldType reflect.Kind
	FieldName string
	Operator  string
	Value     interface{}
}

Param is a single field's parameter for the query.

func (*Param) IsValidOperator

func (q *Param) IsValidOperator(fieldType reflect.Kind, operator string) bool

IsValidOperator returns true if the operator is valid for the field type.

func (*Param) Validate

func (q *Param) Validate() error

Validate runs all the validation checks on the query.

Jump to

Keyboard shortcuts

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