Response.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Collection from './Collection';
  2. export default class Response {
  3. #collection;
  4. #document;
  5. #parser;
  6. #getTag = (doc, tag) => doc.querySelector(tag);
  7. #getTagContent = (doc, tag) => {
  8. const node = this.#getTag(doc, tag);
  9. return node ? node.textContent : '';
  10. };
  11. constructor(rawDocument, parser = new DOMParser()) {
  12. this.#parser = parser;
  13. this.#document = parser.parseFromString(rawDocument, 'application/xml');
  14. }
  15. collection({ sortDirectoriesFirst = false } = {}) {
  16. if (!this.#collection) {
  17. this.#collection = new Collection(
  18. this.responseToPrimitives(this.#document.querySelectorAll('response')),
  19. {
  20. sortDirectoriesFirst,
  21. }
  22. );
  23. }
  24. return this.#collection;
  25. }
  26. responseToPrimitives(responses) {
  27. return Array.from(responses).map((response) => ({
  28. directory: !!this.#getTag(response, 'collection'),
  29. fullPath: this.#getTagContent(response, 'href'),
  30. modified: Date.parse(this.#getTagContent(response, 'getlastmodified')),
  31. size: parseInt(this.#getTagContent(response, 'getcontentlength'), 10),
  32. mimeType: this.#getTagContent(response, 'getcontenttype'),
  33. }));
  34. }
  35. }