var querystring = require('querystring');
var url = require('url');
const fs = require('fs')
var https = require('https');
var request = require('request');
var ejs = require('ejs');
function myPlugin(rawOptions) {
const options = {
isProduction: process.env.NODE_ENV === 'production',
...rawOptions,
root: process.cwd(),
};
let postData; let config;
return {
name: 'vite-plugin-func', // 必须的,将会显示在 warning 和 error 中
configResolved(resolvedConfig) {
// 存储最终解析的配置
config = resolvedConfig
},
configureServer(server) {
server.middlewares.use((req, res, next) => {
console.log(new Date(), 'req.url:', req.url)
if (req.url.indexOf(".flow") != -1 || req.url.indexOf(".func") != -1) {
let url = req.url;
postData = '';
let path
let fmodelpath = url.split("?")[0]
if (fmodelpath.endsWith(".flow")) {
var post_data = { fmodelpath: fmodelpath }
path = process.env.VITE_APP_BASE_API + process.env.VITE_APP_SERVER + "/flow/open?pn=";
} else {
var post_data = { __viewItemId: "" };
path = process.env.VITE_APP_BASE_API + process.env.VITE_APP_SERVER + fmodelpath + "?pn="
}
// let pn = url.split("/")[1];
const TokenKey = 'EAP-Token';
req.on('data', (chunk) => {
post += chunk;
postData = querystring.parse(post);
// console.log(new Date(), 'PostData:', postData);
});
var Cookies = {};
if (req.headers.cookie != null) {
req.headers.cookie.split(';').forEach(l => {
var parts = l.split('=');
Cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
let token = Cookies[TokenKey];
let requestUrl = path + process.env.VITE_APP_PN;
request({
url: requestUrl,
method: "POST",
json: true,
headers: {
"token": token,
"Authorization": "Bearer " + token,
"Content-Type": "application/json;charset=UTF-8"
},
body: post_data
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
// console.log(body) // 请求成功的处理逻辑
let pcform;
if (body) {
if (fmodelpath.endsWith(".flow") && body.outParameter) {
pcform = body.outParameter.task.bizpcform;
} else if (fmodelpath.endsWith(".func") && body.dataPack) {
pcform = body.dataPack.path;
}
}
if (!pcform) {
res.writeHead(500, {
"Content-Type": "application/json;charset=UTF-8"
});
res.end(JSON.stringify(body));
return;
}
// var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html";
let content;
try {
content = fs.readFileSync(pcform, { encoding: 'utf8' })
} catch (e) {
res.writeHead(404, {
"Content-Type": "application/json;charset=UTF-8"
});
res.end("pcform error!");
return;
}
const statusCode = 200;
if (!body)
throw new Error(`No body text found for the ${statusCode} status code`);
var html = ejs.render(content, rawOptions)
let postDataStr = JSON.stringify(postData || {});
let varName = options.varName || 'viteRequestData';
let varGlobal = JSON.stringify(options.global || {});
let funcName = new Date().valueOf();
let queryScript = `
function _viteGetQuery${funcName}() {
var url = window.location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
}
}
return theRequest;
}`
let titleStr = html.match(/<head(.*?)>/g)[0] || "";
html = html.replace(
/<head(.*?)>/g,
`${titleStr}<script>${queryScript};window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script>`
)
res.writeHead(statusCode, {
// 'Content-Length': html.length,
'Content-Type': 'html'
});
res.write(html)
res.end();
} else {
res.writeHead(body.status, {
"Content-Type": "application/json;charset=UTF-8"
});
res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body));
}
}, (msg) => {
res.writeHead(404, {
"Content-Type": "application/json;charset=UTF-8"
});
res.end(JSON.stringify(msg));
// console.log(msg)
});
return;
} else {
next();
}
})
},
}
}
export default myPlugin;