t3rminus / canada-post

Wrapper for the Canada Post API
MIT License
19 stars 10 forks source link

Add support for multple errors returned #6

Closed wesbos closed 3 years ago

wesbos commented 3 years ago

thanks for the lib!

Looks like canada post will return an array of errors if multiple things are wrong. Currently it just swallows that error.

t3rminus commented 3 years ago

Oh! Absolutely a good idea. Can you give me an example of a request with multiple errors, so I can add a test case for this, and make sure everything works as expected?

Then I can merge your PR.

wesbos commented 3 years ago

Great! This should cause the following errors:

{
  '$': { xmlns: 'http://www.canadapost.ca/ws/messages' },
  message: [
    {
      code: '2695',
      description: 'Contact Phone number is a required field.'
    },
    {
      code: '1151',
      description: 'At least one line of Customs Description must be supplied.'
    },
    {
      code: '8716',
      description: 'This product requires a valid value for Non-Delivery Handling.'
    }
  ]
}
const shipment4 = {
  requestedShippingPoint: 'M4X1P1',
  deliverySpec: {
    serviceCode: 'USA.XP',
    sender: {
      company: 'Wes Bos',
      contactPhone: '911',
      addressDetails: {
        addressLine1: '123 fake street',
        city: 'Fake',
        provState: 'ON',
        postalZipCode: 'M4X1P1'
      }
    },
    destination: {
      name: 'Larry David',
      addressDetails: {
        addressLine1: "123 Fake street",
        city: 'Denver',
        provState: 'CO',
        postalZipCode: '90210',
        countryCode: 'US'
      }
    },
    parcelCharacteristics: {
      weight: 1,
      document: false,
      dimensions: {
        length: 23,
        width: 18,
        height: 10
      }
    },
    preferences: {
      showPackingInstructions: true,
      showPostageRate: false,
      showInsuredValue: false
    },
    references: {
      customerRef1: 'test'
    },
  }
};

async function createShipment() {
  const res = await client.createNonContractShipment(shipment4);

  console.log(res);
}

createShipment().catch(console.error);
t3rminus commented 3 years ago

I moved some error parsing code into the CanadaPostError constructor. I also included the original messages in the error, to make parsing/iterating over them easier.

error.code is never an array (it now concatenates codes with ,), but you can use error.originalMessages to loop over them if you need individual codes.

Pushed to NPM as v1.2.0