npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@address-checker/api

v1.6.3

Published

A JavaScript API which enables usage of the address checker.

Downloads

11

Readme

Address checker JavaScript API

This is an NPM package that provides an API for checking the validity of an address. In addition, developers may also make use of getting the required fields, their formats and helper and error text for specific countries. You can obtain your API key from the User Dashboard on the Address Checker website.

⚠️ If you intend to use this package for multiple countries, you should call changeCountry before calling any other method.

Installation

npm install --save @address-checker/api

Basic Usage

// Import the AddressChecker class, and any supporting types if needed
import { AddressChecker } from 'address-checker';

// Initialize the address checker
const addressChecker = new AddressChecker({
  publicKey: '<your-key>',
}, 'nl');

// Autocomplete
document.getElementById('my-input').addEventListener('change', (event) => {
  const query = event.target.value;
  
  if (query && query.length > 3) {
    addressChecker.autocomplete(query)
      .then((suggestions) => renderSuggestions(suggestions.map(s => s.formattedAddress)))
      .catch((error) => displayErrorMessage(error))
  }
});

// Validate
document.getElementById('my-form').addEventListener('submit', (event) => {
  event.preventDefault();
  
  const address = {
    street: document.getElementById('street').value,
    postalCode: document.getElementById('postal-code').value,
    city: document.getElementById('city').value,
    country: document.getElementById('country').value,
  };
  
  addressChecker.resolveAddressFromFormData(address)
    .then((address) => alert('Success: ' + address.formattedAddress))
    .catch((error) => displayErrorMessage(error));
});

// Get required fields
const getRequiredFields = async () => {
  const countrySchema = await addressChecker.changeCountry('fr').getFieldRequirements();
  console.log('The required fields for ' + countrySchema.country + ' are:');
  countrySchema.fields.flat().country.forEach((field) => {
    console.log(field.name + ' (Label: ' + field.label + ', Regex: ' + field.regex + ')');
  });
};

Initialization

The AddressChecker class is the main class that is exported from the package. It is used to interact with the API. As configuration, it accepts an object with the following properties:

  • publicKey - A string that represents the public key of the user. This is required to authenticate the user. That is the key that starts with vera_.
  • useL1L2FromServer - (optional, default=false) Boolean that tells the API whether it should use pre-fetched L1L2 schemas for a faster performance, or if it should fetch them from the server every time. The default option is false (i.e. use local data) since this is data that does not change often.

Types

All types are exported from the package and can be imported as needed. We note the following more important design decisions here:

  • type CountryCode, FullySupportedCountryCode, L1L2SupportedCountryCode - These types are used to represent a country code.
    • CountryCode is a string that represents any existing country code.1
    • FullySupportedCountryCode is a string that represents a country code that is fully supported by the API (i.e. the API interacts with the database of the country to verify an address).
    • L1L2SupportedCountryCode is a string that represents a country code for a country for which there are the required fields and their patterns.
  • type CountryFormSchema - This type is used to represent the required fields for a specific country. It is an object that contains the country name (string), country code (2-letter lowercase string), a number of recommended rows in a form, and an array of fields that are required for that country.
    • Each field is of type CountryFieldSchema and it has:
      • name - The name of the field.
      • label - A label of the field.
      • placeholder - A placeholder of the field.
      • regex - A regular expression that the field must match for it to be considered valid. 💡 Pro-tip: use this regex inside of the property pattern of an HTML input element to have field verification out of the box!
      • helperText - A helper text that can be displayed to the user.
      • errorText - An error text that can be displayed to the user.
      • flex - A number that represents the width of the field in a form. This is used to calculate the number of fields that can be displayed in a row.
  • type ResolvedAddress - This type is used to represent a resolved address. It is an object that contains the following fields:
    • formattedAddress - A string of the formatted address.
    • fields - An array of { name: '...', value: '...' }, or also noted as type FieldValue objects that represent the fields of the address. They also include a {name: 'formattedAddress', value: '...'} object if you prefer to extract it yourself.

Methods

All methods are exported from the package and can be imported as needed. We note the following more important design decisions here:

  • autocomplete(query: string): Promise<ResolvedAddress[]> - This method is used to give address suggestions based on a query. It returns a promise that resolves to an array of resolved addresses.
  • Resolving an address can be done in one of the following ways:
    • resolveAddress(tokens: FieldValue[]): Promise<ResolvedAddress> - This method is used to resolve an address from an array of field values. It returns a promise that resolves to a resolved address.
    • resolveAddressFromFormData(address: { [key: string]: string }): Promise<ResolvedAddress> - This method is used to resolve an address from a form data object. It returns a promise that resolves to a resolved address.
  • getFieldRequirements(): Promise<CountryFormSchema> - This method is used to get the required fields for the current country. It returns a promise that resolves to a country form schema. If the country is not supported, the default schema will be returned.2
  • changeCountry(countryCode: CountryCode): AddressChecker - This method is used to change the country of the address checker. It returns the address checker instance (internally, this).

1 A list of valid countries can be found inside the types file.

2 Default schema for a country:

export default {
  country: 'Default',
  countryCode: 'default',
  rows: 2,
  fields: [
    [
      {
        name: 'street',
        regex: '.*',
        isRequired: true,
        label: 'Town or City',
        placeholder: 'Enter City or Town',
        helperText: 'Enter your town or city',
        errorText: 'Invalid Settlement',
        flex: 2,
      },
      {
        name: 'houseNumber',
        regex: '.*',
        isRequired: true,
        label: 'House Number',
        placeholder: 'Enter your house number',
        helperText: 'Enter your town or city',
        errorText: 'Enter the number of your house, flat or unit',
        flex: 1,
      },
      {
        name: 'addition',
        regex: '.*',
        isRequired: false,
        label: 'Addition',
        placeholder: 'Address addition',
        helperText: 'Enter any additional information about your address',
        errorText: 'Addition is invalid',
        flex: 1,
      },
    ],
    [
      {
        name: 'postCode',
        regex: '.*',
        isRequired: false,
        label: 'Postcode',
        placeholder: 'Enter your postcode',
        helperText: "Enter the postcode for your address in your country's format",
        errorText: 'Invalid postcode',
        flex: 1,
      },
      {
        name: 'settlement',
        regex: '.*',
        isRequired: true,
        label: 'Town or City',
        placeholder: 'Town or City',
        helperText: 'Enter your town or city',
        errorText: 'Invalid town or city',
        flex: 2,
      },
      {
        name: 'province',
        regex: '.*',
        isRequired: false,
        label: 'Province',
        placeholder: 'Enter Province',
        errorText: 'Invalid Province',
        helperText: 'Enter your province or county',
        flex: 2,
      },
    ],
  ],
};