Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: some refactoring #10

Merged
merged 2 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 32 additions & 12 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const router = new Router({
routes: [
{
path: '/',
render: ({url, params, query, request}) => html`
response: ({url, params, query, request}) => html`
<${HtmlPage} title="Home">
<h1>Home</h1>
<nav>
Expand Down Expand Up @@ -56,7 +56,7 @@ self.addEventListener('fetch', (event) => {

## Router

Uses [URLPattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) internally for matching the `paths`. The `render` callback gets passed the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object, as well as any route params or query params.
Uses [URLPattern](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern) internally for matching the `paths`. The `response` callback gets passed the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object, as well as any route params or query params.

```js
import { html, Router } from 'swtl';
Expand All @@ -65,19 +65,19 @@ const router = new Router({
routes: [
{
path: '/',
render: () => html`<h1>Home</h1>`
response: () => html`<h1>Home</h1>`
},
{
path: '/:foo',
render: ({params}) => html`<h1>${params.foo}</h1>`
response: ({params}) => html`<h1>${params.foo}</h1>`
},
{
path: '/:foo/:bar',
render: ({params}) => html`<h1>${params.foo}/${params.bar}</h1>`
response: ({params}) => html`<h1>${params.foo}/${params.bar}</h1>`
},
{
path: '/:foo/:bar',
render: ({url, params, query, request}) => html`<h1>${params.foo}/${params.bar}</h1>`
response: ({url, params, query, request}) => html`<h1>${params.foo}/${params.bar}</h1>`
},
]
});
Expand All @@ -100,12 +100,12 @@ const router = new Router({
{
// The url will be: https://my-app.com/foo/bar/
path: '',
render: () => html`<${Home}/>`
response: () => html`<${Home}/>`
},
{
// The url will be: https://my-app.com/foo/bar/users/1
path: 'users/:id',
render: ({params}) => html`<${User} id=${params.id}/>`
response: ({params}) => html`<${User} id=${params.id}/>`
}
]
});
Expand All @@ -125,7 +125,7 @@ const router = new Router({
routes: [
{
path: '/',
render: () => html`<${Home}/>`
response: () => html`<${Home}/>`
}
],
fallback: ({query, request}) => html`<${NotFound}/>`
Expand All @@ -134,7 +134,7 @@ const router = new Router({

### `plugins`

You can also provide plugins. You can add global plugins that will run for every route, or add plugins for specific routes only. If you return a `Response` from a plugin, the router will return that response to the browser instead of your `render` function.
You can also provide plugins. You can add global plugins that will run for every route, or add plugins for specific routes only. If you return a `Response` from a plugin, the router will return that response to the browser instead of your `response` function.

```js
import { Router, html, HtmlResponse } from 'swtl';
Expand All @@ -154,7 +154,7 @@ const router = new Router({
routes: [
{
path: '/',
render: () => html`<${Home}/>`,
response: () => html`<${Home}/>`,
/**
* These plugins run for this route only
*/
Expand Down Expand Up @@ -201,7 +201,7 @@ const router = new Router({
routes: [
{
path: '/foo',
render: () => html`foo`,
response: () => html`foo`,
options: {
headers: {
'content-type': 'text/xml'
Expand Down Expand Up @@ -360,6 +360,26 @@ const template = html`
`;
```

If you're using SWTL in a more SPA-like PWA app, you can also use the following strategies:
```js
import { networkFirst, networkOnly, cacheFirst, cacheOnly } from 'swtl';

import { Router } from 'swtl';

const router = new Router({
routes: [
{
path: '/images/*.svg',
response: cacheFirst
},
]
});

self.addEventListener('fetch', (event) => {
event.respondWith(router.handleRequest(event.request));
});
```

## Out of order streaming

For out of order streaming you can use the built-in `Await` component and provide a `promise` property:
Expand Down
14 changes: 7 additions & 7 deletions packages/core/demo/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const router = new Router({
routes: [
{
path: "/a",
render: () => html`a`,
response: () => html`a`,
// plugins: [
// {
// name: 'a-plugin',
Expand All @@ -70,7 +70,7 @@ const router = new Router({
},
{
path: "/b",
render: () => html`b`,
response: () => html`b`,
// plugins: [
// {
// name: 'b-plugin',
Expand All @@ -82,11 +82,11 @@ const router = new Router({
},
// {
// path: '/',
// render: () => html`hi<my-el foo=1>baz</my-el>`,
// response: () => html`hi<my-el foo=1>baz</my-el>`,
// },
{
path: "/",
render: ({ params, query, request }) => html`
response: ({ params, query, request }) => html`
<${HtmlPage}>
<h1>home</h1>
<my-el></my-el>
Expand Down Expand Up @@ -114,19 +114,19 @@ const router = new Router({
},
{
path: "/foo",
render: ({ params, query, request }) =>
response: ({ params, query, request }) =>
html`<${HtmlPage}><h1>Foo</h1><//>`,
},
// {
// path: '/bar',
// render: ({params, query, request}) => html`<${HtmlPage}>
// response: ({params, query, request}) => html`<${HtmlPage}>
// <${Baz}>abc<//>
// efg
// <//>`
// },
// {
// path: '/baz',
// render: ({params, query, request}) => html`
// response: ({params, query, request}) => html`
// <${HtmlPage}>
// <${Baz}>abc<//>
// <h3>hello</h3>
Expand Down
28 changes: 17 additions & 11 deletions packages/core/dev.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { html } from './html.js';
import { render, renderToString, handle } from './render.js';
import { render, renderToString } from './render.js';
import { Await, when } from './await.js';
import { Slot } from './slot.js';
import { LitElement, css, html as litHtml } from 'lit';
Expand Down Expand Up @@ -91,16 +91,22 @@ function HtmlPage2({children}) {
return children;
}

const fixture = html`
<${HtmlPage}>
<h1>home</h1>
<my-el></my-el>
<ul>

</ul>
<h2>footer</h2>
<//>
`

// class MyEl extends LitElement {
// static styles = css`:host { color: red }`
// static properties = { disabled: { type: Boolean } };
// render() {
// return litHtml`<h1>hello ${this.disabled ? 'foo' : 'bar'}</h1>`;
// }
// }
// customElements.define('my-el', MyEl);

// html`
// <${HtmlPage}>
// <h1>home</h1>
// <my-el></my-el>
// <//>
// `

const r = unwrap(fixture);
console.log(1, r);
Expand Down
4 changes: 4 additions & 0 deletions packages/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export {
CacheFirst,
CacheOnly,
NetworkOnly,
networkFirst,
cacheFirst,
cacheOnly,
networkOnly
} from './strategies.js';

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swtl",
"version": "0.3.6",
"version": "0.4.0",
"description": "",
"main": "index.js",
"type": "module",
Expand Down
6 changes: 3 additions & 3 deletions packages/core/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class Router {
this.customElementRenderers = customElementRenderers;

this.fallback = {
render: fallback,
response: fallback,
params: {}
};
this.routes = routes.map(route => ({
Expand Down Expand Up @@ -69,15 +69,15 @@ export class Router {
if (match) {
matchedRoute = {
options: route.options,
render: route.render,
response: route.response,
params: match?.pathname?.groups ?? {},
plugins: route.plugins,
};
break;
}
}

const route = matchedRoute?.render ?? this?.fallback?.render;
const route = matchedRoute?.response ?? this?.fallback?.response;
if (route) {
const url = new URL(request.url);
const query = Object.fromEntries(new URLSearchParams(url.search));
Expand Down
28 changes: 16 additions & 12 deletions packages/core/strategies.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,25 @@
*/

/** @param {StrategyParams} params */
export function NetworkFirst({file, children}) {
return fetch(file).catch(() => caches.match(file).then(r => r || children));
}
export const NetworkFirst = ({file, children}) => fetch(file).catch(() => caches.match(file).then(r => r || children));

/** @param {StrategyParams} params */
export function CacheFirst({file, children}) {
return caches.match(file).then(r => r || fetch(file).catch(() => children));
}
export const CacheFirst = ({file, children}) => caches.match(file).then(r => r || fetch(file).catch(() => children));

/** @param {StrategyParams} params */
export function CacheOnly({file, children}) {
return caches.match(file).then(r => r || children);
}
export const CacheOnly = ({file, children}) => caches.match(file).then(r => r || children);

/** @param {StrategyParams} params */
export function NetworkOnly({file, children}) {
return fetch(file).catch(() => children);
}
export const NetworkOnly = ({file, children}) => fetch(file).catch(() => children);

/** @param {Request} request */
export const networkFirst = (request) => fetch(request).catch(() => caches.match(request));

/** @param {Request} request */
export const cacheFirst = (request) => caches.match(request).then(r => r || fetch(request));

/** @param {Request} request */
export const cacheOnly = (request) => caches.match(request);

/** @param {Request} request */
export const networkOnly = (request) => fetch(request);
4 changes: 2 additions & 2 deletions packages/core/test/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('Router', () => {
routes: [
{
path: '/foo',
render: () => html`foo`
response: () => html`foo`
}
]});

Expand All @@ -32,7 +32,7 @@ describe('Router', () => {
routes: [
{
path: '/foo',
render: () => html`foo`,
response: () => html`foo`,
options: {
status: 300,
headers: {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ export interface Plugin {

export interface Route {
path: string,
render: (params: RouteArgs) => RouteResult,
response: (params: RouteArgs) => RouteResult,
plugins?: Plugin[],
options?: RequestInit
}

export interface MatchedRoute {
params: Record<string, string>;
render: (params: RouteArgs) => RouteResult;
response: (params: RouteArgs) => RouteResult;
plugins?: Plugin[];
options?: RequestInit;
}
Loading