-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathserverInitialState.ts
More file actions
94 lines (81 loc) · 2.46 KB
/
Copy pathserverInitialState.ts
File metadata and controls
94 lines (81 loc) · 2.46 KB
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
import {
applyCommercePagesRankingStrategy,
generateContentHash,
} from './utils.js';
import { buildQueryStringFromObject } from '../helpers/index.js';
import { contentEntries } from '../entities/schemas/content.js';
import { type ContentsState } from './types/index.js';
import { get, merge } from 'lodash-es';
import { INITIAL_STATE_CONTENT } from './reducer.js';
import { normalize } from 'normalizr';
import parse from 'url-parse';
import type { ServerInitialState } from '../types/serverInitialState.types.js';
/**
* Converts server data from searchContents to store state.
*
* @param page - Params from the `page` object injected by the server.
*
* @returns Initial state for the contents reducer.
*/
const serverInitialState: ServerInitialState = ({ model, strategy }) => {
if (!get(model, 'searchContentRequests')) {
return { contents: INITIAL_STATE_CONTENT };
}
const { searchContentRequests, slug, seoMetadata, subfolder } = model;
const url = subfolder !== '/' ? slug?.replace(subfolder, '') : slug;
const normalizedUrl = url
?.replace('?json=true', '')
.replace('&json=true', '');
const contents = searchContentRequests.reduce((acc, item) => {
const {
searchResponse,
filters: { codes, contentTypeCode },
} = item;
let response = searchResponse;
const isCommercePage = contentTypeCode === 'commerce_pages';
const code = isCommercePage ? normalizedUrl : codes?.[0];
const hash = generateContentHash({
codes: code,
contentTypeCode: contentTypeCode,
});
if (isCommercePage) {
response = applyCommercePagesRankingStrategy(searchResponse, strategy);
}
const { entities, result } = {
...normalize({ hash, ...response }, contentEntries),
};
return merge(acc, {
entities,
contents: {
searchResults: {
[hash]: {
result,
isLoading: false,
error: null,
},
},
},
});
}, {});
const { pathname, query } = parse(url, true);
delete query.json;
const metadataHash = `${pathname}${buildQueryStringFromObject(query)}`;
const metadata = {
contents: {
metadata: {
isLoading: {
[metadataHash]: false,
},
error: {},
result: {
[metadataHash]: {
...seoMetadata,
},
},
},
} as ContentsState,
};
const total = merge(contents, metadata);
return total;
};
export default serverInitialState;