Bodies.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/PromiseReaction.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  9. #include <LibWeb/WebIDL/Promise.h>
  10. namespace Web::Fetch::Infrastructure {
  11. Body::Body(JS::Handle<Streams::ReadableStream> stream)
  12. : m_stream(move(stream))
  13. {
  14. }
  15. Body::Body(JS::Handle<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
  16. : m_stream(move(stream))
  17. , m_source(move(source))
  18. , m_length(move(length))
  19. {
  20. }
  21. // https://fetch.spec.whatwg.org/#concept-body-clone
  22. WebIDL::ExceptionOr<Body> Body::clone() const
  23. {
  24. // To clone a body body, run these steps:
  25. auto& vm = Bindings::main_thread_vm();
  26. auto& realm = *vm.current_realm();
  27. auto& window = verify_cast<HTML::Window>(realm.global_object());
  28. // FIXME: 1. Let « out1, out2 » be the result of teeing body’s stream.
  29. // FIXME: 2. Set body’s stream to out1.
  30. auto* out2 = vm.heap().allocate<Streams::ReadableStream>(realm, window);
  31. // 3. Return a body whose stream is out2 and other members are copied from body.
  32. return Body { JS::make_handle(out2), m_source, m_length };
  33. }
  34. // https://fetch.spec.whatwg.org/#fully-reading-body-as-promise
  35. JS::PromiseCapability Body::fully_read_as_promise() const
  36. {
  37. auto& vm = Bindings::main_thread_vm();
  38. auto& realm = *vm.current_realm();
  39. // FIXME: Implement the streams spec - this is completely made up for now :^)
  40. if (auto const* byte_buffer = m_source.get_pointer<ByteBuffer>()) {
  41. auto result = String::copy(*byte_buffer);
  42. return WebIDL::create_resolved_promise(realm, JS::js_string(vm, move(result)));
  43. }
  44. // Empty, Blob, FormData
  45. return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv));
  46. }
  47. }