All files / app/address/googleAutocomplete mapToAddress.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48    25x   25x   3x   2x       2x 2x 2x 2x 2x   2x                     3x   2x 1x     2x 1x           1x          
import { Address, Country, Region } from '@bigcommerce/checkout-sdk';
 
import AddressSelectorFactory from './AddressSelectorFactory';
 
export default function mapToAddress(
    autocompleteData: google.maps.places.PlaceResult,
    countries: Country[] = []
): Partial<Address> {
    Iif (!autocompleteData || !autocompleteData.address_components) {
        return {};
    }
 
    const accessor = AddressSelectorFactory.create(autocompleteData);
    const state = accessor.getState();
    const countryCode = accessor.getCountry();
    const country = countries && countries.find(c => countryCode === c.code);
    const street2 = accessor.getStreet2();
 
    return {
        address2: street2,
        city: accessor.getCity(),
        countryCode,
        postalCode: accessor.getPostCode(),
        ...state ? getState(state, country && country.subdivisions) : {},
    };
}
 
function getState(
    stateName: string,
    states: Region[] = []
): Partial<Address> {
    const state = states.find(({ code, name }: Region) =>
        code === stateName || name === stateName
    );
 
    if (!state) {
        return {
            stateOrProvince: !states.length ? stateName : '',
            stateOrProvinceCode: '',
        };
    }
 
    return {
        stateOrProvince: state.name,
        stateOrProvinceCode: state.code,
    };
}