-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(sse): Implement Server-Sent Events
See discussion in #4826
- Loading branch information
Showing
24 changed files
with
14,367 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { SSE_METADATA, PATH_METADATA, METHOD_METADATA } from '../../constants'; | ||
import { RequestMethod } from '../../enums/request-method.enum'; | ||
|
||
/** | ||
* Declares this route as a Server-Sent-Events endpoint | ||
* | ||
* @publicApi | ||
*/ | ||
export function Sse(path?: string): MethodDecorator { | ||
return ( | ||
target: object, | ||
key: string | symbol, | ||
descriptor: TypedPropertyDescriptor<any>, | ||
) => { | ||
Reflect.defineMetadata( | ||
PATH_METADATA, | ||
path && path.length ? path : '/', | ||
descriptor.value, | ||
); | ||
Reflect.defineMetadata( | ||
METHOD_METADATA, | ||
RequestMethod.GET, | ||
descriptor.value, | ||
); | ||
Reflect.defineMetadata(SSE_METADATA, true, descriptor.value); | ||
return descriptor; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export * from './http.module'; | ||
export * from './http.service'; | ||
export * from './interfaces'; | ||
export { SseStream } from './sse-stream.service'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
import { Transform } from 'stream'; | ||
import { IncomingMessage, OutgoingHttpHeaders } from 'http'; | ||
import { MessageEvent } from '../interfaces'; | ||
|
||
function toDataString(data: string | object): string { | ||
if (typeof data === 'object') return toDataString(JSON.stringify(data)); | ||
return data | ||
.split(/\r\n|\r|\n/) | ||
.map(line => `data: ${line}\n`) | ||
.join(''); | ||
} | ||
|
||
interface WriteHeaders { | ||
writeHead?(statusCode: number, headers?: OutgoingHttpHeaders): WriteHeaders; | ||
flushHeaders?(): void; | ||
} | ||
|
||
export type HeaderStream = NodeJS.WritableStream & WriteHeaders; | ||
|
||
/** | ||
* Adapted from https://raw.githubusercontent.com/EventSource/node-ssestream | ||
* Transforms "messages" to W3C event stream content. | ||
* See https://html.spec.whatwg.org/multipage/server-sent-events.html | ||
* A message is an object with one or more of the following properties: | ||
* - data (String or object, which gets turned into JSON) | ||
* - type | ||
* - id | ||
* - retry | ||
* | ||
* If constructed with a HTTP Request, it will optimise the socket for streaming. | ||
* If this stream is piped to an HTTP Response, it will set appropriate headers. | ||
*/ | ||
export class SseStream extends Transform { | ||
private lastEventId: number = null; | ||
|
||
constructor(req?: IncomingMessage) { | ||
super({ objectMode: true }); | ||
if (req) { | ||
req.socket.setKeepAlive(true); | ||
req.socket.setNoDelay(true); | ||
req.socket.setTimeout(0); | ||
} | ||
} | ||
|
||
pipe<T extends HeaderStream>(destination: T, options?: { end?: boolean }): T { | ||
if (destination.writeHead) { | ||
destination.writeHead(200, { | ||
'Content-Type': 'text/event-stream; charset=utf-8', | ||
'Transfer-Encoding': 'identity', | ||
'Cache-Control': 'no-cache', | ||
Connection: 'keep-alive', | ||
}); | ||
destination.flushHeaders(); | ||
} | ||
|
||
destination.write(':ok\n\n'); | ||
return super.pipe(destination, options); | ||
} | ||
|
||
_transform( | ||
message: MessageEvent, | ||
encoding: string, | ||
callback: (error?: Error | null, data?: any) => void, | ||
) { | ||
if (message.type) this.push(`event: ${message.type}\n`); | ||
if (message.id) this.push(`id: ${message.id}\n`); | ||
if (message.retry) this.push(`retry: ${message.retry}\n`); | ||
if (message.data) this.push(toDataString(message.data)); | ||
this.push('\n'); | ||
callback(); | ||
} | ||
|
||
writeMessage( | ||
message: MessageEvent, | ||
encoding?: string, | ||
cb?: (error: Error | null | undefined) => void, | ||
): boolean { | ||
if (!message.id) { | ||
this.lastEventId = this.lastEventId === null ? 0 : this.lastEventId + 1; | ||
message.id = '' + this.lastEventId; | ||
} | ||
|
||
if (!message.type) { | ||
message.type = 'message'; | ||
} | ||
|
||
return this.write(message, encoding, cb); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { expect } from 'chai'; | ||
import { Sse } from '../../decorators/http/sse.decorator'; | ||
import { HTTP_CODE_METADATA, SSE_METADATA } from '../../constants'; | ||
|
||
describe('@Sse', () => { | ||
const prefix = '/prefix'; | ||
class Test { | ||
@Sse(prefix) | ||
public static test() {} | ||
} | ||
|
||
it('should enhance method with expected http status code', () => { | ||
const metadata = Reflect.getMetadata(SSE_METADATA, Test.test); | ||
expect(metadata).to.be.eql(prefix); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
module.exports = { | ||
parser: '@typescript-eslint/parser', | ||
parserOptions: { | ||
project: 'tsconfig.json', | ||
sourceType: 'module', | ||
}, | ||
plugins: ['@typescript-eslint/eslint-plugin'], | ||
extends: [ | ||
'plugin:@typescript-eslint/eslint-recommended', | ||
'plugin:@typescript-eslint/recommended', | ||
'prettier', | ||
'prettier/@typescript-eslint', | ||
], | ||
root: true, | ||
env: { | ||
node: true, | ||
jest: true, | ||
}, | ||
rules: { | ||
'@typescript-eslint/interface-name-prefix': 'off', | ||
'@typescript-eslint/explicit-function-return-type': 'off', | ||
'@typescript-eslint/no-explicit-any': 'off', | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# compiled output | ||
/dist | ||
/node_modules | ||
|
||
# Logs | ||
logs | ||
*.log | ||
npm-debug.log* | ||
yarn-debug.log* | ||
yarn-error.log* | ||
lerna-debug.log* | ||
|
||
# OS | ||
.DS_Store | ||
|
||
# Tests | ||
/coverage | ||
/.nyc_output | ||
|
||
# IDEs and editors | ||
/.idea | ||
.project | ||
.classpath | ||
.c9/ | ||
*.launch | ||
.settings/ | ||
*.sublime-workspace | ||
|
||
# IDE - VSCode | ||
.vscode/* | ||
!.vscode/settings.json | ||
!.vscode/tasks.json | ||
!.vscode/launch.json | ||
!.vscode/extensions.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"singleQuote": true, | ||
"trailingComma": "all" | ||
} |
Oops, something went wrong.