diff --git a/examples/gatekeeper-auth/client/index.ts b/examples/gatekeeper-auth/client/index.ts index 91d4502932..f3932ca65e 100644 --- a/examples/gatekeeper-auth/client/index.ts +++ b/examples/gatekeeper-auth/client/index.ts @@ -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'})