Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ApiRequest.js « Network « src - git.mdns.eu/nextcloud/passwords-client.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a4ce535fd8b2bd91d47e47056c2cff9fd12baae8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import ApiResponse from './ApiResponse';

export default class ApiRequest {

    /**
     *
     * @param {BasicPasswordsClient} api
     * @param {String} [url=null]
     * @param {Session} [session=null]
     */
    constructor(api, url = null, session = null) {
        this._api = api;
        this._url = url;
        this._path = null;
        this._data = null;
        this._method = null;
        this._userAgent = null;
        this._session = session;
        this._responseType = 'application/json';
    }

    /**
     *
     * @returns {(String|null)}
     */
    getUrl() {
        return this._url;
    }

    /**
     *
     * @param {Session} value
     * @returns {ApiRequest}
     */
    setUrl(value) {
        this._url = value;

        return this;
    }

    /**
     * @returns {Session}
     */
    getSession() {
        return this._session;
    }

    /**
     *
     * @param {Session} value
     * @returns {ApiRequest}
     */
    setSession(value) {
        this._session = value;

        return this;
    }

    /**
     *
     * @param {String} value
     * @return {ApiRequest}
     */
    setPath(value) {
        this._path = value;

        return this;
    }

    /**
     *
     * @param {Object} value
     * @return {ApiRequest}
     */
    setData(value) {
        this._data = value;

        return this;
    }

    /**
     *
     * @param {String} value
     * @return {ApiRequest}
     */
    setMethod(value) {
        this._method = value.toUpperCase();

        return this;
    }

    /**
     *
     * @param {String} value
     * @returns {ApiRequest}
     */
    setResponseType(value) {
        this._responseType = value;

        return this;
    }

    /**
     *
     * @param {String} value
     * @return {ApiRequest}
     */
    setUserAgent(value) {
        this._userAgent = value;

        return this;
    }

    /**
     *
     * @returns {Promise<ApiResponse>}
     */
    async send() {
        let options = this._getRequestOptions();
        let httpResponse = await this._executeRequest(this._url + this._path, options);
        let contentType = httpResponse.headers.get('content-type');

        let response = new ApiResponse()
            .setContentType(contentType)
            .setHeaders(httpResponse.headers)
            .setHttpStatus(httpResponse.status)
            .setHttpResponse(httpResponse);

        this._updateSessionId(httpResponse);

        if(this._responseType !== null && contentType && contentType.indexOf(this._responseType) === -1) {
            let error = this._api.getClass('exception.contenttype', this._responseType, contentType, httpResponse);
            this._api.emit('request.error', error);
            throw error;
        } else if(contentType && contentType.indexOf('application/json') !== -1) {
            await this._processJsonResponse(httpResponse, response);
        } else {
            await this._processBinaryResponse(httpResponse, response);
        }

        this._api.emit('request.after', response);

        return response;
    }

    /**
     *
     * @param httpResponse
     * @private
     */
    _updateSessionId(httpResponse) {
        if(httpResponse.headers.has('x-api-session')) {
            if(httpResponse.headers.has('cache-control') && httpResponse.headers.get('cache-control').indexOf('immutable') !== -1) return;
            if(httpResponse.headers.has('pragma') && httpResponse.headers.get('pragma') === 'cache') return;

            if(httpResponse.headers.has('date')) {
                let date = new Date(httpResponse.headers.get('date')),
                    now  = Date.now() - 300000;
                if(date.getTime() < now) return;
            }

            this._session.setId(httpResponse.headers.get('x-api-session'));
        }
    }

    /**
     *
     * @return {{redirect: string, headers: Headers, method: string, credentials: string}}
     * @private
     */
    _getRequestOptions() {
        let headers = this._getRequestHeaders();
        let method = this._method === null ? 'GET':this._method;
        let options = {method, headers, credentials: 'omit', redirect: 'error'};
        if(this._data !== null) {
            options.body = JSON.stringify(this._data);
            if(method === 'GET') options.method = 'POST';
        }

        return options;
    }

    /**
     *
     * @return {Headers}
     * @private
     */
    _getRequestHeaders() {
        let headers = new Headers();

        if(this._session.getUser() !== null) {
            headers.append('authorization', `Basic ${btoa(`${this._session.getUser()}:${this._session.getToken()}`)}`);
        } else if(this._session.getToken() !== null) {
            headers.append('authorization', `Bearer ${btoa(this._session.getToken())}`);
        }

        headers.append('accept', this._responseType);

        if(this._data !== null) {
            headers.append('content-type', 'application/json');
        }

        if(this._userAgent !== null) {
            headers.append('user-agent', this._userAgent);
        }

        if(this._session.getId() !== null) {
            headers.append('x-api-session', this._session.getId());
        }

        return headers;
    }

    /**
     *
     * @param {String} url
     * @param {Object} options
     * @returns {Promise<Response>}
     * @private
     */
    async _executeRequest(url, options) {
        try {
            let request = new Request(url, options);
            this._api.emit('request.before', request);

            return await fetch(request);
        } catch(e) {
            this._api.emit('request.error', e);
            throw e;
        }
    }

    /**
     *
     * @param {Response} httpResponse
     * @param {ApiResponse} response
     * @private
     */
    async _processJsonResponse(httpResponse, response) {
        if(!httpResponse.ok) {
            let error = this._getHttpError(httpResponse);
            this._api.emit('request.error', error);
            throw error;
        }

        try {
            let json = await httpResponse.json();
            response.setData(json);
        } catch(e) {
            let error = this._api.getClass('exception.decoding', httpResponse, e);
            this._api.emit('request.decoding.error', error);
            throw error;
        }
    }

    /**
     *
     * @param {Response} httpResponse
     * @param {ApiResponse} response
     * @private
     */
    async _processBinaryResponse(httpResponse, response) {
        if(!httpResponse.ok) {
            let error = this._getHttpError(httpResponse);
            this._api.emit('request.error', error);
            throw error;
        }

        try {
            let blob = await httpResponse.blob();
            response.setData(blob);
        } catch(e) {
            let error = this._api.getClass('exception.decoding', httpResponse, e);
            this._api.emit('request.decoding.error', error);
            throw error;
        }
    }

    /**
     *
     * @param {Response} response
     * @private
     */
    _getHttpError(response) {
        if([400, 401, 403, 404, 405, 412, 429, 500, 502, 503, 504].indexOf(response.status) !== -1) {
            return this._api.getClass(`exception.http.${response.status}`, response);
        }
        if(response.status > 99) {
            return this._api.getClass('exception.http', response);
        }

        return this._api.getClass('exception.network', response);
    }
}