import axios from 'axios'; import apiUrls from 'shared/constants/api_urls'; import {getCurrentEnv} from 'shared/utils/common'; import {Address, AddressAttributes} from 'checkout/ShippingAddressProps'; import {Cart} from 'checkout/CartProps'; function headers(accessToken: string) { if (accessToken) { return { 'Content-Type': 'application/vnd.api+json', Authorization: 'Bearer ' + accessToken }; } else { return { 'Content-Type': 'application/vnd.api+json' }; } } function apiUrl(api: string, endpoint: string): string { return apiUrls[getCurrentEnv()][api] + endpoint; } export async function getAddresses( accessToken: string ): Promise> { return axios({ method: 'get', headers: headers(accessToken), url: apiUrl('userApi', '/addresses/') }) .then(resp => resp.data.data.filter((a: Address) => a.attributes.source === 'moda') ) .catch(e => { console.error(e); return []; }); } export async function validateAddress( address: AddressAttributes, accessToken: string ): Promise { return axios({ method: 'post', headers: headers(accessToken), url: apiUrl('userApi', '/addresses/validate/'), data: JSON.stringify({ data: { type: 'address', attributes: {...address} } }) }) .then(resp => resp.data.data[0].attributes) .catch(e => { console.log(e); return address; }); } export async function createAddress( address: AddressAttributes, accessToken: string ): Promise
{ return axios({ method: 'post', headers: headers(accessToken), url: apiUrl('userApi', '/addresses'), data: JSON.stringify({ data: { type: 'address', attributes: {...address} } }) }) .then(resp => resp.data.data) .catch(e => { console.log(e); return {attributes: address}; }); } export async function editAddress( address: AddressAttributes, id: string, accessToken: string ): Promise
{ return axios({ method: 'patch', headers: headers(accessToken), url: apiUrl('userApi', `/addresses/${id}/`), data: JSON.stringify({ data: { id, type: 'address', attributes: {...address} } }) }) .then(resp => resp.data.data) .catch(e => { console.error(e); return {attributes: address}; }); } export async function updateCart( id: string, type: string, actionType: string, attributes: object, accessToken: string ): Promise { return axios({ method: 'patch', headers: headers(accessToken), url: `${apiUrls[getCurrentEnv()].mojoApi}/carts/${id}`, data: JSON.stringify({ //eslint-disable-next-line @typescript-eslint/camelcase data: {type: type, action_type: actionType, attributes: attributes} }) }) .then(resp => resp.data['data'][0]) .catch(e => { console.error(e); return {attributes: attributes}; }); } export async function updateLineItem( id: string, type: string, attributes: object, accessToken: string ): Promise { return axios({ method: 'patch', headers: headers(accessToken), url: `${apiUrls[getCurrentEnv()].mojoApi}/line_items/${id}`, data: JSON.stringify({ data: {type: 'line_items', attributes: attributes} }) }) .then(resp => resp.data['data'][0]) .catch(e => { console.error(e); return {attributes: attributes}; }); }