|
| 1 | +import 'dart:js_util' as js_util; |
| 2 | + |
| 3 | +import 'package:edge_runtime/edge_runtime.dart'; |
| 4 | +import 'package:edge_runtime/src/interop/promise_interop.dart'; |
| 5 | +import 'package:edge_runtime/src/response.dart'; |
| 6 | +import 'package:js/js.dart'; |
| 7 | +import 'package:js_bindings/js_bindings.dart' as interop; |
| 8 | +import 'package:shelf/shelf.dart' as shelf; |
| 9 | + |
| 10 | +export 'package:deno_deploy/deno_deploy.dart' hide Response; |
| 11 | + |
| 12 | +@JS('__dartSupabaseFetchHandler') |
| 13 | +external set __dartSupabaseFetchHandler( |
| 14 | + Promise<interop.Response> Function(interop.Request req) f); |
| 15 | + |
| 16 | +class SupabaseFunctionsShelf { |
| 17 | + final FutureOr<shelf.Response> Function(shelf.Request request)? fetch; |
| 18 | + |
| 19 | + SupabaseFunctionsShelf({ |
| 20 | + this.fetch, |
| 21 | + }) { |
| 22 | + // Setup the runtime environment. |
| 23 | + setupRuntime(); |
| 24 | + |
| 25 | + if (fetch != null) { |
| 26 | + __dartSupabaseFetchHandler = allowInterop((interop.Request request) { |
| 27 | + return futureToPromise(Future(() async { |
| 28 | + final clone = request.clone(); |
| 29 | + final Map<String, String> headers = {}; |
| 30 | + |
| 31 | + js_util.callMethod(request.headers, 'forEach', [ |
| 32 | + allowInterop((value, key, _) { |
| 33 | + headers[key] = value; |
| 34 | + }) |
| 35 | + ]); |
| 36 | + |
| 37 | + // Remove the first path segment, because it starts with `dart_edge/<actual-sub-path>`. |
| 38 | + var uri = Uri.parse(clone.url); |
| 39 | + uri = uri.replace(pathSegments: uri.pathSegments.skip(1)); |
| 40 | + |
| 41 | + final shelfRequest = shelf.Request( |
| 42 | + clone.method, |
| 43 | + uri, |
| 44 | + body: clone.body, |
| 45 | + headers: headers, |
| 46 | + ); |
| 47 | + final response = await fetch!(shelfRequest); |
| 48 | + |
| 49 | + return Response( |
| 50 | + await response.readAsString(), |
| 51 | + status: response.statusCode, |
| 52 | + headers: Headers(response.headers), |
| 53 | + ).delegate; |
| 54 | + })); |
| 55 | + }); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments