Skip to content

Commit

Permalink
add SSE support #12
Browse files Browse the repository at this point in the history
  • Loading branch information
jcubic committed Nov 6, 2022
1 parent 54ede66 commit d96afc3
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 5 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## 0.3.0
### Features
* add `sse()` method for Server-Sent Events [#12](https://github.com/jcubic/wayne/issues/12)

## 0.2.1
### Bugs
* fix cross-origin redirect [#2](https://github.com/jcubic/wayne/issues/2)

## 0.2.0
### Features
* allow to use without ES Module [#9](https://github.com/jcubic/wayne/issues/9)
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
alt="Logo of Wayne library - it represent constrution worker helmet and text with the name of the library" />
</h1>

[![npm](https://img.shields.io/badge/npm-0.2.1-blue.svg)](https://www.npmjs.com/package/@jcubic/wayne)
[![npm](https://img.shields.io/badge/npm-0.3.0-blue.svg)](https://www.npmjs.com/package/@jcubic/wayne)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://makeapullrequest.com)

[Service Worker Routing library for in browser HTTP requests](https://github.com/jcubic/wayne/)
Expand Down Expand Up @@ -210,6 +210,7 @@ Code contributions are also welcome.
## Aknowledge
* Part of the content of this README was based on text from [MDN](https://developer.mozilla.org/).
* Logo use illustration from [OpenClipart](https://openclipart.org/detail/320906/hard-hat).
* This article was helpful [SSEGWSW: Server-Sent Events Gateway by Service Workers](https://medium.com/its-tinkoff/ssegwsw-server-sent-events-gateway-by-service-workers-6212c1c55184)

## License

Expand Down
47 changes: 47 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,40 @@ export class HTTPResponse {
}
this._resolve(Response.redirect(url, code));
}
sse({ onClose } = {}) {
let send, close, stream, defunct;
stream = new ReadableStream({
cancel() {
defunct = true;
trigger(onClose);
},
start: controller => {
send = function(event) {
if (!defunct) {
const chunk = createChunk(event);
const payload = new TextEncoder().encode(chunk);
controller.enqueue(payload);
}
};
close = function close() {
controller.close();
stream = null;
trigger(onClose);
};
}
});
this._resolve(new Response(stream, {
headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive'
}
}));
return {
send,
close
};
}
}

// code extracted from https://github.com/jcubic/route.js
Expand Down Expand Up @@ -149,6 +183,19 @@ function error404(path) {
}];
}

function createChunk({ data, event, retry, id }) {
return Object.entries({ event, id, data, retry })
.filter(([, value]) => value)
.map(([key, value]) => `${key}: ${value}`)
.join('\n') + '\n\n';
}

function trigger(maybeFn, ...args) {
if (typeof maybeFn === 'function') {
maybeFn(...args);
}
}

export class Wayne {
constructor() {
this._routes = {};
Expand Down
2 changes: 1 addition & 1 deletion index.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions index.umd.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,47 @@ class HTTPResponse {
this._resolve(Response.redirect(url, code));
}

sse({
onClose
} = {}) {
let send, close, stream, defunct;
stream = new ReadableStream({
cancel() {
defunct = true;
trigger(onClose);
},

start: controller => {
send = function (event) {
if (!defunct) {
const chunk = createChunk(event);
const payload = new TextEncoder().encode(chunk);
controller.enqueue(payload);
}
};

close = function close() {
controller.close();
stream = null;
trigger(onClose);
};
}
});

this._resolve(new Response(stream, {
headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive'
}
}));

return {
send,
close
};
}

} // code extracted from https://github.com/jcubic/route.js
// Copyright (C) 2014-2017 Jakub T. Jankiewicz <https://jcubic.pl/me>

Expand Down Expand Up @@ -170,6 +211,26 @@ function error404(path) {
}];
}

function createChunk({
data,
event,
retry,
id
}) {
return Object.entries({
event,
id,
data,
retry
}).filter(([, value]) => value).map(([key, value]) => `${key}: ${value}`).join('\n') + '\n\n';
}

function trigger(maybeFn, ...args) {
if (typeof maybeFn === 'function') {
maybeFn(...args);
}
}

class Wayne {
constructor() {
this._routes = {};
Expand Down
Loading

0 comments on commit d96afc3

Please sign in to comment.