-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (51 loc) · 1.21 KB
/
index.js
File metadata and controls
63 lines (51 loc) · 1.21 KB
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
import fetch from 'isomorphic-fetch';
let clientSingleton;
export class LeftPadClient {
static API_URL = 'https://api.left-pad.io/';
constructor(apiUrl = LeftPadClient.API_URL, apiKey) {
this.apiUrl = apiUrl;
this.apiKey = apiKey;
}
leftpad(str, len, ch = ' ') {
const encoded = encodeURI(str);
const url = `${this.apiUrl}/?str=${encoded}&len=${len}&ch=${ch}`;
return fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
.then(this.processResponse)
.then(this.parseResponse)
.then(this.ensureResult)
.catch(this.processError);
}
processResponse(response) {
if (response.ok) {
return response.json();
} else {
throw new Error('Invalid response');
}
}
parseResponse(data) {
if (data.str) {
return data.str;
} else {
throw new Error('Invalid response');
}
}
ensureString(str) {
return `${str}`;
}
processError(err) {
// OMG, there's an error?!?
throw err;
}
}
const leftPadWrapper = (str, len, ch) => {
if (!clientSingleton) {
clientSingleton = new LeftPadClient();
}
return clientSingleton.leftpad(str, len, ch);
};
export default leftPadWrapper;