Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

notification.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const Stream = require('stream')
  2. const PassThrough = Stream.PassThrough
  3. const Transform = Stream.Transform
  4. const NotificationRoute = require('../routes/notification')
  5. const stringifyEvent = function (event) {
  6. let str = ''
  7. const endl = '\r\n'
  8. for (const i in event) {
  9. let val = event[i]
  10. if (val instanceof Buffer) { val = val.toString() }
  11. if (typeof val === 'object') { val = JSON.stringify(val) }
  12. str += i + ': ' + val + endl
  13. }
  14. str += endl
  15. return str
  16. }
  17. class Transformer extends Transform {
  18. constructor(options, objectMode) {
  19. super({ objectMode })
  20. options = options || {}
  21. this.counter = 1
  22. this.event = options.event || null
  23. this.generateId = options.generateId ? options.generateId : () => {
  24. return this.counter++
  25. }
  26. }
  27. _transform (chunk, encoding, callback) {
  28. const event = {
  29. id: this.generateId(chunk),
  30. data: chunk
  31. }
  32. if (this.event) { event.event = this.event }
  33. this.push(stringifyEvent(event))
  34. callback()
  35. }
  36. _flush(callback) {
  37. this.push(stringifyEvent({ event: 'end', data: '' }))
  38. callback()
  39. }
  40. }
  41. const writeEvent = function (event, stream) {
  42. if (event) {
  43. stream.write(stringifyEvent(event))
  44. } else {
  45. // closing time
  46. stream.write(stringifyEvent({ event: 'end', data: '' }))
  47. stream.end()
  48. }
  49. }
  50. const onEvent = (event, h, streamOptions) => {
  51. // We only support ObjectMode streams
  52. if (!event._readableState.objectMode) return
  53. const through = new Transformer(streamOptions, true)
  54. const active = new PassThrough()
  55. through.pipe(active)
  56. event.pipe(through)
  57. console.log(event)
  58. return h.response(active)
  59. .header('content-type', 'text/event-stream')
  60. .header('content-encoding', 'identity')
  61. }
  62. module.exports = {
  63. name: 'notification-plugin',
  64. version: '1.0.0',
  65. register: async (server, options) => {
  66. await server.route(NotificationRoute)
  67. server.decorate('toolkit', 'event', onEvent)
  68. }
  69. }