Response.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Collection from './Collection';
  2. export default class Response {
  3. #collection;
  4. #document;
  5. #parser;
  6. #getTag = (doc: Element, tag: string) => doc.getElementsByTagName(tag)[0];
  7. #getTagContent = (doc: Element, tag) => {
  8. const node = this.#getTag(doc, tag);
  9. return node ? node.textContent : '';
  10. };
  11. constructor(rawDocument: string, parser: DOMParser = 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(
  19. this.#document.getElementsByTagName('D:response')
  20. ),
  21. {
  22. sortDirectoriesFirst,
  23. }
  24. );
  25. }
  26. return this.#collection;
  27. }
  28. responseToPrimitives(responses: HTMLCollection) {
  29. return Array.from(responses).map((response) => ({
  30. directory: !!this.#getTag(response, 'D:collection'),
  31. fullPath: this.#getTagContent(response, 'D:href'),
  32. modified: Date.parse(
  33. this.#getTagContent(response, 'lp1:getlastmodified')
  34. ),
  35. size: parseInt(this.#getTagContent(response, 'lp1:getcontentlength'), 10),
  36. mimeType: this.#getTagContent(response, 'D:getcontenttype'),
  37. }));
  38. }
  39. }