Skip to content

Commit

Permalink
Add es-middleware dependency, readme fixes, new dependecy versions
Browse files Browse the repository at this point in the history
  • Loading branch information
Zlobin committed May 16, 2016
1 parent 02f9de2 commit 844f869
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 99 deletions.
116 changes: 83 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

# Ajax requests in JavaScript
# Ajax requests in JavaScript [![Build Status](https://travis-ci.org/Zlobin/es-ajax.png?branch=master)](https://travis-ci.org/Zlobin/es-ajax)

## Synopsis

Expand All @@ -11,18 +11,27 @@ The library is affording have full control for each external requests. Through A

## Dependencies

Dependencies: [object-hash](https://www.npmjs.com/package/object-hash), [qs](https://www.npmjs.com/package/qs)
Dependencies: [object-hash](https://www.npmjs.com/package/object-hash), [qs](https://www.npmjs.com/package/qs), [es-middleware](https://www.npmjs.com/package/es-middleware)

## Installation

`npm i --save es-ajax`
or
`git clone https://github.com/Zlobin/es-ajax.git`
`cd es-ajax && npm i && webpack`

## Examples

```javascript
var ajax = require('es-ajax');
```
Or
Or after running `npm i && webpack` inside library path:
```html
<script src="<PATH/TO/LIBRARY>/dist/bundle.js">
```
You can test some stuff inside /demo/ path.
```js
// GET
ajax('/some/url')
Expand Down Expand Up @@ -52,30 +61,21 @@ ajax('/some/url')
})
.then(function(response) {
// response.headers
// response.status
// response.statusText
// response.type
// response.url
// response.response
if (response.status !== 200) {
console.log('Something wrong status:' + response.status);
} else {
response
.json()
.then(function(data) {
console.log(data);
});
}
// ... some stuff
})
.catch(function(err) {
console.log(err);
});
```
You can change content-type of request, available types: 'json', 'text', 'html'
```js
ajax('/some/url', {
type: 'json'
})
type: 'json'
})
.get()
.then(function() {
// ...
Expand All @@ -85,14 +85,31 @@ ajax('/some/url', {
});
```
Middleware is calling before a request was sent. It can cancel request, change URL, headers before sending.
May be used, for instance, when you want to to some cache library. An example:
Or you can add type manually, via headers:
```js
var cache = function(headers, request, time) {
ajax('/some/url', {
headers: {
'Content-type': 'my-type'
}
})
.get()
.then(function() {
// ...
})
.catch(function() {
// ...
});
```
:TODO
Middleware is the programming pattern of providing hooks with a resume callback. It will be calling before a request was sent. It is able to cancel request, change URL and headers before sending. May be used, for instance, when you want to use some cache library, allow only some http-methods, like GET and POST, for instance. Some examples:
```js
var cache = function(next) {
var response = null;
// For instance, we don't do cache for URL what contains "noCache" parameter.
if (request.url.indexOf('noCache') > 0) {
if (this.request.url.indexOf('noCache') > 0) {
// Check if we already have cached resulst from some MyCache library.
response = MyCache.get({
url: request.url,
Expand All @@ -103,16 +120,18 @@ var cache = function(headers, request, time) {
console.log('Data from cache.');
// Do not send request to the server.
// Return cached response.
// @todo
} else {
console.log('Send request to the server.');
// Send request.
// Add response to the cache.
next();
}
} else {
next();
}
};
ajax()
.applyMiddleware([cache]);
.use([cache]);
// First request will be send to the server.
ajax('/foo/bar')
Expand All @@ -122,7 +141,43 @@ ajax('/foo/bar')
ajax('/foo/bar')
.get();
})
.catch();
.catch(function() {
// ...
});
```
Or if you want to allow to use only GET requests:
```js
var onlyGet = function(request, next) {
if (request.method === 'GET') {
next();
}
throw new Error('Allows only GET methods');
// ...
};
ajax()
.use([onlyGet]);
ajax('/foo/bar')
.get()
.then(function() {
// ... succeed
})
.catch(function() {
// ...
});
ajax('/foo/bar')
.get()
.then(function() {
// ...
})
.catch(function() {
// ... failed
});
```
## API
Expand All @@ -133,7 +188,7 @@ ajax('/foo/bar')
- **<code>getXhrMeta</code> Get meta info for the current request**
- **<code>getAllRequests</code> Get info about each sent request**
- **<code>setTimeout</code> Set timeout when reqeust should be canceled automatically**
- **<code>applyMiddleware</code> no description**
- **<code>use</code> add middleware functions**
##### Non-static, should be used with a XHR (fetch) instance.
- **<code>setOverride</code> Set override for DELETE, PUT requests**
Expand All @@ -151,10 +206,6 @@ ajax('/foo/bar')
Tests are performed using "mocha", "sinon", "expect" libraries, PhantomJS as a browser and "karma" as a server. Run `npm test`.
## Building the documentation
You can use JSDoc comments found within the source code.
## Minifying
You can grab minified versions of es-ajax from /dist path after running `webpack`.
Expand All @@ -164,5 +215,4 @@ You can grab minified versions of es-ajax from /dist path after running `webpack
1. Middleware
2. Send more than one file
3. Add more tests
4. Finish demo
5. Singleton request
4. Singleton request
25 changes: 13 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "es-ajax",
"description": "Ajax (fetch or xhr2) with promises - an useful JavaScript library for convenient work with ajax requests in a browser.",
"version": "1.0.0",
"version": "1.1.0",
"main": "src/index.js",
"author": {
"name": "Eugene Zlobin",
Expand Down Expand Up @@ -32,28 +32,29 @@
],
"license": "MIT",
"dependencies": {
"es-middleware": "^1.0.1",
"object-hash": "^1.1.2",
"qs": "^6.1.0"
},
"devDependencies": {
"babel-cli": "^6.7.7",
"babel-core": "^6.7.7",
"babel-cli": "^6.8.0",
"babel-core": "^6.8.0",
"babel-loader": "^6.2.4",
"babel-plugin-transform-export-extensions": "^6.5.0",
"babel-plugin-transform-object-rest-spread": "^6.6.5",
"babel-plugin-transform-export-extensions": "^6.8.0",
"babel-plugin-transform-object-rest-spread": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-stage-2": "^6.5.0",
"eslint": "^2.8.0",
"eslint-config-airbnb": "^8.0.0",
"eslint": "^2.10.1",
"eslint-config-airbnb": "^9.0.1",
"eslint-loader": "^1.3.0",
"eslint-plugin-import": "^1.6.0",
"eslint-plugin-jsx-a11y": "^1.0.3",
"eslint-plugin-react": "^5.0.1",
"expect": "^1.18.0",
"eslint-plugin-import": "^1.8.0",
"eslint-plugin-jsx-a11y": "^1.2.0",
"eslint-plugin-react": "^5.1.1",
"expect": "^1.20.1",
"karma": "^0.13.22",
"karma-mocha": "^0.2.2",
"karma-phantomjs-launcher": "^1.0.0",
"karma-sinon": "^1.0.4",
"karma-sinon": "^1.0.5",
"karma-webpack": "^1.7.0",
"mocha": "^2.4.5",
"phantomjs-prebuilt": "^2.1.7",
Expand Down
14 changes: 6 additions & 8 deletions src/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import factory from './utils/factory';
import { contentTypes } from './utils/content-types';
import objectHash from 'object-hash';
import { is } from './utils/is';
import Middleware from 'es-middleware';

const _requests = new Set();
const _meta = new Map();
const mw = new Middleware();
let _timeout = 0;
let _middleware = [];

export function ajax(url, parameters = {}) {
const defaults = {
Expand Down Expand Up @@ -41,6 +42,7 @@ export function ajax(url, parameters = {}) {
if (!xhrApi && url) {
// Create new instance.
xhrApi = factory(settings.api, url, settings.request, settings.headers);
xhrApi.setMiddlewareRun(mw.run);
xhrApi.onBeforeSend(params => {
const { headers, request, time } = params;
const hash = objectHash({
Expand All @@ -63,10 +65,6 @@ export function ajax(url, parameters = {}) {

xhrApi.setTimeout(_timeout);
});

if (_middleware.length) {
xhrApi.applyMiddleware(_middleware);
}
}

function proxy(name) {
Expand Down Expand Up @@ -145,8 +143,8 @@ export function ajax(url, parameters = {}) {
return this;
}

function applyMiddleware(functions) {
_middleware = functions;
function use(functions) {
mw.use(functions);

return this;
}
Expand All @@ -158,7 +156,7 @@ export function ajax(url, parameters = {}) {
getXhrMeta,
getAllRequests,
setTimeout,
applyMiddleware,
use,
// Non-static, should be used with a XHR (fetch) instance.
setOverride: proxy('setOverride'),
options: proxy('options'),
Expand Down
12 changes: 8 additions & 4 deletions src/api/xhr-abstract.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,6 @@ export default class XhrAbstract {
this.setHeaders(methodsOverride(methodName));
}

applyMiddleware() {
// ...
}

head() {
this.setRequest({
method: methods.head,
Expand Down Expand Up @@ -114,6 +110,14 @@ export default class XhrAbstract {
return this.send();
}

setMiddlewareRun(middleware) {
if (!is._function(middleware)) {
throw new TypeError('Parameter must be a function.');
}

this.run = middleware;
}

send() {
//
}
Expand Down
Loading

0 comments on commit 844f869

Please sign in to comment.