import 'package:shelf/shelf.dart';

Middleware cors() {
  const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
    'Access-Control-Allow-Headers': 'Origin, Content-Type',
    'Access-Control-Max-Age': "600",
  };

  return createMiddleware(
    requestHandler: (Request request) {
      if (request.method == "OPTIONS") {
        return Response.ok('', headers: corsHeaders);
      }
      return null;
    },
    responseHandler: (Response response) {
      final headers = Map<String, String>.from(response.headers);
      headers.addEntries(corsHeaders.entries.map((e) => MapEntry(e.key, e.value)));
      return response.change(headers: headers);
    },
  );
}
