2017-02-06 14:33:34 +08:00
|
|
|
import { EJSON } from 'meteor/ejson';
|
2017-06-06 18:06:32 -07:00
|
|
|
import moment from 'moment';
|
2017-02-12 22:00:13 +08:00
|
|
|
import { webAppConnectHandlersUse } from './meteor_patch.js';
|
2017-02-06 14:33:34 +08:00
|
|
|
|
2017-02-12 22:00:13 +08:00
|
|
|
// InjectData object
|
|
|
|
export const InjectData = {
|
2017-06-06 18:06:32 -07:00
|
|
|
|
|
|
|
// data object initialized with offset
|
|
|
|
_data: {
|
|
|
|
utcOffset: moment().utcOffset()
|
|
|
|
},
|
|
|
|
|
2017-02-12 22:00:13 +08:00
|
|
|
// encode object to string
|
2017-02-06 14:33:34 +08:00
|
|
|
_encode(ejson) {
|
|
|
|
const ejsonString = EJSON.stringify(ejson);
|
|
|
|
return encodeURIComponent(ejsonString);
|
|
|
|
},
|
|
|
|
|
2017-02-12 22:00:13 +08:00
|
|
|
// decode string to object
|
2017-02-06 14:33:34 +08:00
|
|
|
_decode(encodedEjson) {
|
|
|
|
const decodedEjsonString = decodeURIComponent(encodedEjson);
|
|
|
|
if (!decodedEjsonString) return null;
|
|
|
|
return EJSON.parse(decodedEjsonString);
|
|
|
|
},
|
|
|
|
|
2017-02-12 22:00:13 +08:00
|
|
|
// push data to res._injectPayload and generate res._injectHtml
|
2017-02-06 14:33:34 +08:00
|
|
|
pushData(res, key, value) {
|
2017-06-06 18:06:32 -07:00
|
|
|
|
|
|
|
this._data[key] = value;
|
|
|
|
|
2017-02-06 14:33:34 +08:00
|
|
|
if (!res._injectPayload) {
|
|
|
|
res._injectPayload = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
res._injectPayload[key] = value;
|
|
|
|
|
|
|
|
// if cors headers included if may cause some security holes
|
|
|
|
// so we simply turn off injecting if we detect an cors header
|
|
|
|
// read more: http://goo.gl/eGwb4e
|
2017-02-15 21:07:36 +08:00
|
|
|
if (res._headers && res._headers['access-control-allow-origin']) {
|
|
|
|
const warnMessage =
|
|
|
|
'warn: injecting data turned off due to CORS headers. ' +
|
|
|
|
'read more: http://goo.gl/eGwb4e';
|
|
|
|
console.warn(warnMessage); // eslint-disable-line no-console
|
|
|
|
return;
|
|
|
|
}
|
2017-02-06 14:33:34 +08:00
|
|
|
|
|
|
|
// inject data
|
|
|
|
const data = this._encode(res._injectPayload);
|
|
|
|
res._injectHtml = `<script type="text/inject-data">${data}</script>`;
|
|
|
|
},
|
|
|
|
|
2017-02-12 22:00:13 +08:00
|
|
|
// get data from res._injectPayload
|
2017-02-06 14:33:34 +08:00
|
|
|
getData(res, key) {
|
|
|
|
if (res._injectPayload) {
|
|
|
|
// same as _.clone(res._injectPayload[key]);
|
|
|
|
const data = res._injectPayload[key];
|
|
|
|
const clonedData = EJSON.parse(EJSON.stringify(data));
|
|
|
|
return clonedData;
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
},
|
|
|
|
};
|
2017-02-12 22:00:13 +08:00
|
|
|
|
|
|
|
// **injectDataMiddleware, Notes that it must after router connect handler**
|
|
|
|
webAppConnectHandlersUse(function injectDataMiddleware(req, res, next) {
|
|
|
|
if (res._injectHtml) {
|
|
|
|
req.dynamicHead = req.dynamicHead || '';
|
|
|
|
req.dynamicHead += res._injectHtml;
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
}, { order: 900 });
|