【前端】智能库房综合管理系统前端项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.6 KiB

  1. 'use strict'
  2. export default class FetchSource {
  3. constructor(url, options) {
  4. this.url = url
  5. this.destination = null
  6. this.request = null
  7. this.streaming = true
  8. this.completed = false
  9. this.established = false
  10. this.progress = 0
  11. this.aborted = false
  12. this.onEstablishedCallback = options.onSourceEstablished
  13. this.onCompletedCallback = options.onSourceCompleted
  14. }
  15. connect(destination) {
  16. this.destination = destination
  17. }
  18. start() {
  19. const params = {
  20. method: 'GET',
  21. headers: new Headers(),
  22. keepAlive: 'default'
  23. }
  24. self
  25. .fetch(this.url, params)
  26. .then(
  27. function(res) {
  28. if (res.ok && res.status >= 200 && res.status <= 299) {
  29. this.progress = 1
  30. this.established = true
  31. return this.pump(res.body.getReader())
  32. } else {
  33. // error
  34. }
  35. }.bind(this)
  36. )
  37. .catch(function(err) {
  38. throw err
  39. })
  40. }
  41. pump(reader) {
  42. return reader
  43. .read()
  44. .then(
  45. function(result) {
  46. if (result.done) {
  47. this.completed = true
  48. } else {
  49. if (this.aborted) {
  50. return reader.cancel()
  51. }
  52. if (this.destination) {
  53. this.destination.write(result.value.buffer)
  54. }
  55. return this.pump(reader)
  56. }
  57. }.bind(this)
  58. )
  59. .catch(function(err) {
  60. throw err
  61. })
  62. }
  63. resume(secondsHeadroom) {
  64. // Nothing to do here
  65. }
  66. abort() {
  67. this.aborted = true
  68. }
  69. }