flyd-ajax
A simple ajax library (using XMLHttpRequest) that returns flyd streams.
- Small size
- FRP with flyd
- Supports mock requests for unit tests
- Supports error/progress/abort
Many of the options, terminology, and response objects are directly from the normal XMLHttpRequest API. See the MDN Articles on that topic for details around how to work with response and progress objects.
Example GET request
// Calling request(...) immediately makes the requestconst response = // The response object has four keys: .load, .error, .progress, and .abort// Each of these keys holds a stream of request objects for the corresponding event// Most of the time you will just use .load stream const resp$ = requestload // flyd stream of request objects when the response is loadedflyd
Example POST request
// If you leave out url, it will post to the path on the current domain // If you pass in Object into the .send property, it will convert it to a JSON string by default
Returned streams
The request function immediately returns an object with a set of streams:
// object that gets returned by the request function: load // stream of a request object when the request is completed error // stream of event object when the request cannot be completed due to some error progress // stream of event object on progress events in the request abort // stream of event object on aborted request event
Most of the time you will only need the .load
stream -- error and progress are useful for file transfers.
Each of the above streams will emit the exact corresponding event or request objects as described here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The .load
stream will have a .body
property, which will contain a parsed JS object of JSON data, if the response's had 'json' in its content type. Otherwise it will be a String.
You can map over any of these streams to work with the responses and events. Example usage:
let getPosts = flydflydflyd
Configuration
One easy way to pre-configure ajax requests is to simply define your own module that wraps the request function.
const apiRequest = load // Stream of post responses, could be failure or successconst response$ = // Stream of user dataconst createdUser$ = Rresponse$ // Stream of error messages from creating a userconst errorMessage$ = Rresponse$
Development
Test
Tests use zuul and assert
npm run test
Build
Develop the .es6
files and transpile them to .js
with:
npm run build
Mocking requests for tests
flyd-ajax comes with a built-in utility for mocking ajax requests for frontend unit testing. The require path is flyd-ajax/mock
Example:
Mock API:
setup()
-- Overwritewindow.XMLHttpRequest
teardown()
-- Restorewindow.XMLHttpRequest
handle(method, url, responseObject)
-- Catch and handle requests to this endpoint
The responseObject
can have these properties:
body
-- mock response bodyheaders
-- mock response headersstatus
-- mock response status code