-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathyoupin-api.js
88 lines (80 loc) · 2.27 KB
/
youpin-api.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const request = require('superagent');
const feathers = require('feathers/client');
const rest = require('feathers-rest/client');
const hooks = require('feathers-hooks');
const authentication = require('feathers-authentication/client');
class Api {
// initialise api and do authentication
constructor(uri, username, password) {
this.uri = uri;
this.token = null;
this.username = username;
this.password = password;
const app = feathers()
.configure(hooks())
.configure(rest(uri).superagent(request))
.configure(authentication());
setInterval(() => {
Api.refreshToken();
}, 23 * 60 * 60000); // Refresh token every 23 hours
return new Promise((resolve, reject) => {
app.authenticate({
type: 'local',
email: username,
password: password, //eslint-disable-line object-shorthand
}).then(() => {
this.token = app.get('token');
resolve(this);
}).catch(error => {
console.log(error);
reject(error);
});
});
}
refreshToken() {
// TO-DO: Call /token/auth/refresh instead
const app = feathers()
.configure(hooks())
.configure(rest(this.uri).superagent(request))
.configure(authentication());
app.authenticate({
type: 'local',
email: this.username,
password: this.password,
}).then(() => {
this.token = app.get('token');
}).catch((error) => {
console.log(error);
});
}
postPin(json, callback) {
request
.post(`${this.uri}/pins`)
.set('Authorization', `Bearer ${this.token}`)
.send(json)
.end((error, response) => {
if (!error && response.ok) {
callback(response.body);
} else {
console.error('Unable to post a new pin.');
console.error(response);
console.error(error);
}
});
}
uploadPhotoFromURL(imgLink, callback) {
request
.post(`${this.uri}/photos/upload_from_url`)
.send({ url: imgLink })
.end((error, response) => {
if (!error && response.ok) {
callback(response.body);
} else {
console.error('Unable to upload a new photo.');
console.error(response);
console.error(error);
}
});
}
}
module.exports = Api;