Skip to content

Commit

Permalink
feat: add expected server response type option (#338)
Browse files Browse the repository at this point in the history
* refactor(ajax): do not insert `accept` headers

* feat: add expected server response type option

* docs: add `responseType`

* chore: update examples
  • Loading branch information
kukhariev committed Nov 11, 2021
1 parent 46880c2 commit 72cd61f
Show file tree
Hide file tree
Showing 8 changed files with 23 additions and 17 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ export class AppHomeComponent {
- `endpoint` URL to create new uploads. Default value: `'/upload'`
- `responseType` Expected server response type
- `headers` Headers to be appended to each HTTP request
- `metadata` Custom metadata to be added to the uploaded files
Expand Down
3 changes: 2 additions & 1 deletion src/app/tus/tus.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export class TusComponent {
metadata(file): Record<string, string> {
return { original_name: file.name };
},
retryConfig: { timeout: 60_000 }
retryConfig: { timeout: 60_000 },
responseType: 'json'
};
constructor(private authService: AuthService) {}

Expand Down
21 changes: 12 additions & 9 deletions src/uploadx/lib/ajax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { InjectionToken } from '@angular/core';
import { RequestOptions } from './interfaces';

export interface AjaxRequestConfig extends RequestOptions {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x: string]: any;

data?: BodyInit | null;
Expand Down Expand Up @@ -49,7 +48,6 @@ export class UploadxAjax {
xhr.timeout = timeout;
withCredentials && (xhr.withCredentials = true);
responseType && (xhr.responseType = responseType);
responseType === 'json' && !headers['Accept'] && (headers['Accept'] = 'application/json');
Object.keys(headers).forEach(key => xhr.setRequestHeader(key, String(headers[key])));
xhr.upload.onprogress = onUploadProgress || null;
xhr.onerror =
Expand All @@ -61,7 +59,7 @@ export class UploadxAjax {
};
xhr.onload = () => {
const response = {
data: this.getResponseBody<T>(xhr, responseType === 'json'),
data: this.getResponseBody<T>(xhr),
status: xhr.status,
headers: this.getResponseHeaders(xhr)
};
Expand All @@ -81,12 +79,17 @@ export class UploadxAjax {
}, {});
}

getResponseBody<T = string>(xhr: XMLHttpRequest, json?: boolean): T {
let body = 'response' in (xhr as XMLHttpRequest) ? xhr.response : xhr.responseText;
if (body && json && typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {}
getResponseBody<T>(xhr: XMLHttpRequest): T {
if (xhr.responseType === 'document') {
return 'response' in xhr ? xhr.response : xhr.responseXML;
}
let body = 'response' in xhr ? xhr.response : xhr.responseText;
if (xhr.responseType === 'json') {
if (body && typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {}
}
}
return body;
}
Expand Down
4 changes: 4 additions & 0 deletions src/uploadx/lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ export interface UploaderOptions extends UploadItem {
/** Adaptive chunk size limit */
maxChunkSize?: number;
withCredentials?: boolean;
/**
* Set the expected server response type
*/
responseType?: 'json' | 'text' | 'document';
/**
* Function called before every request
*/
Expand Down
4 changes: 2 additions & 2 deletions src/uploadx/lib/uploader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export abstract class Uploader implements UploadState {
retry: RetryHandler;
canceler = new Canceler();
/** Set HttpRequest responseType */
responseType?: 'json' | 'text';
responseType?: 'json' | 'text' | 'document';
private _progressEventCount = 0;
private readonly _authorize: AuthorizeRequest;
private readonly _prerequest: PreRequest;
Expand Down Expand Up @@ -194,7 +194,7 @@ export abstract class Uploader implements UploadState {
headers: { ...req.headers, ...headers },
url,
data: body,
responseType: this.responseType,
responseType: this.options.responseType ?? this.responseType,
withCredentials: !!this.options.withCredentials,
canceler: this.canceler,
validateStatus: () => true,
Expand Down
2 changes: 1 addition & 1 deletion src/uploadx/lib/uploaderx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { resolveUrl } from './utils';
* @see {@link https://developers.google.com/drive/api/v3/manage-uploads#resumable|Google Drive API documentation}
*/
export class UploaderX extends Uploader {
responseType = 'json' as 'json';
responseType = 'json' as const;

async getFileUrl(): Promise<string> {
const headers = {
Expand Down
2 changes: 0 additions & 2 deletions uploader-examples/multipart-form-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import { resolveUrl, Uploader } from 'ngx-uploadx';
* };
*/
export class MultiPartFormData extends Uploader {
responseType = 'json' as 'json';

async getFileUrl(): Promise<string> {
this.offset = 0;
const formData: FormData = new FormData();
Expand Down
2 changes: 0 additions & 2 deletions uploader-examples/multipart-multer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import { Uploader } from 'ngx-uploadx';
* };
*/
export class Multer extends Uploader {
responseType = 'json' as 'json';

async getFileUrl(): Promise<string> {
this.offset = 0;
const formData: FormData = new FormData();
Expand Down

0 comments on commit 72cd61f

Please sign in to comment.