Bodies.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/PromiseCapability.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. // FIXME: 1. Let « out1, out2 » be the result of teeing body’s stream.
  28. // FIXME: 2. Set body’s stream to out1.
  29. auto* out2 = vm.heap().allocate<Streams::ReadableStream>(realm, realm);
  30. // 3. Return a body whose stream is out2 and other members are copied from body.
  31. return Body { JS::make_handle(out2), m_source, m_length };
  32. }
  33. // https://fetch.spec.whatwg.org/#fully-reading-body-as-promise
  34. JS::NonnullGCPtr<JS::PromiseCapability> Body::fully_read_as_promise() const
  35. {
  36. auto& vm = Bindings::main_thread_vm();
  37. auto& realm = *vm.current_realm();
  38. // FIXME: Implement the streams spec - this is completely made up for now :^)
  39. if (auto const* byte_buffer = m_source.get_pointer<ByteBuffer>()) {
  40. auto result = String::copy(*byte_buffer);
  41. return WebIDL::create_resolved_promise(realm, JS::js_string(vm, move(result)));
  42. }
  43. // Empty, Blob, FormData
  44. return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv));
  45. }
  46. }