Remvoe static create method, update webdav methods signatures, change Config props...
[arvados-workbench2.git] / src / common / webdav.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 export class WebDAV {
6
7     defaults: WebDAVDefaults = {
8         baseURL: '',
9         headers: {},
10     };
11
12     constructor(config?: Partial<WebDAVDefaults>, private createRequest = () => new XMLHttpRequest()) {
13         if (config) {
14             this.defaults = { ...this.defaults, ...config };
15         }
16     }
17
18     propfind = (url: string, config: WebDAVRequestConfig = {}) =>
19         this.request({
20             ...config, url,
21             method: 'PROPFIND'
22         })
23
24     put = (url: string, data?: any, config: WebDAVRequestConfig = {}) =>
25         this.request({
26             ...config, url,
27             method: 'PUT',
28             data,
29         })
30
31     copy = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
32         this.request({
33             ...config, url,
34             method: 'COPY',
35             headers: { ...config.headers, Destination: this.defaults.baseURL + destination }
36         })
37
38     move = (url: string, destination: string, config: WebDAVRequestConfig = {}) =>
39         this.request({
40             ...config, url,
41             method: 'MOVE',
42             headers: { ...config.headers, Destination: this.defaults.baseURL + destination }
43         })
44
45     delete = (url: string, config: WebDAVRequestConfig = {}) =>
46         this.request({
47             ...config, url,
48             method: 'DELETE'
49         })
50
51
52     private request = (config: RequestConfig) => {
53         return new Promise<XMLHttpRequest>((resolve, reject) => {
54             const r = this.createRequest();
55             r.open(config.method, this.defaults.baseURL + config.url);
56
57             const headers = { ...this.defaults.headers, ...config.headers };
58             Object
59                 .keys(headers)
60                 .forEach(key => r.setRequestHeader(key, headers[key]));
61
62             if (config.onProgress) {
63                 r.addEventListener('progress', config.onProgress);
64             }
65
66             r.addEventListener('load', () => resolve(r));
67             r.addEventListener('error', () => reject(r));
68
69             r.send(config.data);
70         });
71
72     }
73 }
74 export interface WebDAVRequestConfig {
75     headers?: {
76         [key: string]: string;
77     };
78     onProgress?: (event: ProgressEvent) => void;
79 }
80
81 interface WebDAVDefaults {
82     baseURL: string;
83     headers: { [key: string]: string };
84 }
85
86 interface RequestConfig {
87     method: string;
88     url: string;
89     headers?: { [key: string]: string };
90     data?: any;
91     onProgress?: (event: ProgressEvent) => void;
92 }