~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/models/base.ts -rw-r--r-- 826 bytes
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
import {NotImplementedError, ResourceError} from '../utils/errors';


export interface IModelData {
    [key: string]: any;
}


export class Model {
    constructor(data: IModelData) {
        this.throwError(data);
        this.serialize(data);
    }

    protected serialize(data: IModelData) {
        throw new NotImplementedError;
    }

    private throwError(data: IModelData) {
        if (data['type'] == 'error') {
            throw new ResourceError(
                'An error object was returned from the API.',
                data
            );
        }
    }

    static assertType(data: IModelData, type: string) {
        if (data['type'] != type) {
            throw new ResourceError(
                `Expected ${type} type but got ${data['type']}.`,
                data
            );
        }
    }
}