Skip to content

Commit

Permalink
Merge pull request #139 from contentstack/fix/cs-43765-reapply-live-p…
Browse files Browse the repository at this point in the history
…review1

Fix/cs 43765 reapply live preview1
  • Loading branch information
abhinav-from-contentstack authored Feb 2, 2024
2 parents 46b0e59 + 427aa04 commit ca228cc
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 177 deletions.
2 changes: 1 addition & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const config = {
},
live_preview: {
enable: false,
host: 'api.contentstack.io'
host: 'rest-preview.contentstack.com'
}
};

Expand Down
17 changes: 14 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,21 @@ export interface ContentTypeCollection {
count?: number
}

export interface LivePreview {
host: string
management_token: string
export type LivePreview = {
host?: string
enable: boolean
} & (LivePreivewConfigWithManagementToken | LivePreviewConfigWithPreviewToken)

export interface LivePreivewConfigWithManagementToken {
/**
* @deprecated Please use `preview_token` instead to enable live preview.
* The `management_token` will be removed in future releases.
*/
management_token: string;
}

export interface LivePreviewConfigWithPreviewToken {
preview_token: string;
}

export interface LivePreviewQuery {
Expand Down
189 changes: 19 additions & 170 deletions src/core/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,18 +233,21 @@ export function sendRequest(queryObject, options) {
queryObject.requestParams.body = merge(queryObject.requestParams.body, cloneQueryObj);

if (queryObject.live_preview && queryObject.live_preview.enable === true && queryObject.live_preview.live_preview && queryObject.live_preview.live_preview !== "init") {
if(queryObject.live_preview.content_type_uid === queryObject.content_type_uid) {
queryObject.requestParams.body = merge(queryObject.requestParams.body, {live_preview: queryObject.live_preview.live_preview || "init"});
cachePolicy = 2; // network else cache
if(queryObject.requestParams.body['environment']) {
delete queryObject.requestParams.body['environment'];
}
if(queryObject.requestParams.headers['access_token'])
delete queryObject.requestParams.headers['access_token'];

queryObject.requestParams.headers['authorization'] = queryObject.live_preview.management_token
} else if(queryObject.live_preview.live_preview) {
cachePolicy = 1; // cache then network
queryObject.requestParams.body = merge(queryObject.requestParams.body, {live_preview: queryObject.live_preview.live_preview || "init"});
cachePolicy = 2; // network else cache
if(queryObject.requestParams.body['environment']) {
delete queryObject.requestParams.body['environment'];
}
if(queryObject.requestParams.headers['access_token'])
delete queryObject.requestParams.headers['access_token'];
delete queryObject.requestParams.headers['authorization'];
delete queryObject.requestParams.headers['preview_token'];

if (queryObject.live_preview.preview_token) {
queryObject.requestParams.headers['preview_token'] = queryObject.live_preview.preview_token;
queryObject.requestParams.headers['live_preview'] = queryObject.live_preview.live_preview;
} else if (queryObject.live_preview.management_token) {
queryObject.requestParams.headers['authorization'] = queryObject.live_preview.management_token;
}
}
}
Expand Down Expand Up @@ -347,56 +350,10 @@ export function sendRequest(queryObject, options) {
if (err || !_data) {
callback(true, resolve, reject);
} else {
try {

const doesQueryRequestForReferences =
queryObject._query &&
Array.isArray(
queryObject._query.include
) &&
queryObject._query.include.length > 0;

if (doesQueryRequestForReferences) {
const referencesToBeResolved =
queryObject._query.include;

const referencesToBeResolvedMap =
generateReferenceMap(
referencesToBeResolved
);

if (isSingle) {
await updateLivePreviewReferenceEntry(
referencesToBeResolvedMap,
_data.entry,
queryObject,
options
);
} else {
await Promise.all(_data.entries.map(async (entry) => {
await updateLivePreviewReferenceEntry(
referencesToBeResolvedMap,
entry,
queryObject,
options

);
}))
}

}
} catch (error) {
}
try {
if (!tojson)
_data =
resultWrapper(_data);
return resolve(
spreadResult(_data)
);
} catch (e) {
return reject(e);
if (!tojson) {
_data = resultWrapper(_data);
}
return resolve(spreadResult(_data));
}
} catch (e) {
return reject(e);
Expand All @@ -405,7 +362,7 @@ export function sendRequest(queryObject, options) {
}else {
callback(true, resolve, reject);
}

});
case 2:
case 0:
Expand Down Expand Up @@ -448,111 +405,3 @@ export function sendRequest(queryObject, options) {
})
}
}


function generateReferenceMap (references) {
const map = {};

function mapSingleReference(reference) {
reference = reference.replace(/[\[]/gm, ".").replace(/[\]]/gm, ""); //to accept [index]
let keys = reference.split("."),
last = keys.pop();

keys.reduce(function (o, k) {
return (o[k] = o[k] || {});
}, map)[last] = { };
}

references.forEach(function (reference) {
mapSingleReference(reference);
});

return map;
};

async function updateLivePreviewReferenceEntry(referenceMap, entry, stack, options, handlerOptions) {
const {live_preview:livePreview, requestParams} = stack;
const { content_type_uid: livePreviewContentTypeUid, management_token } = livePreview;


async function findReferenceAndFetchEntry(referenceMap, entry, setReference) {
if ( typeof entry === "undefined")
return;
if (Array.isArray(entry)) {
await Promise.all(entry.map((subEntry, i) => {
const setReference = (val) => {
entry[i] = val;
}
return findReferenceAndFetchEntry(referenceMap, subEntry, setReference)
}));
} else {
if (entry._content_type_uid === livePreviewContentTypeUid) {

try {
stack.requestParams = JSON.parse(JSON.stringify(requestParams));

const includeReference = getIncludeParamForReference(referenceMap)
stack.requestParams.body.include = includeReference
stack.requestParams.body.live_preview = livePreview.live_preview
stack.requestParams.body.content_type_uid = livePreviewContentTypeUid

const livePreviewUrl = livePreview.host.match(
/^((http[s]?):(\/\/)?)?(.+)$/
);

const livePreviewHost =
(livePreviewUrl[1] || "https://") + livePreviewUrl[4];
const entryUid = entry.uid;

const url = `${livePreviewHost}/v3/content_types/${entry._content_type_uid}/entries/${entryUid}`;
stack.requestParams.url = url
stack.requestParams.method = "GET"

delete stack.requestParams.headers.access_token
stack.requestParams.headers.authorization = management_token

const data = await Request(stack, options);
data.entry._content_type_uid = livePreviewContentTypeUid;
data.entry.uid = entryUid;
setReference(data.entry);

} catch (err) {
console.log("errror", err)
}
} else {

await Promise.all(Object.entries(referenceMap).map(async function ([
currentRefFieldKey,
subReferenceMap,
]) {
// recurse
const setRef = (val) => {
entry[currentRefFieldKey] = val;
}
await findReferenceAndFetchEntry(subReferenceMap, entry[currentRefFieldKey], () => {});
}));
}
}
}

await findReferenceAndFetchEntry(referenceMap, entry, () => {});

}

function getIncludeParamForReference(referenceMap) {
const newRefences = [];

function buildParamStringRecursively(currentReferenceMap, includeParamTillNow) {
if (Object.keys(currentReferenceMap).length === 0) {
newRefences.push(includeParamTillNow.substring(1));
} else {

Object.entries(currentReferenceMap).forEach(([referenceFieldKey, subReferenceMap]) => {
buildParamStringRecursively(subReferenceMap, [includeParamTillNow, referenceFieldKey].join("."));
});
}
}

buildParamStringRecursively(referenceMap, "");
return newRefences.filter((currentReference) => currentReference !== "");
}
2 changes: 1 addition & 1 deletion src/core/modules/entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ export default class Entry {
*/
fetch(fetchOptions) {
var host = this.config.host + ':' + this.config.port
if(this.live_preview && this.live_preview.enable === true && this.live_preview.content_type_uid === this.content_type_uid ) {
if(this.live_preview && this.live_preview.enable === true && this.live_preview.live_preview && this.live_preview.live_preview !== "init" ) {
host = this.live_preview.host
}
if (this.entry_uid) {
Expand Down
4 changes: 2 additions & 2 deletions src/core/modules/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ export default class Query extends Entry {
*/
find(fetchOptions) {
var host = this.config.host + ':' + this.config.port
if (this.type && this.type !== 'asset' && this.live_preview && this.live_preview.enable === true && this.live_preview.content_type_uid === this.content_type_uid ) {
if (this.type && this.type !== 'asset' && this.live_preview && this.live_preview.enable === true && this.live_preview.live_preview && this.live_preview.live_preview !== "init") {
host = this.live_preview.host;
}
const baseURL = this.config.protocol + "://" + host + '/' + this.config.version
Expand Down Expand Up @@ -808,7 +808,7 @@ export default class Query extends Entry {
*/
findOne() {
let host = this.config.protocol + "://" + this.config.host + ':' + this.config.port + '/' + this.config.version
if(this.type && this.type !== 'asset' && this.live_preview && this.live_preview.enable === true && this.live_preview.content_type_uid === this.content_type_uid ) {
if(this.type && this.type !== 'asset' && this.live_preview && this.live_preview.enable === true && this.live_preview.live_preview && this.live_preview.live_preview !== "init" ) {
host = this.config.protocol + "://" + this.live_preview.host + '/' + this.config.version
}
const url = getRequestUrl(this.type, this.config, this.content_type_uid, host)
Expand Down

0 comments on commit ca228cc

Please sign in to comment.