1.1.1 • Published 1 year ago

@justeat/f-http v1.1.1

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 year ago

f-http

Javascript HTTP client for interacting with restful services


npm version CircleCI Coverage Status Known Vulnerabilities

This package exposes methods for interacting with restful services, it may abstract any number of popular NPM packages which provide the ability to perform GET, PUT, POST, PATH, DELETE requests; while also adding some additional benefits.

Benefits (Now)

  • Easy configuration of reusable clients which can be retrieved from context
  • Enables us to switch to alternative HTTP packages when desired
  • Sensible defaults, with the ability to override everything
  • Ability to set authorisation tokens for all requests for specific clients
  • Ability to automatically collect stats showing how long real API calls take

Benefits (Soon)

  • Opt-in ability to use dynamic timeouts

Usage

Installation

Install the module using npm or Yarn

yarn add @justeat/f-http

Initialisation

Ideally the package should be initialised by your website and the httpClient placed in context or a prototype, rather than initialising it in each individual component or every time you make a request.

Initialise an httpClient

import httpModule from '@justeat/f-http';

const options = { // Options are described later
    baseUrl: 'https://jsonplaceholder.typicode.com'
};

// Optional: Implement wrapper using cookie tech you have available
// Enables conversation ID to be automatically provided with requests
const getCookieFunction = cookieName => app.$cookies.get(cookieName);

const httpClient = new httpModule.CreateClient(options, getCookieFunction);

// WHEN: Using a Nuxt Plugin
inject('http', httpClient);

// WHEN: Using Vue CLI
Vue.prototype.$http = httpClient;

Basic Usage

Recommended: Using the prototype (Vue) or context (Nuxt). You can access $http in components, or anywhere the context is available including vuex modules.

export default {
  data () {
    return {
      apiResult: null
    }
  },
  async mounted () {
    this.apiResult = await this.$http.get('/todos/1');
  }
}

Alternative Implementation

If you would rather create the HTTPClient when you use it, that's fine too; it just means it can't be reused as easily and you will need to filter the configuration options down to the component.

export default {
  async mounted () {
    const configuration = { // Options are described later
        baseUrl: 'https://jsonplaceholder.typicode.com'
    };

    const httpClient = new httpModule.CreateClient(configuration);

    const result = await httpClient.get('/todos/1');
  }
}

Setting Authorisation Token

You can globally set the authorisation token so that all requests provide it

// Some event happened that means we now have a token
export default {
  mounted () {
    this.$http.setAuthorisationToken('my token');
  }
}

Unit Testing Guidance

Because $http exists in context, it should be really easy to mock it in any way you want. Check out the example below

const wrapper = mount(MyComponent, {
  mocks: {
    $http: {
      get: jest.fn()
    }
  }
});

Integration / System Testing Guidance

The module exposes a way to create a MockClient, so you can mock the underlying API with pre-configured responses.

import { httpVerbs, MockFactory, CreateClient } from '@justeat/f-http';

const mockFactory = new MockFactory();
const httpClient = new CreateClient();

const wrapper = mount(MyComponent, {
  mocks: {
    $http: httpClient
  }
});

// Reset all previously configured responses
mockFactory.reset();

// Setup a fake response
mockFactory.setupMockResponse(httpVerbs.POST, '/URL', REQUEST_DATA, 201);

Parameters

None of these parameters are required, but using them enables you to customise your http client

OptionDescriptionTypeDefault
optionsAn object containing options you wish to override (see below)object{}
getCookieFunctionWrapper function providing ability to read cookiesfunctionnull
statisticsClientInstance of f-statistics to capture dependency timingsobjectnull

Options

All options are optional, you don't need to specify any overrides if you are happy with the default values

OptionDescriptionTypeDefault
baseUrlEnsure all requests from this client use a relative urlstring''
timeoutHow long each request takes to timeoutnumber10000
errorCallbackA function you can use to globally handle errors (accepts error object)functionnull
contentTypeSpecify a value for the content type headerstring'application/json'

Client Methods

These are all of the methods exposed by the httpClient

MethodDescriptionParameters
getGET a resourceresource URL string, headers array
postPOST a resourceresource URL string, body object, headers array
putPUT a resourceresource URL string, body object, headers array
patchPATCH a resourceresource URL string, body object, headers array
deleteDELETE a resourceresource URL string, headers array
setAuthorisationTokenSet the authorisation token for all requestsauthorisationToken string
readConfigurationReturns the provided optionsNone
1.1.1

1 year ago

1.1.0

1 year ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.10.0

3 years ago

0.9.1

3 years ago

0.9.0

4 years ago

0.8.0

4 years ago

0.7.0

4 years ago

0.6.1

4 years ago

0.6.0

4 years ago

0.5.0

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.2.0

4 years ago