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

feat: add onServerPrefetch #198

Merged
merged 6 commits into from
Dec 2, 2019
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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,25 @@ declare module '@vue/composition-api/dist/component/component' {
}
}
```

## SSR

Even if there is no definitive Vue 3 API for SSR yet, this plugin implements the `onServerPrefetch` lifecycle hook that allows you to use the `serverPrefetch` hook found in the classic API.

```js
import { onServerPrefetch } from '@vue/composition-api';

export default {
setup (props, { ssrContext }) {
const result = ref();

onServerPrefetch(async () => {
result.value = await callApi(ssrContext.someId);
});

return {
result,
};
},
};
```
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"ts-jest": "^24.0.2",
"typescript": "^3.6.2",
"vue": "^2.5.22",
"vue-router": "^3.1.3"
"vue-router": "^3.1.3",
"vue-server-renderer": "^2.6.10"
},
"peerDependencies": {
"vue": "^2.5.22"
Expand Down
1 change: 1 addition & 0 deletions src/apis/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ export const onUnmounted = createLifeCycles(['destroyed', 'deactivated'], genNam
export const onErrorCaptured = createLifeCycle('errorCaptured');
export const onActivated = createLifeCycle('activated');
export const onDeactivated = createLifeCycle('deactivated');
export const onServerPrefetch = createLifeCycle('serverPrefetch');
9 changes: 8 additions & 1 deletion src/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,14 @@ export function mixin(Vue: VueConstructor) {
const ctx = {
slots: {},
} as SetupContext;
const props: Array<string | [string, string]> = ['root', 'parent', 'refs', 'attrs', 'listeners'];
const props: Array<string | [string, string]> = [
'root',
'parent',
'refs',
'attrs',
'listeners',
'ssrContext',
];
const methodReturnVoid = ['emit'];
props.forEach(key => {
let targetKey: string;
Expand Down
139 changes: 139 additions & 0 deletions test/ssr/serverPrefetch.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
const Vue = require('vue/dist/vue.common.js');
const { createRenderer } = require('vue-server-renderer');
const { ref, onServerPrefetch, getCurrentInstance, provide, inject } = require('../../src');

function fetch(result) {
return new Promise(resolve => {
setTimeout(() => {
resolve(result);
}, 10);
});
}

describe('serverPrefetch', () => {
it('should prefetch async operations before rendering', async () => {
const app = new Vue({
setup() {
const count = ref(0);

onServerPrefetch(async () => {
count.value = await fetch(42);
});

return {
count,
};
},
render(h) {
return h('div', this.count);
},
});

const serverRenderer = createRenderer();
const html = await serverRenderer.renderToString(app);
expect(html).toBe('<div data-server-rendered="true">42</div>');
});

it('should prefetch many async operations before rendering', async () => {
const app = new Vue({
setup() {
const count = ref(0);
const label = ref('');

onServerPrefetch(async () => {
count.value = await fetch(42);
});

onServerPrefetch(async () => {
label.value = await fetch('meow');
});

return {
count,
label,
};
},
render(h) {
return h('div', [this.count, this.label]);
},
});

const serverRenderer = createRenderer();
const html = await serverRenderer.renderToString(app);
expect(html).toBe('<div data-server-rendered="true">42meow</div>');
});

it('should pass ssrContext', async () => {
const child = {
setup(props, { ssrContext }) {
const content = ref();

expect(ssrContext.foo).toBe('bar');

onServerPrefetch(async () => {
content.value = await fetch(ssrContext.foo);
});

return {
content,
};
},
render(h) {
return h('div', this.content);
},
};

const app = new Vue({
components: {
child,
},
render(h) {
return h('child');
},
});

const serverRenderer = createRenderer();
const html = await serverRenderer.renderToString(app, { foo: 'bar' });
expect(html).toBe('<div data-server-rendered="true">bar</div>');
});

it('should not share context', async () => {
const instances = [];
function createApp(context) {
return new Vue({
setup() {
const count = ref(0);

onServerPrefetch(async () => {
count.value = await fetch(context.result);
});

instances.push(getCurrentInstance());

return {
count,
};
},
render(h) {
return h('div', this.count);
},
});
}

const serverRenderer = createRenderer();
const promises = [];
// Parallel requests
for (let i = 1; i < 3; i++) {
promises.push(
new Promise(async resolve => {
const app = createApp({ result: i });
const html = await serverRenderer.renderToString(app);
expect(html).toBe(`<div data-server-rendered="true">${i}</div>`);
resolve();
})
);
}
await Promise.all(promises);
expect((instances[0] === instances[1]) === instances[2]).toBe(false);
});
});
66 changes: 66 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1583,6 +1583,16 @@ has@^1.0.1, has@^1.0.3:
dependencies:
function-bind "^1.1.1"

hash-sum@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/hash-sum/-/hash-sum-1.0.2.tgz#33b40777754c6432573c120cc3808bbd10d47f04"
integrity sha1-M7QHd3VMZDJXPBIMw4CLvRDUfwQ=

he@^1.1.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"
integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==

hosted-git-info@^2.1.4:
version "2.7.1"
resolved "https://registry.npm.taobao.org/hosted-git-info/download/hosted-git-info-2.7.1.tgz#97f236977bd6e125408930ff6de3eec6281ec047"
Expand Down Expand Up @@ -2579,11 +2589,36 @@ locate-path@^5.0.0:
dependencies:
p-locate "^4.1.0"

lodash._reinterpolate@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d"
integrity sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=

lodash.sortby@^4.7.0:
version "4.7.0"
resolved "https://registry.npm.taobao.org/lodash.sortby/download/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438"
integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=

lodash.template@^4.4.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-4.5.0.tgz#f976195cf3f347d0d5f52483569fe8031ccce8ab"
integrity sha512-84vYFxIkmidUiFxidA/KjjH9pAycqW+h980j7Fuz5qxRtO9pgB7MDFTdys1N7A5mcucRiDyEq4fusljItR1T/A==
dependencies:
lodash._reinterpolate "^3.0.0"
lodash.templatesettings "^4.0.0"

lodash.templatesettings@^4.0.0:
version "4.2.0"
resolved "https://registry.yarnpkg.com/lodash.templatesettings/-/lodash.templatesettings-4.2.0.tgz#e481310f049d3cf6d47e912ad09313b154f0fb33"
integrity sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ==
dependencies:
lodash._reinterpolate "^3.0.0"

lodash.uniq@^4.5.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773"
integrity sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=

lodash@^4.17.11:
version "4.17.11"
resolved "https://registry.npm.taobao.org/lodash/download/lodash-4.17.11.tgz#b39ea6229ef607ecd89e2c8df12536891cac9b8d"
Expand Down Expand Up @@ -3506,6 +3541,13 @@ resolve@^1.10.0, resolve@^1.11.0, resolve@^1.3.2:
dependencies:
path-parse "^1.0.6"

resolve@^1.2.0:
version "1.13.1"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.13.1.tgz#be0aa4c06acd53083505abb35f4d66932ab35d16"
integrity sha512-CxqObCX8K8YtAhOBRg+lrcdn+LK+WYOS8tSjqSFbjtrI5PnS63QPhZl4+yKfrU9tdsbMu9Anr/amegT87M9Z6w==
dependencies:
path-parse "^1.0.6"

restore-cursor@^2.0.0:
version "2.0.0"
resolved "https://registry.npm.taobao.org/restore-cursor/download/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf"
Expand Down Expand Up @@ -3658,6 +3700,11 @@ semver@^6.0.0:
resolved "https://registry.npm.taobao.org/semver/download/semver-6.1.1.tgz?cache=0&sync_timestamp=1559063729249&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fsemver%2Fdownload%2Fsemver-6.1.1.tgz#53f53da9b30b2103cd4f15eab3a18ecbcb210c9b"
integrity sha1-U/U9qbMLIQPNTxXqs6GOy8shDJs=

serialize-javascript@^1.3.0:
version "1.9.1"
resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-1.9.1.tgz#cfc200aef77b600c47da9bb8149c943e798c2fdb"
integrity sha512-0Vb/54WJ6k5v8sSWN09S0ora+Hnr+cX40r9F170nT+mSkaxltoE/7R3OrIdBSUv1OoiobH1QoWQbCnAO+e8J1A==

serialize-javascript@^1.6.1:
version "1.7.0"
resolved "https://registry.npm.taobao.org/serialize-javascript/download/serialize-javascript-1.7.0.tgz#d6e0dfb2a3832a8c94468e6eb1db97e55a192a65"
Expand Down Expand Up @@ -3791,6 +3838,11 @@ source-map-url@^0.4.0:
resolved "https://registry.npm.taobao.org/source-map-url/download/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3"
integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=

[email protected]:
version "0.5.6"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412"
integrity sha1-dc449SvwczxafwwRjYEzSiu19BI=

source-map@^0.5.0, source-map@^0.5.6:
version "0.5.7"
resolved "https://registry.npm.taobao.org/source-map/download/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
Expand Down Expand Up @@ -4245,6 +4297,20 @@ vue-router@^3.1.3:
resolved "https://registry.npm.taobao.org/vue-router/download/vue-router-3.1.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fvue-router%2Fdownload%2Fvue-router-3.1.3.tgz#e6b14fabc0c0ee9fda0e2cbbda74b350e28e412b"
integrity sha1-5rFPq8DA7p/aDiy72nSzUOKOQSs=

vue-server-renderer@^2.6.10:
version "2.6.10"
resolved "https://registry.yarnpkg.com/vue-server-renderer/-/vue-server-renderer-2.6.10.tgz#cb2558842ead360ae2ec1f3719b75564a805b375"
integrity sha512-UYoCEutBpKzL2fKCwx8zlRtRtwxbPZXKTqbl2iIF4yRZUNO/ovrHyDAJDljft0kd+K0tZhN53XRHkgvCZoIhug==
dependencies:
chalk "^1.1.3"
hash-sum "^1.0.2"
he "^1.1.0"
lodash.template "^4.4.0"
lodash.uniq "^4.5.0"
resolve "^1.2.0"
serialize-javascript "^1.3.0"
source-map "0.5.6"

vue@^2.5.22:
version "2.6.10"
resolved "https://registry.npm.taobao.org/vue/download/vue-2.6.10.tgz#a72b1a42a4d82a721ea438d1b6bf55e66195c637"
Expand Down