~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/models/task.ts -rw-r--r-- 1.8 KiB
5b482cfcKridsada Thanabulpong 0.30.0 3 years ago
                                                                                
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
import {Model, IModelData} from './base';
import {CancellableToken} from '../utils/cancellable';
import {ResourceError} from '../utils/errors';
import {request} from '../utils/request';


enum Statuses {
    Queued,
    Pending,
    Started,
    Retry,
    Failure,
    Success,
}


export class Task extends Model {
    type: string;
    id: string;
    path: string;
    status: Statuses;
    data: {[key: string]: any};

    serialize(data: IModelData) {
        Model.assertType(data, 'task');

        this.type = data['type'];
        this.id = data['id'];
        this.path = data['path'];
        this.data = data['data'];

        switch (data['status']) {
            case 'queued': this.status = Statuses.Queued; break;
            case 'pending': this.status = Statuses.Pending; break;
            case 'started': this.status = Statuses.Started; break;
            case 'retry': this.status = Statuses.Retry; break;
            case 'failure': this.status = Statuses.Failure; break;
            case 'success': this.status = Statuses.Success; break;
        }
    }

    static queryId(
        id: string,
        token?: CancellableToken
    ): Promise<Task> {
        return request('GET', `/api/1.0/tasks/${id}/`, {}, token).then(
            (resp: string) => {
                return new Task(JSON.parse(resp));
            }
        );
    }

    static waitFor(
        id: string,
        token?: CancellableToken
    ): Promise<Task> {
        return Task.queryId(id, token).then((task: Task) => {
            if (task.status == Statuses.Success) {
                return task;
            } else if (task.status == Statuses.Failure) {
                throw new ResourceError('Task could not be completed.');
            } else {
                return Task.waitFor(id, token);
            }
        });
    }
}