registerRoute method

void registerRoute(
  1. String method,
  2. String route,
  3. Schema? schema,
  4. FutureOr<Response> action(
    1. Request req
    ),
)

Registers an action in this objects REST server (service) by the given method and route.

  • method the HTTP method of the route.
  • route the route to register in this object's REST server (service).
  • schema the schema to use for parameter validation.
  • action the action to perform at the given route.

Implementation

void registerRoute(String method, String route, Schema? schema,
    FutureOr<Response> Function(Request req) action) {
  if (_app == null) {
    throw ApplicationException('', 'NOT_OPENED', 'Can\'t add route');
  }

  method = method.toUpperCase();
  if (method == 'DEL') method = 'DELETE';

  route = _fixRoute(route);

  var actionCurl = (Request req) async {
    // Perform validation
    if (schema != null) {
      var params = <dynamic, dynamic>{};

      // query parameters
      req.url.queryParameters.forEach((key, value) {
        params.addAll({key: value});
      });

      // route parameters
      req.params.forEach((key, value) {
        params.addAll({key: value});
      });

      if (req.headers.containsKey('Content-Type')) {
        var body = await req.readAsString();
        var mapBody = body.isNotEmpty ? json.decode(body) : {};
        params.addAll({'body': mapBody});
        req = req.change(body: body);
      }

      var correlationId = getCorrelationId(req);
      var err =
          schema.validateAndReturnException(correlationId, params, false);
      if (err != null) {
        return HttpResponseSender.sendError(req, err);
      }
    }
    return await action(req);
  };
  _app!.add(method, route, actionCurl);
}