serve method Null safety

Future<void> serve()

Implementation

Future<void> serve() async {
  //API header middleware
  //Enable only if API protected mode is true in env variables
  if (protectedMode == true) {
    _httpServer.all(
      '*',
      (req, res) {
        if (req.headers.value('X-RapidAPI-Proxy-Secret') !=
            Platform.environment['RAPID_API_SECRET']!) {
          throw AlfredException(
            401,
            {'error': 'You are not authorized to perform this operation'},
          );
        }
      },
    );
  }

  /// price endpoint
  ///
  /// Returns JSON with price data for the hour that matches the timestamp in the given zone.
  /// Returned "time" object is  l o c a l time in the given zone.
  ///
  /// Parameter 1:
  /// int - timestamp: in s e c o n d s unix time U T C
  /// if timestamp is 0, current local time for the zone will be used
  ///
  /// Parameter 2:
  /// String - zone: either peninsular, canarias, baleares, ceuta or melilla

  _httpServer.get(
    '/price/:timestamp:int/:zone:[a-z]+',
    (req, res) async {
      final zone = _convertStringToZone(req.params['zone']);
      final timestamp = _parseDateTime(req.params['timestamp']);
      final timeNow = _getTimeForZone(zone, timestamp);

      final prices = PriceWatcher().prices;
      await res.json(
        prices
            .firstWhere(
              (element) =>
                  element.time.hour == timeNow.hour &&
                  element.time.day == timeNow.day &&
                  element.zone == zone,
              orElse: () => throw notInSetException,
            )
            .toMap(),
      );
    },
  );

  /// price-average endpoint
  ///
  /// Returns JSON with price average for the day that matches the timestamp in the given zone.
  /// Returned "time" object is l o c a l time in the given zone.
  ///
  /// Parameter 1:
  /// int - timestamp: in s e c o n d s unix time U T C
  /// if timestamp is 0, current local time for the zone will be used
  /// Parameter 2:
  /// String - zone: either peninsular, canarias, baleares, ceuta or melilla
  ///

  _httpServer.get(
    '/price-average/:timestamp:int/:zone:[a-z]+',
    (req, res) async {
      final zone = _convertStringToZone(req.params['zone']);
      final timestamp = _parseDateTime(req.params['timestamp']);
      final timeNow = _getTimeForZone(zone, timestamp);

      final priceAverages = PriceWatcher().priceAverages;
      await res.json(
        priceAverages
            .firstWhere(
              (element) =>
                  element.time.day == timeNow.day && element.zone == zone,
              orElse: () => throw notInSetException,
            )
            .toMap(),
      );
    },
  );

  /// price-daily endpoint
  ///
  /// Returns JSON with price data for the day that matches the timestamp in the given zone.
  /// Returned "time" object is  l o c a l time in the given zone.
  ///
  /// Parameter 1:
  /// int - timestamp: in s e c o n d s unix time U T C
  /// if timestamp is 0, current day for the zone will be used
  ///
  /// Parameter 2:
  /// String - zone: either peninsular, canarias, baleares, ceuta or melilla

  _httpServer.get(
    '/price-daily/:timestamp:int/:zone:[a-z]+',
    (req, res) async {
      final zone = _convertStringToZone(req.params['zone']);
      final timestamp = _parseDateTime(req.params['timestamp']);
      final timeNow = _getTimeForZone(zone, timestamp);

      final prices = PriceWatcher().prices;
      final result = prices.where(
        (element) => element.time.day == timeNow.day && element.zone == zone,
      );
      if (result.isEmpty) {
        throw notInSetException;
      }

      await res.json(result.map((e) => e.toMap()).toList());
    },
  );

  final server = await _httpServer.listen(
    int.parse(Platform.environment['HTTP_PORT']!),
  );
  _logger.i('http_server: Listening on ${server.port}');
}