forked from BuilderIO/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-content-url.ts
148 lines (124 loc) · 4.2 KB
/
generate-content-url.ts
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
import {
flatten,
flattenMongoQuery,
unflatten,
} from '../../helpers/flatten.js';
import { normalizeSearchParams } from '../../helpers/search/search.js';
import { DEFAULT_API_VERSION } from '../../types/api-version.js';
import { getBuilderSearchParamsFromWindow } from '../get-builder-search-params/index.js';
import { isBrowser } from '../is-browser.js';
import type { GetContentOptions } from './types.js';
const isPositiveNumber = (thing: unknown) =>
typeof thing === 'number' && !isNaN(thing) && thing >= 0;
export const generateContentUrl = (options: GetContentOptions): URL => {
const {
limit = 30,
userAttributes,
query,
model,
apiKey,
enrich,
locale,
apiVersion = DEFAULT_API_VERSION,
fields,
omit,
offset,
cacheSeconds,
staleCacheSeconds,
sort,
includeUnpublished,
apiHost,
} = options;
if (!apiKey) {
throw new Error('Missing API key');
}
if (!['v3'].includes(apiVersion)) {
throw new Error(
`Invalid apiVersion: expected 'v3', received '${apiVersion}'`
);
}
// if we are fetching an array of content, we disable noTraverse for perf reasons.
const noTraverse = limit !== 1;
const baseUrl = apiHost || 'https://cdn.builder.io';
const url = new URL(`${baseUrl}/api/${apiVersion}/content/${model}`);
url.searchParams.set('apiKey', apiKey);
url.searchParams.set('limit', String(limit));
url.searchParams.set('noTraverse', String(noTraverse));
url.searchParams.set('includeRefs', String(true));
const finalLocale = locale || userAttributes?.locale;
let finalUserAttributes: Record<string, any> = userAttributes || {};
if (finalLocale) {
url.searchParams.set('locale', finalLocale);
finalUserAttributes = {
locale: finalLocale,
...finalUserAttributes,
};
}
if (enrich) url.searchParams.set('enrich', String(enrich));
url.searchParams.set('omit', omit || 'meta.componentsUsed');
if (fields) {
url.searchParams.set('fields', fields);
}
if (Number.isFinite(offset) && offset! > -1) {
url.searchParams.set('offset', String(Math.floor(offset!)));
}
if (typeof includeUnpublished === 'boolean') {
url.searchParams.set('includeUnpublished', String(includeUnpublished));
}
if (cacheSeconds && isPositiveNumber(cacheSeconds)) {
url.searchParams.set('cacheSeconds', String(cacheSeconds));
}
if (staleCacheSeconds && isPositiveNumber(staleCacheSeconds)) {
url.searchParams.set('staleCacheSeconds', String(staleCacheSeconds));
}
if (sort) {
const flattened = flatten({ sort });
for (const key in flattened) {
url.searchParams.set(key, JSON.stringify((flattened as any)[key]));
}
}
// TODO: how to express 'offset' in the url - as direct queryparam or as flattened in options[key] ?
const queryOptions = {
...getBuilderSearchParamsFromWindow(),
...normalizeSearchParams(options.options || {}),
};
finalUserAttributes = {
...finalUserAttributes,
...getUserAttributesAsJSON(queryOptions),
};
const flattened = flatten(queryOptions);
for (const key in flattened) {
url.searchParams.set(key, String(flattened[key]));
}
if (Object.keys(finalUserAttributes).length > 0) {
url.searchParams.set('userAttributes', JSON.stringify(finalUserAttributes));
}
if (query) {
const flattened = flattenMongoQuery({ query });
for (const key in flattened) {
url.searchParams.set(key, JSON.stringify(flattened[key]));
}
}
return url;
};
const getUserAttributesFromQueryOptions = (queryOptions: any) => {
const newUserAttributes: any = {};
for (const key in queryOptions) {
if (key.startsWith('userAttributes.')) {
newUserAttributes[key] = queryOptions[key];
delete queryOptions[key];
}
}
return newUserAttributes;
};
const getUserAttributesAsJSON = (queryOptions: any) => {
if (isBrowser() && queryOptions['preview'] === 'BUILDER_STUDIO') {
queryOptions['userAttributes.urlPath'] = window.location.pathname;
queryOptions['userAttributes.host'] = window.location.host;
const queryOptionsForUserAttributes =
getUserAttributesFromQueryOptions(queryOptions);
const { userAttributes } = unflatten(queryOptionsForUserAttributes);
return userAttributes;
}
return {};
};