This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 157
/
createServerRootMixin.js
270 lines (231 loc) · 7.31 KB
/
createServerRootMixin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import Vue from 'vue';
import instantsearch from 'instantsearch.js/es';
import algoliaHelper from 'algoliasearch-helper';
const { SearchResults, SearchParameters } = algoliaHelper;
import { warn } from './warn';
function walkIndex(indexWidget, visit) {
visit(indexWidget);
return indexWidget.getWidgets().forEach(widget => {
if (widget.$$type !== 'ais.index') return;
visit(widget);
walkIndex(widget, visit);
});
}
function renderToString(app, _renderToString) {
return new Promise((resolve, reject) =>
_renderToString(app, (err, res) => {
if (err) reject(err);
resolve(res);
})
);
}
function searchOnlyWithDerivedHelpers(helper) {
return new Promise((resolve, reject) => {
helper.searchOnlyWithDerivedHelpers();
// we assume all derived helpers resolve at least in the same tick
helper.derivedHelpers[0].on('result', () => {
resolve();
});
helper.derivedHelpers.forEach(derivedHelper =>
derivedHelper.on('error', e => {
reject(e);
})
);
});
}
function augmentInstantSearch(instantSearchOptions, searchClient, indexName) {
/* eslint-disable no-param-reassign */
const helper = algoliaHelper(searchClient, indexName);
const search = instantsearch(instantSearchOptions);
let resultsState;
/**
* main API for SSR, called in serverPrefetch of a root component which contains instantsearch
* @param {object} componentInstance the calling component's `this`
* @returns {Promise} result of the search, to save for .hydrate
*/
search.findResultsState = function(componentInstance) {
let _renderToString;
try {
_renderToString = require('vue-server-renderer/basic');
} catch (e) {
// error is handled by regular if, in case it's `undefined`
}
if (!_renderToString) {
throw new Error('you need to install vue-server-renderer');
}
let app;
return Promise.resolve()
.then(() => {
const options = {
serverPrefetch: undefined,
fetch: undefined,
_base: undefined,
name: 'ais-ssr-root-component',
// copy over global Vue APIs
router: componentInstance.$router,
store: componentInstance.$store,
};
const Extended = componentInstance.$vnode
? componentInstance.$vnode.componentOptions.Ctor.extend(options)
: Vue.component(
Object.assign({}, componentInstance.$options, options)
);
app = new Extended({
propsData: componentInstance.$options.propsData,
});
// https://stackoverflow.com/a/48195006/3185307
app.$slots = componentInstance.$slots;
app.$root = componentInstance.$root;
app.$options.serverPrefetch = [];
app.instantsearch.helper = helper;
app.instantsearch.mainHelper = helper;
app.instantsearch.mainIndex.init({
instantSearchInstance: app.instantsearch,
parent: null,
uiState: app.instantsearch._initialUiState,
});
})
.then(() => renderToString(app, _renderToString))
.then(() => searchOnlyWithDerivedHelpers(helper))
.then(() => {
const results = {};
walkIndex(app.instantsearch.mainIndex, widget => {
results[widget.getIndexId()] = widget.getResults();
});
search.hydrate(results);
resultsState = Object.keys(results)
.map(indexId => {
const { _state, _rawResults } = results[indexId];
return [
indexId,
{
// copy just the values of SearchParameters, not the functions
_state: Object.keys(_state).reduce((acc, key) => {
acc[key] = _state[key];
return acc;
}, {}),
_rawResults,
},
];
})
.reduce(
(acc, [key, val]) => {
acc[key] = val;
return acc;
},
{
__identifier: 'stringified',
}
);
return search.getState();
});
};
/**
* @returns {Promise} result state to serialize and enter into .hydrate
*/
search.getState = function() {
if (!resultsState) {
throw new Error('You need to wait for findResultsState to finish');
}
return resultsState;
};
/**
* make sure correct data is available in each widget's state.
* called in widget mixin with (this.widget, this)
*
* @param {object} widget The widget instance
* @param {object} parent The local parent index
* @returns {void}
*/
search.__forceRender = function(widget, parent) {
const localHelper = parent.getHelper();
const results = search.__initialSearchResults[parent.getIndexId()];
// this happens when a different InstantSearch gets rendered initially,
// after the hydrate finished. There's thus no initial results available.
if (!results) {
return;
}
const state = results._state;
// helper gets created in init, but that means it doesn't get the injected
// parameters, because those are from the lastResults
localHelper.state = state;
widget.render({
helper: localHelper,
results,
scopedResults: parent.getScopedResults(),
state,
templatesConfig: {},
createURL: parent.createURL,
instantSearchInstance: search,
searchMetadata: {
isSearchStalled: false,
},
});
};
/**
* Called both in server
* @param {object} results a map of indexId: SearchResults
* @returns {void}
*/
search.hydrate = function(results) {
if (!results) {
warn(
'The result of `findResultsState()` needs to be passed to `hydrate()`.'
);
return;
}
const initialResults =
results.__identifier === 'stringified'
? Object.keys(results).reduce((acc, indexId) => {
if (indexId === '__identifier') {
return acc;
}
acc[indexId] = new SearchResults(
new SearchParameters(results[indexId]._state),
results[indexId]._rawResults
);
return acc;
}, {})
: results;
search.__initialSearchResults = initialResults;
search.helper = helper;
search.mainHelper = helper;
search.mainIndex.init({
instantSearchInstance: search,
parent: null,
uiState: search._initialUiState,
});
};
/* eslint-enable no-param-reassign */
return search;
}
export function createServerRootMixin(instantSearchOptions = {}) {
const { searchClient, indexName } = instantSearchOptions;
if (!searchClient || !indexName) {
throw new Error(
'createServerRootMixin requires `searchClient` and `indexName` in the first argument'
);
}
const search = augmentInstantSearch(
instantSearchOptions,
searchClient,
indexName
);
// put this in the user's root Vue instance
// we can then reuse that InstantSearch instance seamlessly from `ais-instant-search-ssr`
const rootMixin = {
provide() {
return {
$_ais_ssrInstantSearchInstance: this.instantsearch,
};
},
data() {
return {
// this is in data, so that the real & duplicated render do not share
// the same instantsearch instance.
instantsearch: search,
};
},
};
return rootMixin;
}