Skip to content

Commit

Permalink
fix: avoid creating new sessions unless necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
dgreif committed Jul 15, 2019
1 parent 5a5220d commit 7b76147
Showing 1 changed file with 7 additions and 17 deletions.
24 changes: 7 additions & 17 deletions api/rest-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const ringErrorCodes: { [code: number]: string } = {
7063: 'MAINTENANCE'
},
clientApiBaseUrl = 'https://api.ring.com/clients_api/',
apiVersion = 11
apiVersion = 11,
hardwareId = generateRandomId()

export function clientApi(path: string) {
return clientApiBaseUrl + path
Expand Down Expand Up @@ -52,10 +53,6 @@ async function requestWithRetry<T>(
}
}

interface Session {
hardwareId: string
}

export interface EmailAuth {
email: string
password: string
Expand Down Expand Up @@ -159,12 +156,8 @@ export class RingRestClient {
}
}

private async fetchNewSession(
authToken: AuthTokenResponse
): Promise<Session> {
const hardwareId = generateRandomId()

await requestWithRetry<SessionResponse>({
private fetchNewSession(authToken: AuthTokenResponse) {
return requestWithRetry<SessionResponse>({
url: clientApi('session'),
data: {
device: {
Expand All @@ -181,11 +174,9 @@ export class RingRestClient {
'content-type': 'application/json'
}
})

return { hardwareId }
}

getSession(): Promise<Session> {
getSession(): Promise<SessionResponse> {
return this.authPromise.then(async authToken => {
try {
return await this.fetchNewSession(authToken)
Expand All @@ -209,7 +200,6 @@ export class RingRestClient {

private refreshAuth() {
this.authPromise = this.getAuthToken()
this.refreshSession()
}

private refreshSession() {
Expand All @@ -223,15 +213,15 @@ export class RingRestClient {
json?: boolean
responseType?: ResponseType
}): Promise<T & ExtendedResponse> {
await this.sessionPromise
const { method, url, data, json, responseType } = options,
authTokenResponse = await this.authPromise,
session = await this.sessionPromise,
headers: { [key: string]: string } = {
'content-type': json
? 'application/json'
: 'application/x-www-form-urlencoded',
authorization: `Bearer ${authTokenResponse.access_token}`,
hardware_id: session.hardwareId
hardware_id: hardwareId
}

try {
Expand Down

0 comments on commit 7b76147

Please sign in to comment.