@hhgtech/hhg-components
Version:
Hello Health Group common components
380 lines (373 loc) • 17.7 kB
JavaScript
;
var tslib_es6 = require('./tslib.es6-92cccef3.js');
var index = require('./index-3020fcb3.js');
var miscCookieHelper = require('./miscCookieHelper.js');
var slugify = require('slugify');
var constantsIsProduction = require('./constantsIsProduction.js');
var formatString = require('string-format');
var React = require('react');
var togetherApiPaths = require('./togetherApiPaths.js');
var constants = require('./constants-bb30dda6.js');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
var slugify__default = /*#__PURE__*/_interopDefault(slugify);
var formatString__default = /*#__PURE__*/_interopDefault(formatString);
var React__default = /*#__PURE__*/_interopDefault(React);
const DefaultComponentGlobalContextData = {
locale: 'vi-VN',
env: {
isMarryBaby: false,
togetherBasePath: '/community',
},
router: {
basePath: '',
asPath: '/',
},
};
const TogetherComponentGlobalContext = React.createContext({
data: DefaultComponentGlobalContextData,
action: {
pushNotifications: (s) => s,
sanitizeFunction: (s) => s,
},
formatMessage: () => null,
});
exports.GlobalData = DefaultComponentGlobalContextData;
const TogetherComponentGlobalContextProvider = ({ locale = 'vi-VN', children, userInfo, router, env = {
isMarryBaby: false,
togetherBasePath: '/community',
}, sanitizeFunction = (s) => s, pushNotifications = () => false, formatMessage, }) => {
const [togetherUserId, setTogetherUserId] = React.useState();
exports.GlobalData = {
userInfo,
locale,
togetherUserId,
router,
env,
};
React.useEffect(() => {
if (userInfo === null || userInfo === void 0 ? void 0 : userInfo.id) {
callApiWithAuth(getApiPath(togetherApiPaths.PATHS.PROFILE, {
_locale: locale,
}), 'GET').then((res) => {
var _a;
setTogetherUserId((_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.id);
});
}
}, [userInfo === null || userInfo === void 0 ? void 0 : userInfo.id]);
return (React__default["default"].createElement(TogetherComponentGlobalContext.Provider, { value: {
data: {
userInfo,
locale,
togetherUserId,
router,
env,
},
action: {
pushNotifications,
sanitizeFunction,
},
formatMessage,
} }, children));
};
// import { DISCOVER_PATHS, PATHS } from './paths'
// let _apolloClient:ApolloClient<NormalizedCacheObject>
const domainLocales = {
'vi-VN': 'hellobacsi.com',
'id-ID': 'hellosehat.com',
'ms-MY': 'hellodoktor.com',
'km-KH': 'hellokrupet.com',
'en-PH': 'hellodoctor.com.ph',
'th-TH': 'hellokhunmor.com',
'my-MM': 'hellosayarwon.com',
'zh-TW': 'helloyishi.com.tw',
'hi-IN': 'helloswasthya.com',
};
const domainLocalesMarryBaby = {
'vi-VN': 'marrybaby.vn',
};
const locale = (process.env.NEXT_PUBLIC_DEPLOY_LOCALE ||
'vi-VN');
const getWebsiteUrlApi = (locale) => {
const { env: { isMarryBaby }, } = exports.GlobalData;
return `https://${isMarryBaby ? domainLocalesMarryBaby[locale] : domainLocales[locale]}`;
};
const cleanFormatString = (url) => {
const qIndex = url.indexOf('?');
if (qIndex >= 0) {
return (url.slice(0, qIndex + 1) +
url
.slice(qIndex + 1)
.replace(/[^=&]+=(&|$)/g, '')
.replace(/&$/, ''));
}
return url;
};
const getCurrentBaseUrl = (locale) => {
const { env: { isMarryBaby }, } = exports.GlobalData;
if (typeof window !== 'undefined')
return window.location.origin;
const isStaging = process.env.NEXT_PUBLIC_DEPLOY_ENV === 'staging';
const isDev = process.env.NEXT_PUBLIC_DEPLOY_ENV === 'development';
return isDev
? 'http://localhost:3000'
: `https://${isStaging
? isMarryBaby
? 'fe.'
: 'discover.'
: isMarryBaby
? 'www.'
: ''}${domainLocales[locale]}`;
};
const getCurrentHref = (locale, basePath, asPath) => {
if (typeof window !== 'undefined')
return window.location.href;
return `${getCurrentBaseUrl(locale)}${basePath}${asPath}`;
};
const getApiPath = (path, params, query, baseUrl) => {
let queryString = '';
if (query) {
queryString = Object.keys(query)
.map((key) => key + '=' + query[key])
.join('&');
}
const { togetherBaseApiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
let formattedPath = formatString__default["default"](path, Object.assign(Object.assign({}, ((params === null || params === void 0 ? void 0 : params._locale)
? {
website_url: getWebsiteUrlApi(String(params._locale)),
}
: {})), params));
formattedPath += `${formattedPath.includes('?') ? '&' : '?'}${queryString}`;
const baseApiUrl = baseUrl ? baseUrl : togetherBaseApiUrl;
return baseApiUrl + 'api/v1/' + cleanFormatString(formattedPath);
};
const getDiscoverApiPath = (path, params, useProOnDev) => {
const { discoverBaseApiUrl = '', discoverBaseProdApiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
const basePath = !constantsIsProduction.isProduction && useProOnDev ? discoverBaseProdApiUrl : discoverBaseApiUrl;
return (basePath +
'wp-json/api/' +
cleanFormatString(formatString__default["default"](path, Object.assign({}, params))));
};
const getMarryBabyApiPath = (path, params, useProOnDev) => {
const { marryBabyApiUrl = '', marryBabyProdApiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
const basePath = useProOnDev && !constantsIsProduction.isProduction ? marryBabyProdApiUrl : marryBabyApiUrl;
return (basePath +
'wp-json/api/' +
cleanFormatString(formatString__default["default"](path, Object.assign({}, params))));
};
const getCarePath = (path, params) => {
const { careBaseApiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
return ((careBaseApiUrl || 'https://service-health-care.hellohealthgroup.com/') +
cleanFormatString(formatString__default["default"](path, Object.assign({}, params))));
};
const getPremiumApiPath = (path, params) => {
const { premiumBaseApiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
return ((premiumBaseApiUrl ||
'https://premium-content-stag.hellohealthgroup.com/') +
cleanFormatString(formatString__default["default"](path, Object.assign({}, params))));
};
const getSsoApiPath = (path, params) => {
const { publicSSO = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
return ((publicSSO || 'https://staging-id.hellobacsi.com/') +
'api/' +
cleanFormatString(formatString__default["default"](path, Object.assign({}, params))));
};
const getChatbotAiApiPath = (path, params) => {
const { chatbotAiUrl = '' } = (exports.GlobalData === null || exports.GlobalData === void 0 ? void 0 : exports.GlobalData.env) || {};
return ((chatbotAiUrl || 'https://chatbot-staging-v2.hellohealthgroup.com/') +
cleanFormatString(formatString__default["default"](path, Object.assign(Object.assign({}, ((params === null || params === void 0 ? void 0 : params._locale)
? {
website_url: getWebsiteUrlApi(String(params._locale)),
}
: {})), params))));
};
const fixedEncodeURI = (str) => {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
};
const convertApiOptionsToRequestInit = (opts) => {
if (opts === null || opts === void 0 ? void 0 : opts.data) {
if (opts.data instanceof FormData) {
opts.body = opts.data;
}
else if (typeof opts.data === 'object') {
opts.body = JSON.stringify(opts.data);
}
delete opts.data;
}
return opts;
};
const callApi = (url, method, options, skipEncodeURI = false) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
var _a, _b, _c;
try {
const res = yield fetch(skipEncodeURI ? url : fixedEncodeURI(url), Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({}, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json());
if (res)
return res;
}
catch (err) {
console.log(err);
console.log({
url,
status: (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.status,
statusText: (_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.statusText,
});
// Sentry.captureException(err)
return ((_c = err === null || err === void 0 ? void 0 : err.response) === null || _c === void 0 ? void 0 : _c.data) || null;
}
return null;
});
const callApiWithOptionalAuth = (urlData, method = 'GET', options, reqCookie) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
var _d, _e, _f, _g, _h, _j;
try {
const url = typeof urlData === 'string' ? urlData : urlData.url;
const backupUrl = typeof urlData === 'string' ? urlData : urlData.backupUrl;
const parsedCookie = index.cookie.parse(reqCookie || '');
const token = parsedCookie[constants.BEARER_TOKEN_COOKIE];
const cookie = token || miscCookieHelper.getCookie(constants.BEARER_TOKEN_COOKIE);
if (cookie && cookie.length) {
try {
const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json());
if ((_d = res === null || res === void 0 ? void 0 : res.messages) === null || _d === void 0 ? void 0 : _d.find((m) => (m === null || m === void 0 ? void 0 : m.toLowerCase()) === 'Unauthenticated')) {
return callApi(backupUrl || url, method, options);
}
if (res)
return res;
}
catch (err) {
console.log({
status: (_e = err === null || err === void 0 ? void 0 : err.response) === null || _e === void 0 ? void 0 : _e.status,
statusText: (_f = err === null || err === void 0 ? void 0 : err.response) === null || _f === void 0 ? void 0 : _f.statusText,
});
// Fallback noauth call
return callApi(backupUrl || url, method, options);
}
}
else {
return callApi(backupUrl || url, method, options);
}
}
catch (err) {
console.log({
status: (_g = err === null || err === void 0 ? void 0 : err.response) === null || _g === void 0 ? void 0 : _g.status,
statusText: (_h = err === null || err === void 0 ? void 0 : err.response) === null || _h === void 0 ? void 0 : _h.statusText,
});
// Sentry.captureException(err)
return ((_j = err === null || err === void 0 ? void 0 : err.response) === null || _j === void 0 ? void 0 : _j.data) || null;
}
return null;
});
const callApiWithAuth = (url, method, options, reqCookie) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
try {
const parsedCookie = index.cookie.parse(reqCookie || '');
const token = parsedCookie[constants.BEARER_TOKEN_COOKIE];
const cookie = token || miscCookieHelper.getCookie(constants.BEARER_TOKEN_COOKIE);
if (cookie && cookie.length) {
const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json());
if (res)
return res;
}
}
catch (err) {
// Sentry.captureException(err)
return null;
}
return null;
});
const callApiWithAdminAuth = (url, method, options, reqCookie) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
try {
const parsedCookie = index.cookie.parse(reqCookie || '');
const token = parsedCookie[constants.BEARER_ADMIN_TOKEN_COOKIE];
const cookie = token || miscCookieHelper.getCookie(constants.BEARER_ADMIN_TOKEN_COOKIE);
if (cookie && cookie.length) {
const res = yield fetch(url, Object.assign(Object.assign({ method }, convertApiOptionsToRequestInit(options)), { headers: Object.assign({ Authorization: 'Bearer ' + cookie }, options === null || options === void 0 ? void 0 : options.headers) })).then((r) => r.json());
if (res)
return res;
}
}
catch (err) {
// Sentry.captureException(err)
return null;
}
return null;
});
function updateQueryStringParameter(uri, key, value) {
const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
const separator = uri.indexOf('?') !== -1 ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, '$1' + key + '=' + value + '$2');
}
else {
return uri + separator + key + '=' + value;
}
}
const getUrlToSSOWithReturnUrl = (url, params) => {
const { publicSSO } = exports.GlobalData.env;
const originalRedirectUrl = url || window.location.href;
// const redirectUrl = new URL(originalRedirectUrl)
if (params) {
Object.keys(params).map((k) => {
updateQueryStringParameter(originalRedirectUrl, k, params[k]);
});
}
updateQueryStringParameter(originalRedirectUrl, 'source', 'communities');
return publicSSO
? `${publicSSO}?returnUrl=${encodeURIComponent(originalRedirectUrl.toString())}`
: originalRedirectUrl;
};
const getUrlToSignUp = (url, params, togetherBasePath = '/community') => {
const currentLocation = url || (typeof window !== 'undefined' ? window.location.href : '/');
let origin = typeof window !== 'undefined' ? window.location.origin : '';
if (!origin) {
if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
origin = url.split('/').slice(0, 3).join('/');
}
}
const onBoardingUrl = `${origin}${togetherBasePath}/on-boarding?return=${encodeURIComponent(currentLocation)}`;
return getUrlToSSOWithReturnUrl(onBoardingUrl, params);
};
const slugifiedNameWithId = (name, id, slug, _locale) => {
if (slug && id) {
return `${slug}-${id}`;
}
return `${slugify__default["default"](name || '', {
lower: true,
locale: _locale || locale,
})}-${id}`;
};
const getCareDoctorUrl = ({ name, id, locale, }) => {
var _a;
return `/care/${(_a = constants.LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.DOCTOR}/${slugifiedNameWithId(name, id)}`;
};
const getCareHospitalUrl = ({ name, id, slug, locale, }) => {
var _a;
return `/care/${(_a = constants.LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.HOSPITAL}/${slugifiedNameWithId(name, id, slug)}`;
};
const getCareHospitalUrlAmp = ({ slug, id, locale, }) => {
var _a;
return `/care/${(_a = constants.LOCALISED_SLUGS[locale || 'vi-VN']) === null || _a === void 0 ? void 0 : _a.HOSPITAL}/${slug}-${id}`;
};
exports.DefaultComponentGlobalContextData = DefaultComponentGlobalContextData;
exports.TogetherComponentGlobalContext = TogetherComponentGlobalContext;
exports.TogetherComponentGlobalContextProvider = TogetherComponentGlobalContextProvider;
exports.callApi = callApi;
exports.callApiWithAdminAuth = callApiWithAdminAuth;
exports.callApiWithAuth = callApiWithAuth;
exports.callApiWithOptionalAuth = callApiWithOptionalAuth;
exports.domainLocales = domainLocales;
exports.domainLocalesMarryBaby = domainLocalesMarryBaby;
exports.getApiPath = getApiPath;
exports.getCareDoctorUrl = getCareDoctorUrl;
exports.getCareHospitalUrl = getCareHospitalUrl;
exports.getCareHospitalUrlAmp = getCareHospitalUrlAmp;
exports.getCarePath = getCarePath;
exports.getChatbotAiApiPath = getChatbotAiApiPath;
exports.getCurrentBaseUrl = getCurrentBaseUrl;
exports.getCurrentHref = getCurrentHref;
exports.getDiscoverApiPath = getDiscoverApiPath;
exports.getMarryBabyApiPath = getMarryBabyApiPath;
exports.getPremiumApiPath = getPremiumApiPath;
exports.getSsoApiPath = getSsoApiPath;
exports.getUrlToSSOWithReturnUrl = getUrlToSSOWithReturnUrl;
exports.getUrlToSignUp = getUrlToSignUp;
exports.getWebsiteUrlApi = getWebsiteUrlApi;
exports.locale = locale;
exports.slugifiedNameWithId = slugifiedNameWithId;
exports.updateQueryStringParameter = updateQueryStringParameter;