Files
bodyshop/client/src/utils/RenderTemplate.js
2020-10-07 10:25:51 -07:00

74 lines
2.1 KiB
JavaScript

import axios from "axios";
import gql from "graphql-tag";
import { QUERY_TEMPLATES_BY_NAME } from "../graphql/templates.queries";
import client from "../utils/GraphQLClient";
export default async function RenderTemplate(templateObject, bodyshop) {
const { data: templateRecords } = await client.query({
query: QUERY_TEMPLATES_BY_NAME,
variables: { name: templateObject.name },
fetchPolicy: "network-only",
});
let templateToUse;
if (templateRecords.templates.length === 1) {
console.log("[ITE] Using OOTB template.");
templateToUse = templateRecords.templates[0];
} else if (templateRecords.templates.length === 2) {
console.log("[ITE] Found custom template.");
templateToUse = templateRecords.templates.filter((t) => !!t.bodyshopid)[0];
console.log("templateToUse", templateToUse);
} else {
//No template found.Uh oh.
alert("Error: Template key does not exist.");
throw new Error("Template key does not exist.");
}
const { data: contextData } = await client.query({
query: gql(templateToUse.query),
variables: { ...templateObject.variables },
fetchPolicy: "network-only",
});
const { data } = await axios.post("/render", {
view: templateToUse.html,
context: { ...contextData, bodyshop: bodyshop },
});
return new Promise((resolve, reject) => {
resolve(data);
});
}
export const displayTemplateInWindow = (html) => {
try {
var newWin = window.open("", "_blank", "toolbar=0,location=0,menubar=0");
newWin.document.write(html);
setTimeout(function () {
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
}, 500);
} catch (error) {
console.log("Unable to write to new window.", error);
}
};
export const displayTemplateInWindowNoprint = (html) => {
try {
var newWin = window.open("", "_blank", "toolbar=0,location=0,menubar=0");
newWin.document.write(html);
setTimeout(function () {
newWin.document.close();
newWin.focus();
//newWin.print();
//newWin.close();
}, 500);
} catch (error) {
console.log("Unable to write to new window.", error);
}
};