Skip to content

Instantly share code, notes, and snippets.

@wkrueger
Created August 8, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkrueger/23314f5ad5a85715f70394785220d299 to your computer and use it in GitHub Desktop.
Save wkrueger/23314f5ad5a85715f70394785220d299 to your computer and use it in GitHub Desktop.
paginatedquery
type Result = { rows: any[]; nextPage?: () => void }
class PaginatedQuery {
constructor(public query: string, public params: any[] = []) {}
private ctx = getContext()
private fetchSize = 10
private nextPromise = new Promise<Result>((resolve, reject) => {
this.nextResolve = resolve
this.nextReject = reject
})
private nextResolve!: Function
private nextReject!: Function
async init() {
const client = await this.ctx.cassandra.getClient()
let that = this
client.eachRow(
this.query,
this.params,
{ fetchSize: this.fetchSize },
function eachRow(/*n, row*/) {},
function eachPage(err: any, result: Result) {
if (err) return that.nextReject(err)
that.nextResolve(result)
}
)
}
async readNext(): Promise<Result | undefined> {
if (!this.nextPromise) return undefined
let result = await this.nextPromise
if (result.nextPage) {
this.nextPromise = new Promise((resolve, reject) => {
this.nextResolve = resolve
this.nextReject = reject
})
result.nextPage()
} else {
this.nextPromise = undefined as any
this.nextResolve = undefined as any
}
return result
}
}
const resultsCache = new Map<string, PaginatedQuery>()
// if (queryId) {
// const found = resultsCache.get(queryId)
// if (found) return found.readNext()
// throw Error("queryId expired or not found.")
// }
// const query = new PaginatedQuery("")
// await query.init()
// const newQueryId = v4()
// resultsCache.set(newQueryId, query)
// setTimeout(() => {
// resultsCache.delete(newQueryId)
// }, 30000)
// return query.readNext()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment