Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add promise support on filters #648

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions src/file-upload/file-uploader.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface Headers {

export type ParsedResponseHeaders = {[headerFieldName:string]:string};

export type FilterFunction = {name:string, fn:(item?:FileLikeObject, options?:FileUploaderOptions)=>boolean};
export type FilterFunction = {name:string, fn:(item?:FileLikeObject, options?:FileUploaderOptions)=>boolean|Promise<boolean>};

export interface FileUploaderOptions {
allowedMimeType?:Array<string>;
Expand Down Expand Up @@ -98,15 +98,15 @@ export class FileUploader {
}

let temp = new FileLikeObject(some);
if (this._isValidFile(temp, arrayOfFilters, options)) {
this._isValidFile(temp, arrayOfFilters, options).then(() => {
let fileItem = new FileItem(this, some, options);
addedFileItems.push(fileItem);
this.queue.push(fileItem);
this._onAfterAddingFile(fileItem);
} else {
}).catch(() => {
let filter = arrayOfFilters[this._failFilterIndex];
this._onWhenAddingFileFailed(temp, filter, options);
}
});
});
if (this.queue.length !== count) {
this._onAfterAddingAll(addedFileItems);
Expand Down Expand Up @@ -400,11 +400,27 @@ export class FileUploader {
return this.options.queueLimit === undefined || this.queue.length < this.options.queueLimit;
}

protected _isValidFile(file:FileLikeObject, filters:FilterFunction[], options:FileUploaderOptions):boolean {
protected _isValidFile(file:FileLikeObject, filters:FilterFunction[], options:FileUploaderOptions): Promise<boolean> {
if (!filters.length) {
return Promise.resolve(true);
}

this._failFilterIndex = -1;
return !filters.length ? true : filters.every((filter:FilterFunction) => {
this._failFilterIndex++;
return filter.fn.call(this, file, options);

return Promise.all(
filters.map((filter: FilterFunction) => {
const isValid: boolean = filter.fn.call(this, file, options);

return Promise.resolve(isValid);
})
).then((values) => {
const isValid = values.every((value: boolean) => {
this._failFilterIndex++;

return value;
})

return isValid ? Promise.resolve(isValid) : Promise.reject(isValid);
});
}

Expand Down