filterbase

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 3 Imported by: 0

README

Filterbase

ci codecov

Filterbase is a simple, lightweight, and fast library for filtering data in go using CEL expressions.

Installation

go get github.com/mscno/filterbase

Usage

In order to use the filtering package you need to implement a simple filter function for your struct. This is required for the filtering package to be able to filter your data and get the right params and field values from the structs.

Example:

type User struct {
	Name  string
	Age   int
	Admin bool
}

// Filters the slice acs by invoke CEL program for each AC
func FilterUsers(ctx context.Context, acs []*User, celCmd string) ([]*User, error) {
	var celEnvOptions = []cel.EnvOption{
		cel.Variable("name", cel.StringType),
		cel.Variable("age", cel.IntType),
		cel.Variable("admin", cel.BoolType),
	}

	accessorFn := func(row *User) map[string]interface{} {

		return map[string]any{
			"name":  row.Name,
			"age":   row.Age,
			"admin": row.Admin,
		}
	}

	return Filter(ctx, acs, celEnvOptions, accessorFn, celCmd)
}

Then you can use the filter function like this:

filteredUsers := FilterUsers(ctx, users, "name == 'John' && age > 18")

Or you can create your own specific filter functions for your structs:

func FilterUsersByAge(users []*User, age int) []users {
	ctx := context.Background()
    return FilterUsers(ctx, users, fmt.Sprintf("age > %d", age))
}

and use it like this:

filteredUsers := FilterUsersByAge(users, 18)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidCELProgram = errors.New("invalid CEL program")
View Source
var ErrInvalidCELResultType = errors.New("invalid CEL expression result, filter expression must evaluate to a bool")

Functions

func Filter

func Filter[T any](ctx context.Context, ss []T, envOptions []cel.EnvOption, fn func(T) map[string]interface{}, celexpression string) ([]T, error)

Filters the slice of [T] by creating and invoking a CEL filter expression for each row

Types

This section is empty.

Jump to

Keyboard shortcuts

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