Skip to content

Commit

Permalink
examples: update gatekeeper client to use the new API.
Browse files Browse the repository at this point in the history
  • Loading branch information
thruflo committed Nov 19, 2024
1 parent 33fd386 commit c97c8ce
Showing 1 changed file with 33 additions and 33 deletions.
66 changes: 33 additions & 33 deletions examples/gatekeeper-auth/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,47 @@ interface Definition {
columns?: string
}

async function fetchShapeOptions(definition: Definition, offset: string) {
const { table, ...params} = definition

const qs = new URLSearchParams({offset, ...params}).toString()
const url = `${API_URL}/gatekeeper/${table}?${qs}`

const resp = await fetch(url, {method: "POST"})
return await resp.json()
}

async function sync(definition: Definition, offset: string = '-1') {
/*
* Fetch the shape options and start syncing. When new data is recieved,
* log the number of rows. When an auth token expires, reconnect.
*/
async function sync(definition: Definition, handle: string, offset: string = '-1') {
console.log('sync: ', offset)

const options = await fetchShapeOptions(definition, offset)
const stream = new ShapeStream(options)
const options = await fetchShapeOptions(definition)
const stream = new ShapeStream({...options, handle: handle, offset: offset})
const shape = new Shape(stream)

let lastOffset = offset

stream.subscribe(
(messages) => {
messages.forEach((message) => {
if ('offset' in message) {
lastOffset = message.offset!
}
})
},
async (error) => {
if ('status' in error) {
console.warn('fetch error: ', error.status)
}
shape.subscribe(async ({ rows }) => {
if (shape.error && 'status' in shape.error) {
const status = shape.error.status
console.warn('fetch error: ', status)

shape.unsubscribeAll()
if (status === 401 || status === 403) {
shape.unsubscribeAll()

await sync(definition, lastOffset)
return await sync(definition, shape.handle, shape.lastOffset)
}
}
else {
console.log('num rows: ', rows ? rows.length : 0)
}
)

shape.subscribe(async ({ rows }) => {
console.log('num rows: ', rows ? rows.length : 0)
})
}

/*
* Make a request to the gatekeeper endpoint to get the proxy url and
* auth headers to connect to/with.
*/
async function fetchShapeOptions(definition: Definition) {
const { table, ...params} = definition

const qs = new URLSearchParams(params).toString()
const url = `${API_URL}/gatekeeper/${table}${qs ? '?' : ''}${qs}`

const resp = await fetch(url, {method: "POST"})
return await resp.json()
}

// Start syncing.
await sync({table: 'items'})

0 comments on commit c97c8ce

Please sign in to comment.