in packages/runtime/src/dataLoader.ts [70:131]
export function parseTemplate(config: StaticDataLoader) {
const queryParams = {};
const getQueryParams = () => {
if (Object.keys(queryParams).length === 0) {
if (location.search.includes('?')) {
location.search.substring(1).split('&').forEach(query => {
const res = query.split('=');
// ?test=1&hello=world
if (res[0] !== undefined && res[1] !== undefined) {
queryParams[res[0]] = res[1];
}
});
}
}
return queryParams;
};
const cookie = {};
const getCookie = () => {
if (Object.keys(cookie).length === 0) {
document.cookie.split(';').forEach(c => {
const [key, value] = c.split('=');
if (key !== undefined && value !== undefined) {
cookie[key.trim()] = value.trim();
}
});
}
return cookie;
};
// Match all template of query cookie and storage.
let strConfig = JSON.stringify(config) || '';
const regexp = /\$\{(queryParams|cookie|storage)(\.(\w|-)+)?}/g;
let cap = [];
let matched = [];
while ((cap = regexp.exec(strConfig)) !== null) {
matched.push(cap);
}
matched.forEach(item => {
const [origin, key, value] = item;
if (item && origin && key && value && value.startsWith('.')) {
if (key === 'queryParams') {
// Replace query params.
strConfig = strConfig.replace(origin, getQueryParams()[value.substring(1)] || '');
} else if (key === 'cookie') {
// Replace cookie.
strConfig = strConfig.replace(origin, getCookie()[value.substring(1)] || '');
} else if (key === 'storage') {
// Replace storage.
strConfig = strConfig.replace(origin, localStorage.getItem(value.substring(1)) || '');
}
}
});
// Replace url.
strConfig = strConfig.replace('${url}', location.href);
return JSON.parse(strConfig);
}