sort

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2022 License: MIT Imports: 4 Imported by: 0

README

Query for MongoDB-Sort

MongoDB has a client that allows you to sort the result of a find request. This parser support a simple syntax to write sort expressions e.g. by the requester of an API (see example below).

The language

The syntax of this language is simple: field_name_to_sort_by = sort_order. You can chain multiple sort criteria with with the separator , e.g. last_name=asc,first_name=asc. There are two ways to sort:

  1. ASC or 1 to sort ascending
  2. DESC or -1 to sort descending

Example

For API
import (
	"github.com/StevenCyb/goapiutils/parser/mongo/sort"

	"go.mongodb.org/mongo-driver/mongo/options"
)
// ...

  sortExpressionString := r.URL.Query().Get("sort")

  parser := sort.NewParser(nil)
  sortExpression, err := parser.Parse(sortExpressionString)
  // ...

  opts := options.Find()
  opts.SetSort(sortExpression)
  // ...

  coll.Find(r.Context(), filter, opts...)
  // ...
For API with policy

This parser supports two types of policies:

  1. WHITELIST_POLICY -> disallow everything except given fields
  2. BLACKLIST_POLICY -> allow everything except given fields
import (
	"github.com/StevenCyb/goapiutils/mongo/sort"
	"github.com/StevenCyb/goapiutils/parser/tokenizer"

	"go.mongodb.org/mongo-driver/mongo/options"
)

func ListHandler(w http.ResponseWriter, r *http.Request) {
  sortExpressionString := r.URL.Query().Get("sort")

  parser := sort.NewParser(
    // just allow the requester to sort by
    // "first_name", "last_name" and "age"
    tokenizer.NewPolicy(
      tokenizer.WHITELIST_POLICY,
      "first_name", "last_name", "age",
    )
  )
  sortExpression, err := parser.Parse(sortExpressionString)
  // ...

  opts := options.Find()
  opts.SetSort(sortExpression)
  // ...

  coll.Find(r.Context(), filter, opts...)
  // ...
}

Documentation

Index

Constants

View Source
const (
	SkipType          tokenizer.Type = "SKIP"
	AndType           tokenizer.Type = ","
	SetType           tokenizer.Type = "="
	SortConditionType tokenizer.Type = "SORT_CRITERIA"
	FieldNameType     tokenizer.Type = "FIELD_NAME"
)

Types that are used in this parser.

Variables

This section is empty.

Functions

This section is empty.

Types

type Parser

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

Parser provides the logic to parse rsql statements.

func NewParser

func NewParser(policy *tokenizer.Policy) *Parser

NewParser creates a new parser.

func (*Parser) Parse

func (p *Parser) Parse(query string) (bson.D, error)

Parse a given query.

Jump to

Keyboard shortcuts

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