-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdk.template.ts
185 lines (162 loc) · 4.75 KB
/
sdk.template.ts
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import crypto from 'crypto'
import fetch from 'cross-fetch'
import { Events } from './WebhookTypes'
const skipped_env = ['local', 'test']
type GraphQLError = {
message: string
path: string[]
extensions?: { code?: string }
}
type Request<key extends string | number | symbol> = {
query: string
operationName: key
variables: Record<string, unknown>
}
/**
* Types for webhook events
*/
export type WebhookEvent<T extends keyof Events> = {
/** ISODate of the timestamp of the request */
timestamp: string
/** Name of the event being received */
name: Events[T]['name']
/** Data of the event being received */
payload: Events[T]
}
class AuthenticationError extends Error {
constructor(message: string) {
super(message)
this.name = 'AuthenticationError'
}
}
class UnexpectedError extends Error {
data: unknown
constructor(message: string, data: unknown) {
super(message)
this.name = 'AuthenticationError'
this.data = data
}
}
class OperationError extends Error {
errors: GraphQLError[]
constructor(errors: GraphQLError[]) {
super(errors[0].message)
this.name = 'OperationError'
this.errors = errors
}
}
export class Firesquad {
private apiUrl: string
private apiId: string
private apiKey: string
private token: string
/**
* Creates a Firesquad SDK Instance.
* @param apiUrl Root URL assigned to your account.
* @param apiId ID of the integration.
* @param apiKey API Secret to authenticate.
*/
constructor(apiUrl: string, apiId: string, apiKey: string) {
if (
!skipped_env.includes(process.env.NODE_ENV) &&
!apiUrl.startsWith('https://')
)
throw new Error('Incorrect protocol, API URL should start with https://')
this.apiUrl = apiUrl
this.apiId = apiId
this.apiKey = apiKey
}
/**
* This signs an authentication payload, used to validate your authentication
* with our API without transmitting your token, exchanging it to a short-timed JWT.
* If you're receiving websocket, use this to validate your `x-signature-sha-256` header against your secret.
* @param secret - payload to sign.
* @param payload - payload to sign.
* @returns SHA-256 signature of the payload.
*/
public signPayload(secret: string, payload: string) {
return crypto.createHmac('sha256', secret).update(payload).digest('hex')
}
/**
* Retrieves a fresh token from the API.
* @returns - A new token
*/
private async refreshToken() {
const body = JSON.stringify({
api_id: this.apiId,
timestamp: new Date().toISOString(),
})
try {
const res = await fetch(`${this.apiUrl}/auth`, {
method: 'POST',
body,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'x-signature-sha-256': this.signPayload(this.apiKey, body),
},
})
if (res.ok) {
const data = await res.json()
this.token = data.token
return this.token
}
if (res.status === 400)
throw new AuthenticationError(`Incorrect credentials.`)
throw new UnexpectedError(`Failed to exchange token`, {
res,
json: await res.json(),
})
} catch (e) {
if (e.data) throw e
throw new UnexpectedError(`Failed to exchange token`, { error: e })
}
}
/**
* Returns a local token if not expired.
* @returns - String token
*/
private async getToken() {
try {
if (this.token) {
const date = Date.now() - 500
const token = JSON.parse(
Buffer.from(this.token.split('.')[1], 'base64').toString('utf-8')
)
return !token || date >= token.exp * 1000
? await this.refreshToken()
: this.token
}
return await this.refreshToken()
} catch (e) {
return await this.refreshToken()
}
}
/**
* This is a generic method to run requests to our GraphQL API.
* If the default methods does not match your needs, you can use this method to run your own requests.
* @param request - Request to send to the API.
* @returns - Response from the API.
*/
public async doRequest<key extends keyof res, res = Record<key, unknown>>(
request: Request<key>
): Promise<res[key]> {
const req = await fetch(`${this.apiUrl}/graphql`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${await this.getToken()}`,
},
body: JSON.stringify({
query: request.query,
variables: request.variables,
operationName: request.operationName,
}),
})
const { data, errors } = await req.json()
if (errors) throw new OperationError(errors)
return data?.[request.operationName]
}
/* $REPLACE$ */
}