ampersand-sync
Advanced tools
Comparing version 3.0.7 to 4.0.0
@@ -1,130 +0,2 @@ | ||
/*$AMPERSAND_VERSION*/ | ||
var result = require('lodash.result'); | ||
var defaults = require('lodash.defaults'); | ||
var includes = require('lodash.includes'); | ||
var assign = require('lodash.assign'); | ||
var xhr = require('xhr'); | ||
var qs = require('qs'); | ||
// Throw an error when a URL is needed, and none is supplied. | ||
var urlError = function () { | ||
throw new Error('A "url" property or function must be specified'); | ||
}; | ||
// Map from CRUD to HTTP for our default `Backbone.sync` implementation. | ||
var methodMap = { | ||
'create': 'POST', | ||
'update': 'PUT', | ||
'patch': 'PATCH', | ||
'delete': 'DELETE', | ||
'read': 'GET' | ||
}; | ||
module.exports = function (method, model, options) { | ||
var type = methodMap[method]; | ||
var headers = {}; | ||
// Default options, unless specified. | ||
defaults(options || (options = {}), { | ||
emulateHTTP: false, | ||
emulateJSON: false, | ||
// overrideable primarily to enable testing | ||
xhrImplementation: xhr | ||
}); | ||
// Default request options. | ||
var params = {type: type}; | ||
// Ensure that we have a URL. | ||
if (!options.url) { | ||
options.url = result(model, 'url') || urlError(); | ||
} | ||
// Ensure that we have the appropriate request data. | ||
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { | ||
params.json = options.attrs || model.toJSON(options); | ||
} | ||
// If passed a data param, we add it to the URL or body depending on request type | ||
if (options.data && type === 'GET') { | ||
// make sure we've got a '?' | ||
options.url += includes(options.url, '?') ? '&' : '?'; | ||
options.url += qs.stringify(options.data); | ||
} | ||
// For older servers, emulate JSON by encoding the request into an HTML-form. | ||
if (options.emulateJSON) { | ||
headers['Content-Type'] = 'application/x-www-form-urlencoded'; | ||
params.body = params.json ? {model: params.json} : {}; | ||
delete params.json; | ||
} | ||
// For older servers, emulate HTTP by mimicking the HTTP method with `_method` | ||
// And an `X-HTTP-Method-Override` header. | ||
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { | ||
params.type = 'POST'; | ||
if (options.emulateJSON) params.body._method = type; | ||
headers['X-HTTP-Method-Override'] = type; | ||
} | ||
// When emulating JSON, we turn the body into a querystring. | ||
// We do this later to let the emulateHTTP run its course. | ||
if (options.emulateJSON) { | ||
params.body = qs.stringify(params.body); | ||
} | ||
// Start setting ajaxConfig options (headers, xhrFields). | ||
var ajaxConfig = (result(model, 'ajaxConfig') || {}); | ||
// Combine generated headers with user's headers. | ||
if (ajaxConfig.headers) { | ||
assign(headers, ajaxConfig.headers); | ||
} | ||
params.headers = headers; | ||
//Set XDR for cross domain in IE8/9 | ||
if (ajaxConfig.useXDR) { | ||
params.useXDR = true; | ||
} | ||
// Set raw xhr options. | ||
if (ajaxConfig.xhrFields) { | ||
var beforeSend = ajaxConfig.beforeSend; | ||
params.beforeSend = function (req) { | ||
for (var key in ajaxConfig.xhrFields) { | ||
req[key] = ajaxConfig.xhrFields[key]; | ||
} | ||
if (beforeSend) return beforeSend.apply(this, arguments); | ||
}; | ||
params.xhrFields = ajaxConfig.xhrFields; | ||
} else { | ||
params.beforeSend = ajaxConfig.beforeSend; | ||
} | ||
// Turn a jQuery.ajax formatted request into xhr compatible | ||
params.method = params.type; | ||
var ajaxSettings = assign(params, options); | ||
// Make the request. The callback executes functions that are compatible | ||
// With jQuery.ajax's syntax. | ||
var request = options.xhr = options.xhrImplementation(ajaxSettings, function (err, resp, body) { | ||
if (err) { | ||
if (options.error) return options.error(resp, 'error', err.message); | ||
} else { | ||
// Parse body as JSON if a string. | ||
if (body && typeof body === 'string') { | ||
try { | ||
body = JSON.parse(body); | ||
} catch (err) { | ||
if (options.error) return options.error(resp, 'error', err.message); | ||
} | ||
} | ||
if (options.success) return options.success(body, 'success', resp); | ||
} | ||
}); | ||
model.trigger('request', model, request, options, ajaxSettings); | ||
request.ajaxSettings = ajaxSettings; | ||
return request; | ||
}; | ||
var xhr = require('request'); | ||
module.exports = require('./core')(xhr); |
{ | ||
"name": "ampersand-sync", | ||
"description": "Provides sync behavior for updating data from ampersand models and collections to the server.", | ||
"version": "3.0.7", | ||
"version": "4.0.0", | ||
"author": "Henrik Joreteg <henrik@andyet.net>", | ||
"files": [ | ||
"ampersand-sync.js" | ||
"ampersand-sync*", | ||
"core.js" | ||
], | ||
@@ -23,16 +24,15 @@ "browserify": { | ||
"lodash.result": "^3.0.0", | ||
"qs": "^2.2.4", | ||
"xhr": "^1.10.0" | ||
"qs": "^4.0.0", | ||
"request": "^2.55.0", | ||
"xhr": "^2.0.3" | ||
}, | ||
"devDependencies": { | ||
"ampersand-model": "^4.0.1", | ||
"ampersand-rest-collection": "^2.0.1", | ||
"browserify": "^6.2.0", | ||
"ampersand-model": "^5.0.3", | ||
"ampersand-rest-collection": "^4.0.0", | ||
"concat-stream": "^1.4.8", | ||
"jshint": "^2.5.3", | ||
"phantomjs": "^1.9.12", | ||
"precommit-hook": "^1.0.7", | ||
"run-browser": "~1.3.0", | ||
"tap-spec": "^1.0.1", | ||
"tape": "^2.14.0", | ||
"tape-run": "^0.3.0" | ||
"run-browser": "^2.0.2", | ||
"tap-spec": "^4.0.2", | ||
"tape": "^4.0.0" | ||
}, | ||
@@ -48,2 +48,3 @@ "homepage": "https://github.com/ampersandjs/ampersand-sync", | ||
"main": "ampersand-sync.js", | ||
"browser": "ampersand-sync-browser.js", | ||
"repository": { | ||
@@ -54,4 +55,4 @@ "type": "git", | ||
"scripts": { | ||
"start": "run-browser test/*", | ||
"test": "browserify test/* | tape-run | tap-spec" | ||
"start": "run-browser test/index.js", | ||
"test": "run-browser test/index.js -b | tap-spec && node test/index.js" | ||
}, | ||
@@ -58,0 +59,0 @@ "testling": { |
@@ -5,24 +5,16 @@ # ampersand-sync | ||
<!-- starthide --> | ||
Part of the [Ampersand.js toolkit](http://ampersandjs.com) for building clientside applications. | ||
<!-- endhide --> | ||
You probably won't use this directly, but it is used by ampersand-model and ampersand-rest-collection to provide the REST functionality. | ||
## Important note on the 1.0.x versions | ||
As of v4.0 works in browsers and Node.js | ||
In moving from 1.0.1 to 1.0.2 we switched the underlying ajax implementation from jQuery's ajax to [xhr](http://github.com/raynos/xhr). This changed slightly the options, as well as how `ajaxConfig` in models/collections operated when configured as a function. | ||
Previously `ajaxConfig` would be passed the current ajax parameters object for modification, now it receives no arguments and should just return options to be merged in to the ajax parameters which will be passed to xhr. | ||
This should have been a major release both for this module and its dependents (ampersand-model, ampersand-rest-collection, ampersand-collection-rest-mixin), but unfortunately we made a mistake and published as 1.0.2, and were too slow to rollback our mistake before workarounds were in place. | ||
As such we are leaving the current 1.0.x versions in place, but deprecated, and suggest people upgrade to the latest versions of model/collection when they can which will contain the new implementation of xhr. | ||
This should only affect your if you're using `ajaxConfig` as a function. If so you'll need to return the options you want to add, rather than expecting to be passed a params object to your ajaxConfig function. If you're having trouble ping us in freenode #&yet or on twitter: [@philip_roberts](http://twitter.com/philip_roberts) & [@henrikjoreteg](http://twitter.com/henrikjoreteg). | ||
## browser support | ||
[![testling badge](https://ci.testling.com/AmpersandJS/ampersand-sync.png)](https://ci.testling.com/AmpersandJS/ampersand-sync) | ||
IE9+ and any other browser. | ||
<!-- starthide --> | ||
Part of the [Ampersand.js toolkit](http://ampersandjs.com) for building clientside applications. | ||
<!-- endhide --> | ||
Might work in IE8, but it's not officially supported. | ||
@@ -35,2 +27,50 @@ ## install | ||
## usage | ||
```js | ||
var sync = require("ampersand-sync") | ||
var rawRequest = sync(method, model, options) | ||
``` | ||
**method** is a string used for choosing HTTP verb of the sync request. It has to be chosen from the keys of the following map: | ||
```js | ||
{ | ||
'create': 'POST', | ||
'update': 'PUT', | ||
'patch': 'PATCH', | ||
'delete': 'DELETE', | ||
'read': 'GET' | ||
} | ||
``` | ||
**model** (optional) is an ampersand-model object or equivalent. `ajaxConfig` and `url` fields of the model are used (if present) to override default options for the request. (for details on ajaxConfig see below) | ||
If model is provided, `model.toJSON` is called and the result is used as body for create, update and patch methods. | ||
When the request is made, `request` event is triggered on the model with arguments: `(model, XMLHttpRequest, options, ajaxSettings)` where ajaxSettings is the final configuration passed to http request implementation. In Node.js, object returned from `request()` will be passed in instead of `XMLHttpRequest`, so streaming is possible. | ||
If model is null, some options are required to form a correct http request. Please apply common sense. | ||
**options** (optional) are used to override any settings for the http request and provide callbacks for the results or errors. | ||
**rawRequest** is returned. In the browser, it is an XMLHttpRequest object instance, in Node.js it's the object returned by `request()`. | ||
### ajaxConfig and options | ||
both `ajaxConfig` and `options` can contain any and all of the options that [xhr](https://github.com/Raynos/xhr) or [request](https://github.com/request/request) accepts. | ||
Additional fields in `ajaxConfig`: | ||
- `xhrFields` key that contains all fields which should be added to the raw XMLHttpObject before it's sent. `xhrFields` is only used in the browser and has no effect in node. | ||
Additional fields in `options`: | ||
- emulateHTTP - defaults to `false` | ||
- emulateJSON - defaults to `false` | ||
- xhrImplementation - can be used to override http request implementation for just this one call | ||
- data - JSON serializable object to be sent as request body | ||
- `success(body, 'success', responseObject)` - optional callback to be called when request finishes successfully | ||
- `error(responseObject, 'error', error.message)` - optional callback to be called when an error occurs (http request/response error or parsing response error) | ||
- `always(error, responseObject, body)` - optional callback to be called when request finishes no matter what the result | ||
## running the tests | ||
@@ -48,2 +88,27 @@ | ||
## Changes | ||
### Notes on 4.0.0 | ||
Version 4 supports making requests in Node.js as well as browser. [xhr](https://github.com/Raynos/xhr) is used in the browser and [request](https://github.com/request/request) in node, but you can substitute the request making code with your on implementation as well. | ||
```js | ||
var sync = require("ampersand-sync/core")(whateverXhrYouWant) | ||
``` | ||
For details on 4.0 release see [v4.0 milestone](https://github.com/AmpersandJS/ampersand-sync/issues?utf8=%E2%9C%93&q=milestone%3Av4.0) | ||
### Important note on the 1.0.x versions | ||
In moving from 1.0.1 to 1.0.2 we switched the underlying ajax implementation from jQuery's ajax to [xhr](http://github.com/raynos/xhr). This changed slightly the options, as well as how `ajaxConfig` in models/collections operated when configured as a function. | ||
Previously `ajaxConfig` would be passed the current ajax parameters object for modification, now it receives no arguments and should just return options to be merged in to the ajax parameters which will be passed to xhr. | ||
This should have been a major release both for this module and its dependents (ampersand-model, ampersand-rest-collection, ampersand-collection-rest-mixin), but unfortunately we made a mistake and published as 1.0.2, and were too slow to rollback our mistake before workarounds were in place. | ||
As such we are leaving the current 1.0.x versions in place, but deprecated, and suggest people upgrade to the latest versions of model/collection when they can which will contain the new implementation of xhr. | ||
This should only affect your if you're using `ajaxConfig` as a function. If so you'll need to return the options you want to add, rather than expecting to be passed a params object to your ajaxConfig function. If you're having trouble ping us in freenode #&yet or on twitter: [@philip_roberts](http://twitter.com/philip_roberts) & [@henrikjoreteg](http://twitter.com/henrikjoreteg). | ||
## credits | ||
@@ -50,0 +115,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
14156
8
6
131
123
8
2
+ Addedrequest@^2.55.0
+ Addedajv@6.12.6(transitive)
+ Addedasn1@0.2.6(transitive)
+ Addedassert-plus@1.0.0(transitive)
+ Addedasynckit@0.4.0(transitive)
+ Addedaws-sign2@0.7.0(transitive)
+ Addedaws4@1.13.2(transitive)
+ Addedbcrypt-pbkdf@1.0.2(transitive)
+ Addedcaseless@0.12.0(transitive)
+ Addedcombined-stream@1.0.8(transitive)
+ Addedcore-util-is@1.0.2(transitive)
+ Addeddashdash@1.14.1(transitive)
+ Addeddelayed-stream@1.0.0(transitive)
+ Addedecc-jsbn@0.1.2(transitive)
+ Addedextend@3.0.2(transitive)
+ Addedextsprintf@1.3.0(transitive)
+ Addedfast-deep-equal@3.1.3(transitive)
+ Addedfast-json-stable-stringify@2.1.0(transitive)
+ Addedforever-agent@0.6.1(transitive)
+ Addedform-data@2.3.3(transitive)
+ Addedgetpass@0.1.7(transitive)
+ Addedglobal@4.4.0(transitive)
+ Addedhar-schema@2.0.0(transitive)
+ Addedhar-validator@5.1.5(transitive)
+ Addedhttp-signature@1.2.0(transitive)
+ Addedis-function@1.0.2(transitive)
+ Addedis-typedarray@1.0.0(transitive)
+ Addedisstream@0.1.2(transitive)
+ Addedjsbn@0.1.1(transitive)
+ Addedjson-schema@0.4.0(transitive)
+ Addedjson-schema-traverse@0.4.1(transitive)
+ Addedjson-stringify-safe@5.0.1(transitive)
+ Addedjsprim@1.4.2(transitive)
+ Addedmime-db@1.52.0(transitive)
+ Addedmime-types@2.1.35(transitive)
+ Addedoauth-sign@0.9.0(transitive)
+ Addedperformance-now@2.1.0(transitive)
+ Addedprocess@0.11.10(transitive)
+ Addedpsl@1.10.0(transitive)
+ Addedpunycode@2.3.1(transitive)
+ Addedqs@4.0.06.5.3(transitive)
+ Addedrequest@2.88.2(transitive)
+ Addedsafe-buffer@5.2.1(transitive)
+ Addedsafer-buffer@2.1.2(transitive)
+ Addedsshpk@1.18.0(transitive)
+ Addedtough-cookie@2.5.0(transitive)
+ Addedtunnel-agent@0.6.0(transitive)
+ Addedtweetnacl@0.14.5(transitive)
+ Addeduri-js@4.4.1(transitive)
+ Addeduuid@3.4.0(transitive)
+ Addedverror@1.10.0(transitive)
+ Addedxhr@2.6.0(transitive)
- Removedglobal@4.3.2(transitive)
- Removedonce@1.1.1(transitive)
- Removedprocess@0.5.2(transitive)
- Removedqs@2.4.2(transitive)
- Removedxhr@1.17.1(transitive)
Updatedqs@^4.0.0
Updatedxhr@^2.0.3