2.0.3 • Published 3 years ago

@myparcel/js-sdk v2.0.3

Weekly downloads
29
License
GPL-3.0
Repository
-
Last release
3 years ago

Content

Installation

npm install @myparcel/js-sdk
yarn add @myparcel/js-sdk

The MyParcel SDK should work with node version >= 8

Git hooks

This repository uses git hooks with Husky.

pre-commit

Runs npm run build before committing and adds the dist folder to the commit you are making.

Use --no-verify with git commit to skip this hook, if needed.

To use this hook while committing from PhpStorm you must have "Run git hooks" checked in the commit dialog. Uncheck it to skip the hook.

Quick start

import Client from '@myparcel/js-sdk';

const client = new Client('api_key_from_MyParcel_backoffice');

// Create one or more new shipments
const ids = await client.shipment.create(shipmentObj);

// Update one or more shipments
const shipments = await client.shipment.update(shipmentObj);

// Delete one or more shipments
await client.shipment.delete(shipmentIds);

// Retrieve multiple shipments
const shipments = await client.shipment.search(queryObj);

// Retrieve a single shipment
const shipment = await client.shipment.get(shipmentId);

Constructor options

NameTypeDescription
keystringOptional. An api key of your account.
acceptLanguagestringOptional. Set to negotiate the response language.

Endpoints

EndpointSupported methodsKey requiredAPI Reference
shipmentcreate, update, delete, get, searchYeshttps://myparcelnl.github.io/api/#6_A
deliverysearchNohttps://myparcelnl.github.io/api/#9_A
pickupsearchNohttps://myparcelnl.github.io/api/#9_B
labelcreateYeshttps://myparcelnl.github.io/api/#6_F
tracktraceget, searchYeshttps://myparcelnl.github.io/api/#6_G

Endpoint methods

Every method is async.

SignatureDescriptionReturns
create({ /* resource data */ })Create a single resource.An array of integer ids.
create([ /* resource objects */ ])Create multiple resources.An array of integer ids.
update({ /* resource data */ })Update a single resource.An array of objects.
update([ /* resource objects */ ])Update multiple resources.An array of objects.
delete(id)Delete one resource.null.
delete([ /* ids */ ])Delete multiple resources.null.
get(id)Retrieve a single resource.An object.
search({ /* filter data */ })Retrieves multiple instances.An array of objects.

Constants

We defined a large set of constant values suitable to help to build the payload.

CategoryLabelDescription
shipmentsCarrierIdsCarrier ID's
shipmentsContent TypesSet of content types.
shipmentsDelivery TypesSet of deliveries.
shipmentsEPS CountriesEuropean countries.
shipmentsMultiCollo CountriesCountries which support shipment with multiple packages.
shipmentsPackage TypesSet of define parcels.
shipmentsRegionsRegions (EU / ROW / Home Country)
shipmentsShipment TypesTypes to define the shipment.
shipmentsDelivery StatussesDifferent states for indication the delivery status.
labelsPaper TypesDifferent set of Paper formats.
labelsPrint PositionsDirections of the pinting positions.

Countries ISO2

A list of all countries over the world with their ISO-2 code.

Examples

For more examples, see the API docs

Create a domestic shipment

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id'
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type'

const client = new Client('api_key_from_MyParcel_backoffice');

const createShipment = async () => {
    return await client.shipment.create({
        "carrier": POSTNL,
        "reference_identifier" : "FOO-222-BAR-42",
        "recipient": {
            "cc": "NL",
            "region": "Zuid-Holland",
            "city": "Hoofddorp",
            "street": "Siriusdreef",
            "number": "66",
            "postal_code": "2132WT",
            "person": "Mr. Parcel",
            "phone": "0213030315",
            "email": "testing@myparcel.nl"
        },
        "options": {
            "package_type": PARCEL,
            "only_recipient": 1,
            "signature": 1,
            "return": 1,
            "insurance": {
                "amount": 50000,
                "currency": "EUR"
            },
            "large_format": 0,
            "label_description": "My custom description",
            "age_check":1
        },
    })
}
createShipment().then(
    (result) => console.log('Success!\n\n', result),
    (error) => console.error('Something went wrong\n\n', error),
);

Create an international shipment

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id'
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type'

const client = new Client('api_key_from_MyParcel_backoffice');

const createShipment = async () => {
    return await client.shipment.create({
        "carrier": POSTNL,
        "recipient": {
            "cc": "JP",
            "region": "埼玉県",
            "city": "さいたま市",
            "street": "埼玉県さいたま市浦和区 常盤9-21-21",
            "person": "Tanaka san",
            "company": "さいたま国際キリスト教会",
            "email": "saitamakyokai@gmail.com",
            "phone": "0081-48-825-6637"
        },
        "options": {
            "package_type": PARCEL
        },
        "customs_declaration": {
            "contents": 1,
            "invoice": "1231235345345",
            "weight": 30,
            "items": [{
                "description": "Sample Product",
                "amount": 10,
                "weight": 20,
                "item_value": {
                    "amount": 7000,
                    "currency": "EUR"
                },
                "classification": "0181",
                "country": "NL"
            }, {
                "description": "Sample Product 2",
                "amount": 5,
                "weight": 10,
                "item_value": {
                    "amount": 1000,
                    "currency": "EUR"
                },
                "classification": "0181",
                "country": "BE"
            }]
        },
        "physical_properties": {
            "weight": 30
        }
    });
}
createShipment().then(
    (result) => console.log('Success!\n\n', result),
    (error) => console.error('Something went wrong\n\n', error),
);

Retrieve delivery types and pickup locations

import Client from '@myparcel/js-sdk';

const client = new Client('api_key_from_MyParcel_backoffice');

const deliveryTypes = await client.delivery.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

const pickupLocations = await client.pickup.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

Create a shipment with a pickup location

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id';
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type';
import {PICKUP} from '@myparcel-sdk/dist/constant/shipment/delivery-type';

const client = new Client('api_key_from_MyParcel_backoffice');

const pickupLocations = await client.pickup.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

/**
* Transform a pickup information object to a shipment pickup.
*
* @param {object} pickup
* @returns {object}
*/
const makeShipmentPickup = ({postal_code, street, city, number, location_name}) => ({postal_code, street, city, number, location_name});

const [id] = await client.shipment.create({
    "carrier": POSTNL,
    "reference_identifier" : "FOO-222-BAR-42",
    "recipient": {
        "cc": "NL",
        "region": "Zuid-Holland",
        "city": "Hoofddorp",
        "street": "Siriusdreef",
        "number": "66",
        "postal_code": "2132WT",
        "person": "Mr. Parcel",
        "phone": "0213030315",
        "email": "testing@myparcel.nl"
    },
    "options": {
        "package_type": PARCEL,
        "delivery_type": PICKUP,
        "only_recipient": 1,
        "signature": 1,
        "return": 1,
        "insurance": {
            "amount": 50000,
            "currency": "EUR"
        },
        "large_format": 0,
        "label_description": "My custom description",
        "age_check":1
    },
    "pickup": makeShipmentPickup(pickupLocations[0]),
});

Download a label

import Client from '@myparcel/js-sdk';
import {A4} from '@myparcel/js-sdk/dist/constant/label/paper-type';
import fetch from 'node-fetch';
import fs from 'fs';

const client = new Client('api_key_from_MyParcel_backoffice');

// Ask the api to create a label for the given ids.
const [{url}] = await client.label.create({
    // See https://myparcelnl.github.io/api/#6_F_3 for all parameters
    ids: [
      // Add your shipment ids
    ],
    format: A4,
});

// The label might not be available for download right away. This could be because
// the requested label is very large, or one of the partners takes a while to respond.

while (true) {
    const response = await fetch(url);

    if (response.status !== 200) {
      // If the label is not available (yet), wait for a bit and try again
      // We strongly recommend that the retry code has sensible retry limits,
      // both in timeout and attempts.
      if (response.status === 404) {
        await new Promise(resolve => setTimeout(resolve, 500));
        continue;
      } else {
        // Something went wrong, stop retrying.
        break;
      }
    }

    // The label is now ready to use. For example, write it to file or send it to the client.
    const file = fs.createWriteStream('myparcel-label.pdf');
    response.body.pipe(file);
}

Contribute

  1. Check for open issues or open a new issue to start a discussion around a bug or feature.
  2. Fork the repository on GitHub to start making your changes.
  3. Write one or more tests for the new feature or that expose the bug.
  4. Make code changes to implement the feature or fix the bug.
  5. Send a pull request to get your changes merged and published.