Skip to content

Commit

Permalink
Add overload res.fetch with Request object
Browse files Browse the repository at this point in the history
  • Loading branch information
jcubic committed Aug 22, 2023
1 parent 179777c commit decf9e4
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 33 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION=0.10.1
VERSION=0.11.0
DATE=`date -uR`
YEAR=`date +%Y`

Expand Down
37 changes: 32 additions & 5 deletions 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.10.1-blue.svg)](https://www.npmjs.com/package/@jcubic/wayne)
[![npm](https://img.shields.io/badge/npm-0.11.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 @@ -142,6 +142,32 @@ app.get('/external', function(req, res) {
});
```

### Handle same extension for all requests

```javascript
importScripts(
'https://cdn.jsdelivr.net/npm/@jcubic/wayne/index.umd.min.js',
'https://cdn.jsdelivr.net/gh/jcubic/static@master/js/path.js'
);

const app = new Wayne();

app.get('*', function(req, res) {
const url = new URL(req.url);
const extension = path.extname(url.pathname);
const accept = req.headers.get('Accept');
if (extension === '.js' && accept.match(/text\/html/)) {
res.text('// Sorry no source code for you');
} else {
res.fetch(req);
}
});
```

This code will show comment `// Sorry no source code for you` for every
request to JavaScript files from the browser (if open in new tab).
When you want to view the file the browser sends `Accept: text/html`.

### File system middleware

```javascript
Expand Down Expand Up @@ -301,6 +327,7 @@ by Jake Archibald.
* [Server-Sent Events Proxy demo](https://jcubic.github.io/wayne/sse/).
* [Offline demo](https://jcubic.github.io/wayne/offline/).
* [Download demo](https://jcubic.github.io/wayne/download/).
* [Source Code Syntax highlight demo](https://jcubic.github.io/wayne/code/).

The source code for the demos can be found [in docs directory at gh-pages branch](https://github.com/jcubic/wayne/tree/gh-pages/docs).

Expand All @@ -315,7 +342,7 @@ Wayne object has those methods that correspond to HTTP methods
* `patch`

each method accepts URL with markers inside curly brackets those markers will be available from **Request.params** object.
Request object is browser native object of a given request see [MDN for details](https://developer.mozilla.org/en-US/docs/Web/API/Request). The only change to the native API is that the object have proeprty **params**.
Request object is browser native object of a given request see [MDN for details](https://developer.mozilla.org/en-US/docs/Web/API/Request). The only change to the native API is that the object have property **params**.

Here are few most important Request properties:

Expand Down Expand Up @@ -346,7 +373,7 @@ each of those methods accepts string as first argument. Second argument are opti
Additional methods:
* `redirect()` - accept url or optional first argument that is number of HTTP code
* `sse([options])` - function create Server-Sent Event stream, the return object have method `send` that send new event.
* `fetch(url)` - method will send normal HTTP request to the server and return the result to the client.
* `fetch(url | Request)` - method will send normal HTTP request to the server and return the result to the client. You can use default Request object from the route.
* `download(data, { filename })` - method that can be used to trigger of file download. The data can be a `string` or `arrayBuffer` you can use native fetch API and call `await res.text()` or `await res.arrayBuffer()` and pass the result as data.

Application also have middlewere as in Express.js
Expand All @@ -361,13 +388,13 @@ Additional exported functions:

## Story

The idea of using a Service worker to serve pure in browser HTTP requests has a long history. I've first used this technque for my [Git Web Terminal](https://git-terminal.js.org/) and described the usage of it in the article from 2018: [How to create Web Server in Browser](https://jcubic.wordpress.com/2018/05/23/how-to-create-web-server-from-browser/). In June 2022, I came up with a cool new way of using this technique. While creating PoC for the article I'm going to write (will update this story when ready), I realized that I can extract all the logic of creating those fake HTTP requests into a library. This is how Wayne was born.
The idea of using a Service worker to serve pure in browser HTTP requests has a long history. I've first used this technique for my [Git Web Terminal](https://git-terminal.js.org/) and described the usage of it in the article from 2018: [How to create Web Server in Browser](https://jcubic.wordpress.com/2018/05/23/how-to-create-web-server-from-browser/). In June 2022, I came up with a cool new way of using this technique. While creating PoC for the article I'm going to write (will update this story when ready), I realized that I can extract all the logic of creating those fake HTTP requests into a library. This is how Wayne was born.

The name of the library was inspired by the scene in [Wayne's World 2](https://en.wikipedia.org/wiki/Wayne's_World_2) in which Wayne dresses up as a construction worker.

[![Watch the video](https://github.com/jcubic/wayne/blob/master/assets/wayne's-world-screen-capture.png?raw=true)](https://youtu.be/89W-lCTFT2o)

I hightly recommend both movies if you haven't seen them already.
I highly recommend both movies if you haven't seen them already.


## Contribution
Expand Down
19 changes: 12 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Wayne - Server Worker Routing library (v. 0.10.1)
* Wayne - Server Worker Routing library (v. 0.11.0)
*
* Copyright (c) 2022-2023 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under MIT license
Expand Down Expand Up @@ -42,8 +42,9 @@ function isPromiseFs(fs) {
}

export class HTTPResponse {
constructor(resolve) {
constructor(resolve, reject) {
this._resolve = resolve;
this._reject = reject;
}
html(data, init) {
this.send(data, { type: 'text/html', ...init });
Expand All @@ -65,10 +66,14 @@ export class HTTPResponse {
}
this.blob(data, init);
}
async fetch(url) {
const _res = await fetch(url);
const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
this.send(await _res.arrayBuffer(), { type });
async fetch(arg) {
if (typeof arg === 'string') {
const _res = await fetch(arg);
const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
this.send(await _res.arrayBuffer(), { type });
} else if (arg instanceof Request) {
return fetch(arg).then(this._resolve).catch(this._reject);
}
}
download(content, { filename = 'download', type = 'text/plain', ...init } = {}) {
const headers = {
Expand Down Expand Up @@ -369,7 +374,7 @@ export class Wayne {
event.respondWith(new Promise(async (resolve, reject) => {
const req = event.request;
try {
const res = new HTTPResponse(resolve);
const res = new HTTPResponse(resolve, reject);
await chain_handlers(this._middlewares, function(fn, next) {
return fn(req, res, next);
});
Expand Down
6 changes: 3 additions & 3 deletions index.min.js

Large diffs are not rendered by default.

27 changes: 16 additions & 11 deletions index.umd.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/*
* Wayne - Server Worker Routing library (v. 0.10.0)
* Wayne - Server Worker Routing library (v. 0.10.1)
*
* Copyright (c) 2022-2023 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under MIT license
*
* Sun, 02 Jul 2023 18:55:00 +0000
* Tue, 22 Aug 2023 17:34:19 +0000
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.wayne = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Expand All @@ -20,7 +20,7 @@ exports.rpc = rpc;
exports.send = send;

/*
* Wayne - Server Worker Routing library (v. 0.10.1)
* Wayne - Server Worker Routing library (v. 0.11.0)
*
* Copyright (c) 2022-2023 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under MIT license
Expand Down Expand Up @@ -63,8 +63,9 @@ function isPromiseFs(fs) {
}

class HTTPResponse {
constructor(resolve) {
constructor(resolve, reject) {
this._resolve = resolve;
this._reject = reject;
}

html(data, init) {
Expand Down Expand Up @@ -102,13 +103,17 @@ class HTTPResponse {
this.blob(data, init);
}

async fetch(url) {
const _res = await fetch(url);
async fetch(arg) {
if (typeof arg === 'string') {
const _res = await fetch(arg);

const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
this.send(await _res.arrayBuffer(), {
type
});
const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
this.send(await _res.arrayBuffer(), {
type
});
} else if (arg instanceof Request) {
return fetch(arg).then(this._resolve).catch(this._reject);
}
}

download(content, {
Expand Down Expand Up @@ -453,7 +458,7 @@ class Wayne {
const req = event.request;

try {
const res = new HTTPResponse(resolve);
const res = new HTTPResponse(resolve, reject);
await chain_handlers(this._middlewares, function (fn, next) {
return fn(req, res, next);
});
Expand Down
6 changes: 3 additions & 3 deletions index.umd.min.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jcubic/wayne",
"version": "0.10.1",
"version": "0.11.0",
"description": "Service Worker Routing for in browser HTTP requests",
"type": "module",
"main": "index.min.js",
Expand Down

0 comments on commit decf9e4

Please sign in to comment.