Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. /**
  2. * Simulation for a database read with limit/offset pagination.
  3. * Records are just padded id strings - e.g. 0001, 0002, ... 5062.
  4. * Each read takes randomly between 500-2500ms.
  5. * limit - how many records to return
  6. * offset - how many records to skip
  7. * MAX_RECORDS - max records in "database"
  8. */
  9. const read = async ({ limit, offset }: { limit: number, offset: number }) => {
  10. const MAX_RECORDS = 22;
  11. await new Promise((resolve) => setTimeout(resolve, Math.round(Math.random() * 2000 + 500)));
  12. const returnSize = Math.max(limit - Math.max(limit + offset - MAX_RECORDS, 0), 0);
  13. const startId = offset;
  14. return new Array(returnSize)
  15. .fill('0'.repeat(String(MAX_RECORDS).length))
  16. .map((nullId, i) => {
  17. return nullId.concat(String(startId + i))
  18. .slice(-String(MAX_RECORDS).length);
  19. });
  20. };
  21. /**
  22. * Readable-stream datasource for simulated "database".
  23. * Chunks from DB are pushed when ready.
  24. */
  25. class StreamSource extends Readable {
  26. private reads = 0;
  27. constructor() {
  28. super({ highWaterMark: 5 });
  29. }
  30. async _read(size: any) {
  31. console.log(`_read #${this.reads++} size=${size}`);
  32. const data = await read({ limit: size, offset: (this.reads - 1) * size });
  33. data.forEach(item => {
  34. this.push(`${item} `);
  35. });
  36. this.push('\n');
  37. // Pagination reached end. Finish the data stream.
  38. if (data.length < size) {
  39. this.push('-|\n');
  40. this.push(null);
  41. }
  42. }
  43. }
  44. new StreamSource().pipe(process.stdout);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement