Skip to content

Commit

Permalink
Handle rejected promises
Browse files Browse the repository at this point in the history
  • Loading branch information
paoloricciuti committed Feb 4, 2023
1 parent bb57109 commit d22df1b
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 68 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug_report.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ body:
id: logs
attributes:
label: Logs
description: "Please include browser console and server logs around the time this bug occurred. Optional if provided reproduction. Please try not to insert an image but copy paste the log text."
description: 'Please include browser console and server logs around the time this bug occurred. Optional if provided reproduction. Please try not to insert an image but copy paste the log text.'
render: shell
14 changes: 7 additions & 7 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: Run Lint
on:
on:
pull_request:
branches:
- main
Expand All @@ -8,10 +8,10 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
- run: npm install
- run: npm lint
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
- run: npm install
- run: npm lint
# - run: npm test
4 changes: 2 additions & 2 deletions .github/workflows/publish-to-npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ jobs:
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v3
with:
node-version: "16.x"
registry-url: "https://registry.npmjs.org"
node-version: '16.x'
registry-url: 'https://registry.npmjs.org'
- run: npm i
- run: npm run build
- working-directory: package
Expand Down
22 changes: 11 additions & 11 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
- Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
- Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities
Expand Down Expand Up @@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban.
### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
Expand Down
82 changes: 41 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@ This package allows you to transfare Promises over the wire in sveltekit. It use
Here's an example of what you would write;

**hooks.server.ts**

```ts
import { defer_handle } from 'sveltekit-defer';
import type { Handle } from '@sveltejs/kit';

export const handle: Handle = defer_handle;

```

if you have other handles you can chain them with the utility function `sequence` provided by sveltekit.

**hooks.server.ts**

```ts
import { defer_handle } from 'sveltekit-defer';
import { sequence } from "@sveltejs/kit/hooks";
import { sequence } from '@sveltejs/kit/hooks';
import type { Handle } from '@sveltejs/kit';

export const handle: Handle = sequence(defer_handle, your_handle);
Expand All @@ -34,62 +35,61 @@ import { defer } from 'sveltekit-defer';
import type { PageServerLoad } from './$types';

async function get_blog() {
await new Promise(r => setTimeout(r, 7000));
return "A long blog post that it's very critical so the user need to see it right away";
await new Promise((r) => setTimeout(r, 7000));
return "A long blog post that it's very critical so the user need to see it right away";
}

async function get_comments() {
await new Promise(r => setTimeout(r, 10000));
return [
{ author: "Antonio", comment: "Very cool" },
{ author: "Oskar", comment: "Yeah it's wonderful" },
];
await new Promise((r) => setTimeout(r, 10000));
return [
{ author: 'Antonio', comment: 'Very cool' },
{ author: 'Oskar', comment: "Yeah it's wonderful" }
];
}

/**
* Wrap you actual load function inside our defer function to unlock the defer functionality
*/
export const load: PageServerLoad = defer((async (event: ServerLoadEvent) => {
// start the fetch for the comments right away without awaiting
const comments = get_comments();
// await the blog post given that is critical content
const blog = await get_blog();
//return the promise (comments) and the blog post
return {
blog,
comments,
};
}));

export const load: PageServerLoad = defer(async (event: ServerLoadEvent) => {
// start the fetch for the comments right away without awaiting
const comments = get_comments();
// await the blog post given that is critical content
const blog = await get_blog();
//return the promise (comments) and the blog post
return {
blog,
comments
};
});
```

then on the client side you can access the data via the store provided by `sveltekit-defer`

```svelte
<script lang="ts">
import { get_data } from "sveltekit-defer";
import type { PageData } from "./$types";
import { get_data } from 'sveltekit-defer';
import type { PageData } from './$types';
const data = get_data<PageData>();
const data = get_data<PageData>();
</script>
<main>
<section>
<!--The blog will be available right away-->
{$data.blog}
</section>
<section>
<ul>
<!--await the comments because they are a Promise-->
{#await $data.comments}
Loading...
{:then comments}
{#each comments as comment}
<li>{comment.author} - {comment.comment}</li>
{/each}
{/await}
</ul>
</section>
<section>
<!--The blog will be available right away-->
{$data.blog}
</section>
<section>
<ul>
<!--await the comments because they are a Promise-->
{#await $data.comments}
Loading...
{:then comments}
{#each comments as comment}
<li>{comment.author} - {comment.comment}</li>
{/each}
{/await}
</ul>
</section>
</main>
```

Expand All @@ -108,4 +108,4 @@ Here's how it works:

There's a lot to do, but the first thing is to make sure that this doesn't create some super-huge security/performance issue and generally if there are things that can be done better.

Feel free to open an issue if you found something that is not working or if you have some ideas on how to improve.
Feel free to open an issue if you found something that is not working or if you have some ideas on how to improve.
18 changes: 13 additions & 5 deletions src/lib/defer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { ServerLoadEvent } from '@sveltejs/kit';
import { COOKIE_NAME, STREAM_PATHNAME } from './constants';

function pushEvent(event: ServerLoadEvent, data: any) {
event.fetch(`${STREAM_PATHNAME}?load=${event.url}`, {
method: 'POST',
body: JSON.stringify(data)
});
}

export function defer<T extends (...args: any[]) => any>(
func: T
): (event: ServerLoadEvent) => Promise<ReturnType<T>> {
Expand All @@ -20,12 +27,13 @@ export function defer<T extends (...args: any[]) => any>(
returnVal.promises = [];
}
returnVal.promises.push(key);
returnVal[key].then((res: any) => {
event.fetch(`${STREAM_PATHNAME}?load=${event.url}`, {
method: 'POST',
body: JSON.stringify({ value: JSON.stringify(res), key })
returnVal[key]
.then((res: any) => {
pushEvent(event, { value: JSON.stringify(res), key, kind: 'resolve' });
})
.catch((error: any) => {
pushEvent(event, { value: JSON.stringify(error), key, kind: 'reject' });
});
});
returnVal[key] = '__PROMISE_TO_DEFER__';
}
});
Expand Down
7 changes: 6 additions & 1 deletion src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ export function get_data<T>() {
});
eventSource?.addEventListener(STREAM_EVENT, (evt) => {
const resolved = JSON.parse(evt.data);
resolvers.get(resolved.key)?.resolve(JSON.parse(resolved.value));
const resolver = resolvers.get(resolved.key);
if (resolved.kind === 'resolve') {
resolver?.resolve(JSON.parse(resolved.value));
} else {
resolver?.reject(JSON.parse(resolved.value));
}
});
});
onDestroy(() => {
Expand Down

0 comments on commit d22df1b

Please sign in to comment.