SoftInstigate / restheart

Rapid API Development with MongoDB
https://restheart.org
GNU Affero General Public License v3.0
807 stars 171 forks source link

Aggregations and optional query params? #390

Closed StephenOTT closed 3 years ago

StephenOTT commented 3 years ago

Is there any established pattern for handling optional query params with the avars param?

https://restheart.org/docs/aggregations/#passing-variables-to-aggregations indicates that a "missing variable" error would be returned. Are optional parameters supported?

ujibang commented 3 years ago

I assume that for optional parameter you mean a parameter with a default value, i.e. if not explicitly set via qparam it gets a pre-defined values.

You can achieve this with an Interceptor. Follows an example (I have not tested it)

@RegisterPlugin(name = "defaultAggregationVariable",
    interceptPoint = InterceptPoint.REQUEST_AFTER_AUTH,
    description = "sets the default avar myVar if missing")
public class DefaultAggregationVariable implements MongoInterceptor {
    @Override
    public void handle(MongoRequest request, MongoResponse response) throws Exception {
        var avars = request.getAggreationVars();

        var defaultValue = BsonBoolean.TRUE;

        if (!avars.containsKey("myVar")) {
            avars.put("myVar", defaultValue);
        }
    }

    @Override
    public boolean resolve(MongoRequest request, MongoResponse response) {
        return "/coll/_aggrs/myaggr".equals(request.getPath());
    }
}
StephenOTT commented 3 years ago

Okay. Thanks. plugin option works. I was originally looking for something that was focused on configuration at runtime when admins define aggregations. 👍