UNPKG

3.18 kBPlain TextView Raw
1import { ResponseParser } from "./responseparser";
2import { ResponseTemplateManager } from "./responsetemplatemanager";
3
4/**
5 * ResponseTemplate class
6 */
7export class ResponseTemplate {
8 /**
9 * plain API response
10 */
11 protected raw: string;
12 /**
13 * hash representation of plain API response
14 */
15 protected hash: any;
16
17 /**
18 * Constructor
19 * @param raw plain API response
20 */
21 public constructor(raw: string) {
22 if (!raw) {
23 raw = ResponseTemplateManager.getInstance().getTemplate("empty").getPlain();
24 }
25 this.raw = raw;
26 this.hash = ResponseParser.parse(raw);
27 if (
28 !Object.prototype.hasOwnProperty.call(this.hash, "CODE") ||
29 !Object.prototype.hasOwnProperty.call(this.hash, "DESCRIPTION")
30 ) {
31 this.raw = ResponseTemplateManager.getInstance().getTemplate("invalid").getPlain();
32 this.hash = ResponseParser.parse(this.raw);
33 }
34 }
35
36 /**
37 * Get API response code
38 * @returns API response code
39 */
40 public getCode(): number {
41 return parseInt(this.hash.CODE, 10);
42 }
43
44 /**
45 * Get API response description
46 * @returns API response description
47 */
48 public getDescription(): string {
49 return this.hash.DESCRIPTION;
50 }
51
52 /**
53 * Get Plain API response
54 * @returns Plain API response
55 */
56 public getPlain(): string {
57 return this.raw;
58 }
59
60 /**
61 * Get Queuetime of API response
62 * @returns Queuetime of API response
63 */
64 public getQueuetime(): number {
65 if (Object.prototype.hasOwnProperty.call(this.hash, "QUEUETIME")) {
66 return parseFloat(this.hash.QUEUETIME);
67 }
68 return 0.00;
69 }
70
71 /**
72 * Get API response as Hash
73 * @returns API response hash
74 */
75 public getHash(): any {
76 return this.hash;
77 }
78
79 /**
80 * Get Runtime of API response
81 * @returns Runtime of API response
82 */
83 public getRuntime(): number {
84 if (Object.prototype.hasOwnProperty.call(this.hash, "RUNTIME")) {
85 return parseFloat(this.hash.RUNTIME);
86 }
87 return 0.00;
88 }
89
90 /**
91 * Check if current API response represents an error case
92 * API response code is an 5xx code
93 * @returns boolean result
94 */
95 public isError(): boolean {
96 return this.hash.CODE.charAt(0) === "5";
97 }
98
99 /**
100 * Check if current API response represents a success case
101 * API response code is an 2xx code
102 * @returns boolean result
103 */
104 public isSuccess(): boolean {
105 return this.hash.CODE.charAt(0) === "2";
106 }
107
108 /**
109 * Check if current API response represents a temporary error case
110 * API response code is an 4xx code
111 * @returns boolean result
112 */
113 public isTmpError(): boolean {
114 return this.hash.CODE.charAt(0) === "4";
115 }
116
117 /**
118 * Check if current operation is returned as pending
119 * @returns boolean result
120 */
121 public isPending(): boolean {
122 return (Object.prototype.hasOwnProperty.call(this.hash, "PENDING") ? this.hash.PENDING === "1" : false);
123 }
124}