Skip to content

Commit

Permalink
Merge pull request #28 from textileio/andrew/set-session-on-start
Browse files Browse the repository at this point in the history
sessions: allow app to restart from previous session
  • Loading branch information
andrewxhill authored Feb 6, 2020
2 parents ad155dc + 21953bf commit 9254392
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
19 changes: 12 additions & 7 deletions src/ThreadsConfig.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { grpc } from '@improbable-eng/grpc-web'
import { Config } from '@textile/threads-client'
import axios, { AxiosRequestConfig } from 'axios'

type Session = {
id: string
session_id: string
}
export class ThreadsConfig extends Config {
public host: string
public session?: string
public sessionId?: string
constructor(
public token: string,
public deviceId: string,
Expand All @@ -21,7 +22,11 @@ export class ThreadsConfig extends Config {
super()
this.host = `${this.apiScheme}://${this.api}:${this.threadsPort}`
}
async start() {
async start(sessionId?: string) {
if (sessionId !== undefined) {
this.sessionId = sessionId
return
}
await this.refreshSession()
}
get sessionAPI(): string {
Expand All @@ -47,24 +52,24 @@ export class ThreadsConfig extends Config {
if (resp.status !== 200) {
new Error(resp.statusText)
}
this.session = resp.data.session_id
this.sessionId = resp.data.session_id
}
_wrapMetadata(values?: { [key: string]: any }): { [key: string]: any } | undefined {
if (!this.session) {
if (!this.sessionId) {
return values
}
const response = values ?? {}
if ('Authorization' in response || 'authorization' in response) {
return response
}
response['Authorization'] = `Bearer ${this.session}`
response['Authorization'] = `Bearer ${this.sessionId}`
return response
}
_wrapBrowserHeaders(values: grpc.Metadata): grpc.Metadata {
if (!this.session) {
if (!this.sessionId) {
return values
}
values.set('Authorization', `Bearer ${this.session}`)
values.set('Authorization', `Bearer ${this.sessionId}`)
return values
}
}
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,15 @@ export class API {
)
}

async start() {
await this._threadsConfig.start()
async start(sessionId?: string) {
await this._threadsConfig.start(sessionId)
return this
}

get sessionId(): string | undefined {
return this._threadsConfig.sessionId
}

get threadsConfig(): ThreadsConfig {
return this._threadsConfig
}
Expand Down

0 comments on commit 9254392

Please sign in to comment.