import superagent from 'superagent'; import { isEmpty, isNil } from 'ramda'; import { AjaxConfig, AjaxState } from './ajax.model'; import store from '../store/store'; const cache: any = {}; const pMemoize = (cb: any) => (...args: any) => { const key = JSON.stringify(args); if (cache[key]) { return cache[key]; } cache[key] = cb(...args); return cache[key]; }; export async function ajaxAction({ action, method = 'post', data = {}, isThirdParty = false, }: { action: string; method?: 'get' | 'post' | 'delete'; data?: any; isThirdParty?: boolean; }) { // @ts-ignore const ajaxUrl = window.ajaxurl; const request = superagent[method](ajaxUrl); if (method === 'get') { request.query({ ...data, action, }); } if (method === 'post') { const postData = new FormData(); postData.append('action', action); Object.entries(data).forEach(([key, value]) => { postData.append(key, value as any); }); request.send(postData); } try { const result = await request; if (!isThirdParty) { if (result.body.status === 'SUCCESS') { return result.body.payload; } throw new Error(`Error in request`); } return result.body; } catch (e) { console.error(e); if (!isThirdParty) { alert('There was an error making this request. Please try again.'); } return AjaxState.Error; } } export const ajaxActionMemoized = pMemoize(ajaxAction); export const getMemoized = pMemoize((url: string, query?: any) => { const request = superagent.get(url); if (query) { request.query(query); } return request; }); export async function ajaxApi(endpoint: string, config?: AjaxConfig) { const state = store.getState(); const token = state.authentication.token; const { method = 'get', data = {} } = config || {}; const request = superagent[method](`${process.env.API_URL}/${endpoint}`); if (data) { if (method === 'get') { request.query({ ...data, externalToken: token, }); } if (method === 'post') { request.send({ ...data, externalToken: token, }); } } try { const result = await request; return result.body.payload; } catch (e) { return null; } }