Skip to content

Commit

Permalink
Merge pull request #10 from niloo-fs/niloofar/75915/convert-shared-ut…
Browse files Browse the repository at this point in the history
…iles-to-ts

Niloofar Sadeghi / Convert login, object, os, platform, promise to TS [shared-utiles]
  • Loading branch information
jim-deriv authored Sep 29, 2022
2 parents be2caff + fa09004 commit fe20da8
Show file tree
Hide file tree
Showing 17 changed files with 102 additions and 82 deletions.
4 changes: 0 additions & 4 deletions packages/shared/src/utils/brand/brand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ type TPlatforms = {
go: TPlatform;
};

export const getBrandName = () => {
return config_data.brand_name;
};

export const getLegalEntityName = (landing_company: keyof TLandingCompany) => {
return config_data.legal_entities[landing_company];
};
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/src/utils/browser/browser_detect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
declare global {
interface Window {
safari?: any;
HTMLElement: any;
safari?: { pushNotification: () => void };
HTMLElement: HTMLElement & string;
}
}

Expand Down
34 changes: 14 additions & 20 deletions packages/shared/src/utils/cfd/cfd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { LandingCompany, GetAccountStatus, DetailsOfEachMT5Loginid } from '@deri
let CFD_text_translated: { [key: string]: () => void };

// TODO: add swap_free to this file when ready

const CFD_text: { [key: string]: string } = {
dxtrade: 'Deriv X',
mt5: 'MT5',
Expand All @@ -18,30 +17,30 @@ const CFD_text: { [key: string]: string } = {
financial_fx: 'Financial Labuan',
financial_v: 'Financial Vanuatu',
financial_svg: 'Financial SVG',
};
} as const;

// * mt5_login_list returns these:
// market_type: "financial" | "gaming"
// sub_account_type: "financial" | "financial_stp" | "swap_free"
// *
// sub_account_type financial_stp only happens in "financial" market_type
type TPlatform = 'dxtrade' | 'mt5';
type TMarketType = 'all' | 'financial' | 'synthetic' | 'gaming' | undefined;
type TMarketType = 'financial' | 'synthetic' | 'gaming' | 'all' | undefined;
type TShortcode = 'svg' | 'bvi' | 'labuan' | 'vanuatu';
type TGetAccount = {
market_type: TMarketType;
sub_account_type?: 'financial' | 'financial_stp' | 'swap_free';
platform: TPlatform;
};

type TGetCFDAccountKey = TGetAccount & {
shortcode?: TShortcode;
};

// * mt5_login_list returns these:
// market_type: "financial" | "gaming"
// sub_account_type: "financial" | "financial_stp" | "swap_free"
// *
// sub_account_type financial_stp only happens in "financial" market_type
export const getCFDAccountKey = ({ market_type, sub_account_type, platform, shortcode }: TGetCFDAccountKey) => {
if (market_type === 'all') {
return 'dxtrade';
}

if (market_type === 'gaming' || market_type === 'synthetic') {
if (platform === CFD_PLATFORMS.DXTRADE || sub_account_type === 'financial') {
switch (shortcode) {
Expand Down Expand Up @@ -84,6 +83,7 @@ export const getCFDAccountKey = ({ market_type, sub_account_type, platform, shor
* @param {string} type [synthetic, financial, financial_stp]
* @return {string}
*/

type TGetAccountTypeFields = {
category: 'real' | 'demo';
type: 'financial' | 'synthetic';
Expand All @@ -94,15 +94,9 @@ type TAccountType = {
mt5_account_type?: string;
};

type TAccountTypes = {
synthetic: TAccountType;
financial: TAccountType;
};
type TAccountTypes = Record<TGetAccountTypeFields['type'], TAccountType>;

type TMapMode = {
real: TAccountTypes;
demo: TAccountTypes;
};
type TMapMode = Record<TGetAccountTypeFields['category'], TAccountTypes>;

export const getAccountTypeFields = ({ category, type }: TGetAccountTypeFields) => {
const map_mode: TMapMode = {
Expand Down Expand Up @@ -142,7 +136,7 @@ export const getCFDAccountDisplay = ({
shortcode,
is_mt5_trade_modal,
}: TGetCFDAccountDisplay) => {
let cfd_account_key: string | undefined = getCFDAccountKey({ market_type, sub_account_type, platform, shortcode });
let cfd_account_key = getCFDAccountKey({ market_type, sub_account_type, platform, shortcode });
if (!cfd_account_key) return undefined;

if (cfd_account_key === 'financial' && is_eu) {
Expand All @@ -158,14 +152,14 @@ type TGetCFDAccount = TGetAccount & {
};

export const getCFDAccount = ({ market_type, sub_account_type, platform, is_eu }: TGetCFDAccount) => {
let cfd_account_key: string | undefined = getCFDAccountKey({ market_type, sub_account_type, platform });
let cfd_account_key = getCFDAccountKey({ market_type, sub_account_type, platform });
if (!cfd_account_key) return undefined;

if (cfd_account_key === 'financial' && is_eu) {
cfd_account_key = 'cfd';
}

return CFD_text[cfd_account_key];
return CFD_text[cfd_account_key as keyof typeof CFD_text];
};

export const setSharedCFDText = (all_shared_CFD_text: { [key: string]: () => void }) => {
Expand Down
40 changes: 20 additions & 20 deletions packages/shared/src/utils/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { isStaging } from '../url/helpers';
export const livechat_license_id = 12049137;
export const livechat_client_id = '66aa088aad5a414484c1fd1fa8a5ace7';

export const domain_app_ids: { [key: string]: number } = {
export const domain_app_ids = {
// these domains as supported "production domains"
'deriv.app': 16929, // TODO: [app-link-refactor] - Remove backwards compatibility for `deriv.app`
'app.deriv.com': 16929,
Expand All @@ -25,7 +25,7 @@ export const domain_app_ids: { [key: string]: number } = {
'binary.com': 1,
};

export const platform_app_ids: { [key: string]: number } = {
export const platform_app_ids = {
derivgo: 23789,
};

Expand All @@ -34,7 +34,7 @@ export const getCurrentProductionDomain = () =>
Object.keys(domain_app_ids).find(domain => window.location.hostname === domain);

export const isProduction = () => {
const all_domains: string[] = Object.keys(domain_app_ids).map(domain => `(www\\.)?${domain.replace('.', '\\.')}`);
const all_domains = Object.keys(domain_app_ids).map(domain => `(www\\.)?${domain.replace('.', '\\.')}`);
return new RegExp(`^(${all_domains.join('|')})$`, 'i').test(window.location.hostname);
};

Expand All @@ -46,57 +46,57 @@ export const getAppId = () => {
let app_id = null;
const user_app_id = ''; // you can insert Application ID of your registered application here
const config_app_id = window.localStorage.getItem('config.app_id');
const current_domain: string = getCurrentProductionDomain() || '';
const current_domain = getCurrentProductionDomain() || '';
const platform = new URLSearchParams(window.location.search).get('platform');

// Added platform at the top since this should take precedence over the config_app_id
if (platform && platform_app_ids[platform]) {
app_id = platform_app_ids[platform];
if (platform && platform_app_ids[platform as keyof typeof platform_app_ids]) {
app_id = platform_app_ids[platform as keyof typeof platform_app_ids];
} else if (config_app_id) {
app_id = config_app_id;
} else if (user_app_id.length) {
window.localStorage.setItem('config.default_app_id', user_app_id);
app_id = user_app_id;
} else if (isStaging()) {
window.localStorage.removeItem('config.default_app_id');
app_id = isBot() ? 19112 : domain_app_ids[current_domain] || 16303; // it's being used in endpoint chrome extension - please do not remove
app_id = isBot() ? 19112 : domain_app_ids[current_domain as keyof typeof domain_app_ids] || 16303; // it's being used in endpoint chrome extension - please do not remove
} else if (/localhost/i.test(window.location.hostname)) {
app_id = 17044;
} else {
window.localStorage.removeItem('config.default_app_id');
app_id = (isBot() ? 19111 : domain_app_ids[current_domain]) || 16929;
app_id = (isBot() ? 19111 : domain_app_ids[current_domain as keyof typeof domain_app_ids]) || 16929;
}

return app_id;
};

export const getSocketURL = () => {
const local_storage_server_url: string | null = window.localStorage.getItem('config.server_url');
const local_storage_server_url = window.localStorage.getItem('config.server_url');
if (local_storage_server_url) return local_storage_server_url;

let active_loginid_from_url;
const search: string = window.location.search;
const search = window.location.search;
if (search) {
const params: URLSearchParams = new URLSearchParams(document.location.search.substring(1));
const params = new URLSearchParams(document.location.search.substring(1));
active_loginid_from_url = params.get('acct1');
}

const loginid: string | null | undefined = window.localStorage.getItem('active_loginid') || active_loginid_from_url;
const is_real: boolean | '' | null | undefined = loginid && !/^VRT/.test(loginid);
const loginid = window.localStorage.getItem('active_loginid') || active_loginid_from_url;
const is_real = loginid && !/^VRT/.test(loginid);

const server: 'green' | 'blue' = is_real ? 'green' : 'blue';
const server = is_real ? 'green' : 'blue';
const server_url = `${server}.binaryws.com`;

return server_url;
};

export const checkAndSetEndpointFromUrl = () => {
if (isTestLink()) {
const url_params: URLSearchParams = new URLSearchParams(location.search.slice(1));
const url_params = new URLSearchParams(location.search.slice(1));

if (url_params.has('qa_server') && url_params.has('app_id')) {
const qa_server: string = url_params.get('qa_server') || '';
const app_id: string = url_params.get('app_id') || '';
const qa_server = url_params.get('qa_server') || '';
const app_id = url_params.get('app_id') || '';

url_params.delete('qa_server');
url_params.delete('app_id');
Expand All @@ -111,8 +111,8 @@ export const checkAndSetEndpointFromUrl = () => {
localStorage.setItem('config.server_url', qa_server);
}

const params: string = url_params.toString();
const hash: string = location.hash;
const params = url_params.toString();
const hash = location.hash;

location.href = `${location.protocol}//${location.hostname}${location.pathname}${
params ? `?${params}` : ''
Expand All @@ -126,7 +126,7 @@ export const checkAndSetEndpointFromUrl = () => {
};

export const getDebugServiceWorker = () => {
const debug_service_worker_flag: string | null = window.localStorage.getItem('debug_service_worker');
const debug_service_worker_flag = window.localStorage.getItem('debug_service_worker');
if (debug_service_worker_flag) return !!parseInt(debug_service_worker_flag);

return false;
Expand Down
7 changes: 2 additions & 5 deletions packages/shared/src/utils/config/platform-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@ import { initMoment } from '../date';
import { routes } from '../routes';

type TPlatform = {
icon_text: undefined;
icon_text?: string;
is_hard_redirect: boolean;
platform_name: string;
route_to_path: string;
url: string;
};

type TPlatforms = {
p2p: TPlatform;
derivgo: TPlatform;
};
type TPlatforms = Record<'p2p' | 'derivgo', TPlatform>;

// TODO: This should be moved to PlatformContext
export const platforms: TPlatforms = {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CookieStorage, isStorageSupported, LocalStore } from '../storage/storag
import { getAppId, domain_app_ids } from '../config/config';
import { getStaticUrl, urlForCurrentDomain } from '../url';

export const redirectToLogin = (is_logged_in, language, has_params = true, redirect_delay = 0) => {
export const redirectToLogin = (is_logged_in: boolean, language: string, has_params = true, redirect_delay = 0) => {
if (!is_logged_in && isStorageSupported(sessionStorage)) {
const l = window.location;
const redirect_url = has_params ? window.location.href : `${l.protocol}//${l.host}${l.pathname}`;
Expand All @@ -15,11 +15,20 @@ export const redirectToLogin = (is_logged_in, language, has_params = true, redir
}
};

export const redirectToSignUp = ({ is_appstore }) => {
type TRedirectToSignUp = {
is_appstore?: boolean;
is_deriv_crypto?: boolean;
};

export const redirectToSignUp = ({ is_appstore }: TRedirectToSignUp) => {
window.open(getStaticUrl('/signup/', { is_appstore }));
};

export const loginUrl = ({ language }) => {
type TLoginUrl = {
language: string;
};

export const loginUrl = ({ language }: TLoginUrl) => {
const server_url = LocalStore.get('config.server_url');
const signup_device_cookie = new CookieStorage('signup_device');
const signup_device = signup_device_cookie.get('signup_device');
Expand All @@ -38,7 +47,7 @@ export const loginUrl = ({ language }) => {
return `https://${server_url}/oauth2/authorize?app_id=${getAppId()}&l=${language}${marketing_queries}&brand=${website_name.toLowerCase()}`;
}

if (getAppId() === domain_app_ids[window.location.hostname]) {
if (getAppId() === domain_app_ids[window.location.hostname as keyof typeof domain_app_ids]) {
return getOAuthUrl();
}
return urlForCurrentDomain(getOAuthUrl());
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/* eslint-disable */
const extend = require('extend');

export const removeObjProperties = (property_arr, { ...obj }) => {
export const removeObjProperties = (property_arr: string[], { ...obj }) => {
property_arr.forEach(property => delete obj[property]);
return obj;
};

export const filterObjProperties = ({ ...obj }, property_arr) =>
export const filterObjProperties = ({ ...obj }, property_arr: string[]) =>
Object.fromEntries(
Object.entries(obj)
// eslint-disable-next-line no-unused-vars
.filter(([key, _]) => property_arr.includes(key))
);

export const isEmptyObject = obj => {
export const isEmptyObject = (obj: any) => {
let is_empty = true;
if (obj && obj instanceof Object) {
Object.keys(obj).forEach(key => {
Expand All @@ -22,10 +23,10 @@ export const isEmptyObject = obj => {
return is_empty;
};

export const cloneObject = obj => (!isEmptyObject(obj) ? extend(true, Array.isArray(obj) ? [] : {}, obj) : obj);
export const cloneObject = (obj: any) => (!isEmptyObject(obj) ? extend(true, Array.isArray(obj) ? [] : {}, obj) : obj);

// Note that this function breaks on objects with circular references.
export const isDeepEqual = (a, b) => {
export const isDeepEqual = (a: any, b: any) => {
if (typeof a !== typeof b) {
return false;
} else if (Array.isArray(a)) {
Expand All @@ -39,19 +40,19 @@ export const isDeepEqual = (a, b) => {
return a === b;
};

export const isEqualArray = (arr1, arr2) =>
export const isEqualArray = (arr1: any[], arr2: any[]): boolean =>
arr1 === arr2 || (arr1.length === arr2.length && arr1.every((value, idx) => isDeepEqual(value, arr2[idx])));

export const isEqualObject = (obj1, obj2) =>
export const isEqualObject = (obj1: any, obj2: any): boolean =>
obj1 === obj2 ||
(Object.keys(obj1).length === Object.keys(obj2).length &&
Object.keys(obj1).every(key => isDeepEqual(obj1[key], obj2[key])));

// Filters out duplicates in an array of objects by key
export const unique = (array, key) =>
export const unique = (array: any[], key: string) =>
array.filter((e, idx) => array.findIndex((a, i) => (a[key] ? a[key] === e[key] : i === idx)) === idx);

export const getPropertyValue = (obj, k) => {
export const getPropertyValue = (obj: any, k: string | string[]): any => {
let keys = k;
if (!Array.isArray(keys)) keys = [keys];
if (!isEmptyObject(obj) && keys[0] in obj && keys && keys.length > 1) {
Expand All @@ -61,7 +62,7 @@ export const getPropertyValue = (obj, k) => {
return obj ? cloneObject(obj[keys[0]]) : undefined;
};

export const removeEmptyPropertiesFromObject = obj => {
export const removeEmptyPropertiesFromObject = (obj: any) => {
const clone = { ...obj };

Object.getOwnPropertyNames(obj).forEach(key => {
Expand All @@ -73,16 +74,16 @@ export const removeEmptyPropertiesFromObject = obj => {
return clone;
};

export const sequence = n => Array.from(Array(n).keys());
export const sequence = (n: number) => Array.from(Array(n).keys());

export const pick = (source, fields) => {
return fields.reduce((target, prop) => {
export const pick = (source: any, fields: any) => {
return fields.reduce((target: any, prop: any) => {
if (Object.prototype.hasOwnProperty.call(source, prop)) target[prop] = source[prop];
return target;
}, {});
};

export const findValueByKeyRecursively = (obj, key) => {
export const findValueByKeyRecursively = (obj: any, key: string) => {
let return_value;

Object.keys(obj).some(obj_key => {
Expand All @@ -109,7 +110,7 @@ export const findValueByKeyRecursively = (obj, key) => {
};

// Recursively freeze an object (deep freeze)
export const deepFreeze = obj => {
export const deepFreeze = (obj: any) => {
Object.getOwnPropertyNames(obj).forEach(key => {
const value = obj[key];
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
Expand Down
File renamed without changes.
Loading

0 comments on commit fe20da8

Please sign in to comment.