Browse Source

hacky method of awaiting promises during SSR

svelte
James Fenn 7 months ago
parent
commit
5943e0b83e
4 changed files with 33 additions and 11 deletions
  1. +9
    -0
      server/index.ts
  2. +15
    -0
      src/components/Await.svelte
  3. +5
    -10
      src/routes/Wiki.svx
  4. +4
    -1
      tsconfig.json

+ 9
- 0
server/index.ts View File

@@ -16,7 +16,16 @@ app.get('*', async (req, res) => {

console.log(`Rendering: ${req.method} ${req.url}`);

globalThis.promises = [];
globalThis.promiseValues = [];
let render = main.render({ url: req.url });

if (globalThis.promises.length > 0) {
await Promise.all(globalThis.promises);
globalThis.promises.length = 0;
render = main.render({ url: req.url });
}

html = html.replace("{content}", render.html);

res.set('Content-Type', "text/html");


+ 15
- 0
src/components/Await.svelte View File

@@ -0,0 +1,15 @@
<script lang="ts">
export let promise: Promise<any> = Promise.resolve();

const promises = globalThis.promises || [];
const promiseValues = globalThis.promiseValues || [];

const id = promises.length;
promises[id] = promise.then((result) => {
promiseValues[id] = result;
});
</script>

{#if promiseValues[id]}
<slot result={promiseValues[id]}/>
{/if}

+ 5
- 10
src/routes/Wiki.svx View File

@@ -1,11 +1,11 @@
<script lang="ts">
import Markdown from '../components/Markdown';
import Await from '../components/Await';

export let page = "";

page = page || "Home";
let content = fetch(`https://cdn.code.horrific.dev/horrific/horrific.dev/wiki/${page}.md`)
.then(response => response.text());
let content = fetch(`https://cdn.code.horrific.dev/horrific/horrific.dev/wiki/${page}.md`).then(response => response.text());

const title = page.replace('-', ' ');
</script>
@@ -18,11 +18,6 @@
{/if}
<h1>{title}</h1>

<div>
{#await content}
<p>Loading...</p>
{:then markdown}
<Markdown content="{markdown}"/>
{/await}
</div>

<Await promise={content} let:result>
<Markdown content="{result}"/>
</Await>

+ 4
- 1
tsconfig.json View File

@@ -2,5 +2,8 @@
"extends": "./node_modules/@tsconfig/svelte/tsconfig.json",

"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
"exclude": ["node_modules/*", "__sapper__/*", "public/*"],
"compilerOptions": {
"allowSyntheticDefaultImports": true
}
}

Loading…
Cancel
Save