Skip to content

Commit

Permalink
feat: add SupabaseFunctionsShelf
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinzent03 committed Apr 17, 2023
1 parent 971227c commit c405e74
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
58 changes: 58 additions & 0 deletions packages/supabase_functions/lib/supabase_functions_shelf.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import 'dart:js_util' as js_util;

import 'package:edge_runtime/edge_runtime.dart';
import 'package:edge_runtime/src/interop/promise_interop.dart';
import 'package:edge_runtime/src/response.dart';
import 'package:js/js.dart';
import 'package:js_bindings/js_bindings.dart' as interop;
import 'package:shelf/shelf.dart' as shelf;

export 'package:deno_deploy/deno_deploy.dart' hide Response;

@JS('__dartSupabaseFetchHandler')
external set __dartSupabaseFetchHandler(
Promise<interop.Response> Function(interop.Request req) f);

class SupabaseFunctionsShelf {
final FutureOr<shelf.Response> Function(shelf.Request request)? fetch;

SupabaseFunctionsShelf({
this.fetch,
}) {
// Setup the runtime environment.
setupRuntime();

if (fetch != null) {
__dartSupabaseFetchHandler = allowInterop((interop.Request request) {
return futureToPromise(Future(() async {
final clone = request.clone();
final Map<String, String> headers = {};

js_util.callMethod(request.headers, 'forEach', [
allowInterop((value, key, _) {
headers[key] = value;
})
]);

// Remove the first path segment, because it starts with `dart_edge/<actual-sub-path>`.
var uri = Uri.parse(clone.url);
uri = uri.replace(pathSegments: uri.pathSegments.skip(1));

final shelfRequest = shelf.Request(
clone.method,
uri,
body: clone.body,
headers: headers,
);
final response = await fetch!(shelfRequest);

return Response(
await response.readAsString(),
status: response.statusCode,
headers: Headers(response.headers),
).delegate;
}));
});
}
}
}
1 change: 1 addition & 0 deletions packages/supabase_functions/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dependencies:
edge_runtime: ^0.0.4+1
js_bindings: ^0.1.0
js: ^0.6.5
shelf: ^1.4.0

dev_dependencies:
lints: ^2.0.0
Expand Down

0 comments on commit c405e74

Please sign in to comment.