filter method

String filter(
  1. String expr, [
  2. Map<String, dynamic> query = const {}
])

Constructs a filter expression with placeholders populated from a map.

Placeholder parameters are defined with the {:paramName} notation.

The following parameter values are supported:

  • String (single quotes are autoescaped)
  • num
  • bool
  • DateTime
  • null
  • everything else is converted to a string using jsonEncode()

Example:

pb.collection("example").getList(filter: pb.filter(
  "title ~ {:title} && created >= {:created}",
  { "title": "example", "created": DateTime.now() },
));

Implementation

String filter(String expr, [Map<String, dynamic> query = const {}]) {
  if (query.isEmpty) {
    return expr;
  }

  query.forEach((key, value) {
    if (value == null || value is num || value is bool) {
      value = value.toString();
    } else if (value is DateTime) {
      value = "'${value.toUtc().toIso8601String().replaceFirst("T", " ")}'";
    } else if (value is String) {
      value = "'${value.replaceAll("'", "\\'")}'";
    } else {
      value = "'${jsonEncode(value).replaceAll("'", "\\'")}'";
    }
    expr = expr.replaceAll("{:$key}", value.toString());
  });

  return expr;
}