handler method

  1. @override
Future<Response> handler()
override

Must be implemented

Implementation

@override
Future<Response> handler() async => checkApiSecret(request).fold(
      (errorResponse) => errorResponse,
      (_) async {
        if (request.requestedUri.path.contains('change_driver_district')) {
          final body = jsonDecode(await request.readAsString());
          final event = HasuraEvent.fromJson(body['event']);

          final operation = event.operationType;
          late String districtId;

          final switcher = Switcher<String, Future<void>>(operation);

          switcher
            ..when('INSERT', () {
              districtId = event.data.current!['districtId'];
              return repository.upsertDistrictScheduleInCRM(districtId);
            })
            ..when('UPDATE', () {
              districtId = event.data.current!['districtId'];
              return repository.upsertDistrictScheduleInCRM(districtId);
            })
            ..when('DELETE', () {
              districtId = event.data.old!['districtId'];
              return repository.deleteDistrictScheduleInCRM(districtId);
            });

          try {
            await switcher.result();
            return Response.ok(
              '{"districtId":"$districtId", "operation": "schedule $operation"}',
            );
          } catch (e) {
            return Response.forbidden('Error: ${e.toString()}');
          }
        } else {
          return Response.notModified();
        }
      },
    );