Skip to content

Commit

Permalink
Split addServerPeer into smaller methods
Browse files Browse the repository at this point in the history
This change should have no functionality impact.
  • Loading branch information
EvanHahn committed Oct 9, 2024
1 parent 7cc3a1f commit bb74456
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/member-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,22 @@ export class MemberApi extends TypedEmitter {
'Base URL is invalid'
)

const { deviceId } = await this.#addServerToProject(baseUrl)

const roleId = MEMBER_ROLE_ID
await this.#roles.assignRole(deviceId, roleId)

await this.#waitForInitialSyncWithServer(
baseUrl,
dangerouslyAllowInsecureConnections
)
}

/**
* @param {string} baseUrl Server base URL. Should already be validated.
* @returns {Promise<{ deviceId: string }>}
*/
async #addServerToProject(baseUrl) {
const requestUrl = new URL('projects', baseUrl)
const requestBody = {
projectKey: encodeBufferForServer(this.#projectKey),
Expand Down Expand Up @@ -314,7 +330,6 @@ export class MemberApi extends TypedEmitter {
)
}

/** @type {string} */ let deviceId
try {
const responseBody = await response.json()
assert(
Expand All @@ -327,22 +342,31 @@ export class MemberApi extends TypedEmitter {
typeof responseBody.data.deviceId === 'string',
'Response body is valid'
)
;({ deviceId } = responseBody.data)
const { deviceId } = responseBody.data
return { deviceId }
} catch (err) {
throw new Error(
"Failed to add server peer because we couldn't parse the response"
)
}
}

const roleId = MEMBER_ROLE_ID
await this.#roles.assignRole(deviceId, roleId)

/**
* @param {string} baseUrl
* @param {boolean} dangerouslyAllowInsecureConnections
* @returns {Promise<void>}
*/
async #waitForInitialSyncWithServer(
baseUrl,
dangerouslyAllowInsecureConnections
) {
const projectPublicId = projectKeyToPublicId(this.#projectKey)
const websocketUrl = new URL('sync/' + projectPublicId, baseUrl)
websocketUrl.protocol =
dangerouslyAllowInsecureConnections && websocketUrl.protocol === 'http:'
? 'ws:'
: 'wss:'

const websocket = new WebSocket(websocketUrl)
websocket.on('error', noop)
const replicationStream = this.#getReplicationStream()
Expand Down

0 comments on commit bb74456

Please sign in to comment.