This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
forked from daniellockard/tiltify-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
162 lines (143 loc) · 4.43 KB
/
index.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/**
* This callback type is called `requestCallback` and is displayed as a global symbol.
*
* @callback requestCallback
* @param {object} data the data returned from the endpoint
*/
const fetch = require('node-fetch')
const Campaign = require('./lib/campaign')
const Cause = require('./lib/cause')
const FundraisingEvents = require('./lib/fundraisingEvents')
const Team = require('./lib/team')
const User = require('./lib/user')
class TiltifyClient {
/**
* A TiltifyClient contains all of the sub-types that exist on the Tiltify API
* @param {string} clientId - from https://app.tiltify.com/account/connected-accounts/oauth-applications
* @param {string} clientSecret - from https://app.tiltify.com/account/connected-accounts/oauth-applications
* @constructor
*/
constructor (clientId, clientSecret) {
this.clientId = clientId
this.clientSecret = clientSecret
/**
* this.Campaigns is used to get info about campaigns
* @type Campaign
*/
this.Campaigns = new Campaign(this)
/**
* this.Causes is used to get info about causes
* @type Cause
*/
this.Causes = new Cause(this)
/**
* this.FundraisingEvents is used to get info about fundraising events
* @type FundraisingEvents
*/
this.FundraisingEvents = new FundraisingEvents(this)
/**
* this.Team is used to get info about a team
* @type Team
*/
this.Team = new Team(this)
/**
* this.User is used to get info about a user
* @type User
*/
this.User = new User(this)
}
unsupported () {
throw new TiltifyError({
message: 'This API is no longer available in Tiltify API v5',
status: 410
})
}
notFound () {
throw new TiltifyError({
message: 'Not Found',
status: 404
})
}
async _fetch (url, options) {
try {
const response = await fetch(url, options)
return await response.json()
} catch (error) {
throw new Error(error.message)
}
}
async _getToken () {
const url = 'https://v5api.tiltify.com/oauth/token?' +
`client_id=${this.clientId}&` +
`client_secret=${this.clientSecret}&` +
'grant_type=client_credentials&scope=public'
const json = await this._fetch(url, { method: 'POST' })
if (json.error) throw new TiltifyError(json)
return {
accessToken: json.access_token,
expiresAt: Date.parse(json.created_at) + (json.expires_in * 1000)
}
}
async _rawRequest (route, parameters, reattempt = true) {
if (!this.token || Date.now() > this.token.expiresAt) {
this.token = await this._getToken()
}
let path = `https://v5api.tiltify.com/api/public/${route}`
const pathParameters = {}
const pathParameterRegex = /{([^}]+)}/g // match {parameter}
for (const [trigger, key] of route.matchAll(pathParameterRegex)) {
if (parameters[key] === undefined) {
throw new Error(`missing path parameter ${key} for ${route}`)
}
path = path.replace(trigger, encodeURIComponent(parameters[key]))
pathParameters[key] = true
}
const queryString = Object.entries(parameters)
.filter(arr => !pathParameters[arr[0]])
.map(arr => `${encodeURIComponent(arr[0])}=${encodeURIComponent(arr[1])}`)
.join('&')
if (queryString) {
path += `?${queryString}`
}
const json = await this._fetch(path, {
headers: {
Authorization: `Bearer ${this.token.accessToken}`
}
})
if (json.error) {
if (json.error.status === 401 && reattempt) {
this.token = null
return this._rawRequest(path, parameters, false)
}
throw new TiltifyError(json)
}
return json
}
async _sendRequest (route, callback, parameters, enumerate=true) {
function end (result) {
if (callback) callback(result)
return result
}
let data; let metadata; const results = []
while (true) {
if (metadata?.after) {
parameters.after = metadata.after
parameters.limit = 100
}
({ data, metadata } = await this._rawRequest(route, parameters))
if (!Array.isArray(data) || !enumerate) return end(data)
results.push(...data)
if (data.length === 0 || !metadata?.after) return end(results)
}
}
}
class TiltifyError extends Error {
constructor (json) {
super(json.error.message)
this.name = 'TiltifyError'
for (const key in json.error) {
this[key] = json.error[key]
}
}
}
module.exports = TiltifyClient