This repository was archived by the owner on Sep 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
108 lines (94 loc) · 2.67 KB
/
Copy pathindex.js
File metadata and controls
108 lines (94 loc) · 2.67 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const ClientOAuth2 = require('client-oauth2')
const Request = require('request')
const PackageJson = require('./package.json')
class Environment {
static SANDBOX () {
return {
baseUrl: 'https://api.sandbox.stuart.com'
}
}
static PRODUCTION () {
return {
baseUrl: 'https://api.stuart.com'
}
}
}
class Authenticator {
constructor (environment, apiClientId, apiClientSecret) {
this.environment = environment
this.oauthClient = new ClientOAuth2({
clientId: apiClientId,
clientSecret: apiClientSecret,
accessTokenUri: environment.baseUrl + '/oauth/token'
})
}
getAccessToken () {
return new Promise((resolve, reject) => {
if (this.accessToken != null && !this.accessToken.expired()) {
resolve(this.accessToken.accessToken)
} else {
this.oauthClient.credentials.getToken().then((accessToken) => {
this.accessToken = accessToken
resolve(this.accessToken.accessToken)
}).catch(error => { reject(error) })
}
})
}
}
class ApiResponse {
constructor (statusCode, body, headers) {
this.statusCode = statusCode
this.body = body
this.headers = headers
}
success () {
return this.statusCode >= 200 && this.statusCode < 300
}
}
class HttpClient {
constructor (authenticator) {
this.authenticator = authenticator
}
performGet (resource, params) {
return new Promise((resolve, reject) => {
this.authenticator.getAccessToken().then((accessToken) => {
let options = {
url: this.url(resource),
headers: this.defaultHeaders(accessToken)
}
if (params) options.qs = params
Request.get(options, (err, res) => resolve(
new ApiResponse(res.statusCode, JSON.parse(res.body), res.headers)))
}).catch(error => { reject(error) })
})
};
performPost (resource, body) {
return new Promise((resolve, reject) => {
this.authenticator.getAccessToken().then((accessToken) => {
let options = {
url: this.url(resource),
headers: this.defaultHeaders(accessToken),
body: body
}
Request.post(options, (err, res) => resolve(
new ApiResponse(res.statusCode, JSON.parse(res.body || '{}'), res.headers)))
}).catch(error => { reject(error) })
})
};
url (resource) {
return this.authenticator.environment.baseUrl + resource
}
defaultHeaders (accessToken) {
return {
'Authorization': 'Bearer ' + accessToken,
'User-Agent': 'stuart-client-js/' + PackageJson.version,
'Content-Type': 'application/json'
}
}
}
module.exports = {
Authenticator,
Environment,
ApiResponse,
HttpClient
}