Code Monkey home page Code Monkey logo

js-data-http's Introduction

js-data logo

js-data-http

Slack Status npm version npm downloads Circle CI Coverage Status

This repo contains HTTP adapters for js-data:

  • js-data-http - HTTP (XHR, includes [axios][axios]) adapter for JSData in the browser. Capable of using window.fetch instead of axios. Only works in the browser.
  • js-data-fetch - Same as js-data-http but does not include axios and will use window.fetch if available and if you don't provide your own http library.
  • js-data-http-node - Same as js-data-http but runs on Node.js. Depends on axios and will use axios unless you provide a different http library.

Tested on IE9, Chrome 46, Firefox 41 & Safari 7.1 using bs logo

To get started, visit the main website at http://js-data.io.

Links

License

The MIT License (MIT)

Copyright (c) 2014-2016 js-data-http project authors

js-data-http's People

Contributors

crobinson42 avatar internalfx avatar ivanvoznyakovsky avatar jmdobry avatar joshdrake avatar nlac avatar pik avatar robertherhold avatar scotttrenda avatar tfoxy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-data-http's Issues

Map file path in js-data-http.min.js is incorrect.

The map file should be relative to the min.js file. The path in js-data-http.min.js is "dist/js-data-http.min.map". This should be changed to "js-data-http.min.map".

-- //# sourceMappingURL=dist/js-data-http.min.map
++ //# sourceMappingURL=js-data-http.min.map

I believe the change can be made in the package.json file on line 26 (the min line).

Not testing for false with HttpAdapter option(s) "log"

https://js-data.slack.com/archives/js-data-http/p1466314357000009

this.adapter = new HttpAdapter({"log": false, "error": false}); - setting log to false in the config for js-data 3 causes this error..

"this.log.apply is not a function"

doesn't check for log being false first.

Problem is in utils mixin in js-data .. need to test for false this.log (or typeof === 'function') here:

https://github.com/js-data/js-data/blob/3.0.0-beta.7/src/utils.js#L1033

Rewrite DSHttpAdapter page on js-data.io

Need to remove api reference docs because that will be auto-generated by the jsdoc comments in the source code. The new js-data-http should be just guide, usage, & examples documentation.

  • - Document custom deserialization
  • - Document using window.fetch
  • - Document using the adapter's lifecycle hooks

Cannot read property 'http' of undefined

When I use it like

var DSHttpAdapter = require("js-data-http")
var adapter = new DSHttpAdapter()

I got

node_modules/js-data-http/dist/js-data-http.js:140
        this.http = options.http || axios;

Log failures

I really appreciate that js-data-http logs successful requests. Would appreciate it if it logged failures as well. I'm normally more interested to see the logs for failures anyway. What do you think?

params

(delete this line) GitHub Issues are NOT for support questions.
(delete this line) GitHub Issues ARE for bug reports, feature requests, and other issues.
(delete this line) Find out how to Get Support here: http://js-data.io/docs/support.

<your detailed, discussable, actionable, and helpful text goes here>

Thanks!

Handle multiple relations in getEndpoint

versions:

"js-data": "2.8.2",
"js-data-angular": "3.1.0",

Hi there! I have a model that looks like this:

{
  name: 'TelephoneNumber',
  endpoint: 'telephonenumber',
  relations: {
    belongsTo: {
      Account: {
        parent: true,
        localKey: 'accountId',
      },
      Partition: {
        parent: true,
        localKey: 'partitionId',
      }
    }
  },
}

As you can see a TelephoneNumber belongs to both an Account and Partition (incidentally, an Account belongs to a Partition). Odd, I know. When I call getEndpoint like so:

const item = {accountId: 'foo', partitionId: 'bar', ...otherStuff}
const url = httpAdapter.getEndpoint(TelephoneNumberDefinition, item)

Here this returns: partition/bar/telephonenumber

The issue is that right now the defineResource method doesn't support having a definition with multiple parent, parentKey, and parentId properties (here. So when that runs the account is set as the parent, and then the partition overrides it (though this is not 100% deterministic because iteration on objects is not 100% consistent across browsers).

What I would expect is if I provide an accountId it should factor the account in generating the URL, so it would become: partition/bar/account/foo/telephonenumber

Problem I can see from this is with me providing both an accountId and a partitionId, you don't know which one to use... So, I think maybe the solution could be that I don't provide a partitionId and you look that up on the account which would happen naturally...

To sum up, what I think needs to happen is this code needs to account for multiple parents. Then all code using that needs to account for a potential of an array of parents (in particular, the getEndpoint method). That would resolve my issue...

I expect that this would be a breaking change for people depending on and using the parent with multiple belongsTo.

Angular/HTTP: Allow computed properties without using data attributes from the service

I would like to be able to add a computed property to the object without having to use one of the properties from the response object. An example of this is below.

computed: {
    type: [null, function(){ //use null? Maybe there's a better way?
        return "gift";
    }],
}

This way all items of this response get a static property assigned to them, in this case "gift".

In order to make this work I have to use any property except the ID in the function definition and just ignore the variable.

computed: {
    type: ['someProperty', function(someProperty){
        return "gift";
    }],
}

js-data-http does not work with React Native in a mobile environment

Your framework currently runs in a browser and Node. We are experimenting with mobile apps with something like React Native which is closer to a browser but does not have all the polyfills. I had to comment out a few cookie/document/navigator references in you 'js-data-http' adapter to make it work. Please consider this 3rd environment - the delta in terms of code changes is not big but you can fulfill the needs of a big emerging category of apps.

ReferenceError: navigator is not defined

I am using js-data to communicate between 2 nodejs applications.

js-data-http 1.2.3 does not work anymore with nodejs, while v1.1.0 does.

The error is: "ReferenceError: navigator is not defined"

I can't figure who throws the error. Maybe axios?

The error was hidden by an other issue in js-data-http:

 function logResponse(data) {
    var str = start.toUTCString() + ' - ' + data.config.method.toUpperCase() + ' ' + data.config.url + ' - ' + data.status + ' ' + (new Date().getTime() - start.getTime()) + 'm

In case of error from the server (e.g. wrong url), data.config is not defined.

Cannot read property 'method' of undefined

Environment: Node.js
Version: 2.0.0

Stack:

[TypeError: Cannot read property 'method' of undefined]
TypeError: Cannot read property 'method' of undefined
    at logResponse (/js-data-http/src/index.js:136:56)
    at lib$es6$promise$$internal$$tryCatch (/js-data-http/node_modules/es6-promise/dist/es6-promise.js:331:16)
    at lib$es6$promise$$internal$$invokeCallback (/js-data-http/node_modules/es6-promise/dist/es6-promise.js:343:17)
    at lib$es6$promise$$internal$$publish (/js-data-http/node_modules/es6-promise/dist/es6-promise.js:314:11)
    at lib$es6$promise$$internal$$publishRejection (/js-data-http/node_modules/es6-promise/dist/es6-promise.js:264:7)
    at lib$es6$promise$asap$$flush (/js-data-http/node_modules/es6-promise/dist/es6-promise.js:125:9)
    at doNTCallback0 (node.js:407:9)
    at process._tickCallback (node.js:336:13)

Problem: When running js-data-http in Node.js it attempts to open a connection to whatever endpoint you have specified. If the server is not up, it creates an ECONNREFUSED Error. By default, js-data-http tries to log both error and success promise callbacks with the same function, logResponse, which assumes an object structure that is not an Error object.

ECONNREFUSED Error object:

{ [Error: connect ECONNREFUSED 127.0.0.1:80]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80 }

Line in logResponse() assumes a data.config.method... object structure to exist.

let str = `${start.toUTCString()} - ${data.config.method.toUpperCase()} ${data.config.url} - ${data.status} ${(new Date().getTime() - start.getTime())}ms`;

I will work on a PR for this.

Angular/HTTP: Canceling requests with timeout promise does not work

This bug was found while trying to address the problem of how to cancel a request made with js-data in Angular.

At one point, it was suggested to pass a promise as the timeout property in the options to findAll, since that's the mechanism that Angular provides for canceling requests made with $http. However, this is not canceling the callback after the timeout promise is resolved.

I dug into it, and the reason it's not doing it is because js-data-http's findAll and HTTP methods start out by doing a copy on the config. That deep copy clones the timeout promise, and so resolving the original timeout promise doesn't resolve the clone.

I tried modifying the code in the js-data-angular dist to see if creating a shallow copy (using _.clone) instead of a deep copy (copy from JSUtils) in findAll and HTTP would fix the issue, and it worked for findAll at first glance. However, it seems that other methods besides findAll would have the same issue, and when I replaced copy with _.clone in find, I got this error:

Error: organizations.inject: "attrs" must contain the property specified by "idAttribute"!

So it appears that there's something else going on at a different level that could prevent a shallow clone from working generically across the different methods. I'm not sure what.

Another approach that would fix this specific issue, would be to have the copy code check to see if the source argument is a Promise (not sure how to do that 100% correctly yet), and copy it by reference if so.

responseError callback no longer includes the actual error response object from the server

It's common for error responses returned from the server to contain a JSON object similar to this:

{
  "status": 400,
  "error": "You forgot to enter your name"
}

I've found it very useful in the past to do something like this when configuring the http adapter:

var httpAdapter = new JSDataHttp.HttpAdapter({
  responseError: function (response, config, options) {
    console.log('response error', response, config, options)
    if (response.status === 401) {
      // display login modal
    } else if (response.status === 426) {
      // Prompt user to refresh the page since the code is outdated
    } else {
      // Alert the user that there was an error with this request
    }
  }
})

While it's good practice to handle errors within the components of an application (and I do often), it's also nice to have this to notify a user whenever there is an error (in a Toast in the corner) and what the error was. Mainly it's nice when a session expires and a 401 request is returned to be able to have a single place within the application to open the login dialog so a user can re-authenticate without losing all their work.

This has been working in the past but no longer does. When I log what is passed into the responseError method in the latest version (3.0.0-rc.2) I see that it is just this, a regular old JS error:
Error: Request failed with status code 400(…)

Would be fantastic if response.status and response.data.error both existed still rather than just returning an instantiation of the Error class... or just the ability to get the response object that "errored" somehow. Same story with the error method in the HttpAdapter configuration.

Steps to reproduce:

  1. Set up an environment with both JSData and JSDataHttp (3.0.0-rc.2)
  2. When configuring HttpAdapter, include the above configuration for responseError
  3. Make any request using JSData to an endpoint that returns an HTTP status code in the 400s or 500s and includes a JSON object in the body of the response.
  4. Observe that the logged data from the console.log inside of responseError only has a vanilla JS Error object rather than the actual response object that it used to.
  5. Downgrade JSDataHttp to (3.0.0-beta.8)
  6. Re-run the same request
  7. Observe that the first parameter of the responseError callback contains an object which has both status and data properties filled appropriately.

Add support for patch / patrial update method

If the API supports PATCH then it's ideal to use PATCH instead of PUT when updating a specific property or set of properties. This avoids the need for more complex serialize and deserialize logic, prevents unwanted properties from being sent to API, and gives precise control to the developer.

A DSPatch method make a PATCH request with individual selected properties, and update only those properties on when model on success.

For example:

// single property
this.wheel.current_owner = 99;
this.wheen.patch('current_owner');
PATCH /wheels/1 {current_owner: 99}

// multiple
this.wheel.last_service = new Date();
this.wheel.patch(['current_owner', last_service]);
PATCH /wheels/1 {current_owner: 99, last_service: Date}

Module not found: Error: Cannot resolve module 'axios'

We recently started seeing:
Module not found: Error: Cannot resolve module 'axios' during our webpack build.

I noticed that axios was recently made a devDependency instead of a dependency in package.json.

By making it a dependency, the error disappears.

Adding support for form-data

It would be great to have support for form-data in the httpAdapter to upload files via HTTP. Angulars $resource comes with this support built-in (attaching form-data and setting headers):

var data = $resource('/data/:id', {}, {
  post: {
    method: 'POST',
    transformRequest: function(data) {
      var fd = new FormData();
      fd.append('file', data);
      return fd;
    },
    headers: {'Content-Type': undefined}
  }
};

_this.defaults.log() throws Illegal invocation

Here's the stack:

TypeError: Illegal invocation
    at http://localhost:8888/bower_components/js-data-http/dist/js-data-http.js:1365:22
    at invokeCallback (http://localhost:8888/bower_components/js-data-http/dist/js-data-http.js:890:15)
    at publish (http://localhost:8888/bower_components/js-data-http/dist/js-data-http.js:935:5)
    at publishFulfillment (http://localhost:8888/bower_components/js-data-http/dist/js-data-http.js:1041:3)
    at MutationObserver.flush (http://localhost:8888/bower_components/js-data-http/dist/js-data-http.js:752:5) 

Also: _this.defaults.log === console.log === true

Feature Request: Option to allow 404 response to be interpretted as No content (204) response

We are using loopback.io for our REST back end. If we make a valid REST requests, but no record(s) are found, the reply code is 404, rather than 204. The http adapter treats anything outside of 200-299 as an error. Could we add an option to allow 404 to be interpreted as Not Found. I looked through the loopback code, and it doesn't appear to be configurable on their side.

Error with window on Universal Rendering

I'm trying to use js-data-http with universal rendering but I got an error about window's existence

FAILED: window is not defined ReferenceError: window is not defined
at Object.<anonymous> (xxxxx/node_modules/js-data-http/dist/webpack:/~/axios/lib/adapters/xhr.js:16:1)
at __webpack_require__ (xxxxx/node_modules/js-data-http/dist/js-data-http.js:38:30)
at executor (xxxxx/node_modules/js-data-http/dist/webpack:/~/axios/lib/core/dispatchRequest.js:31:1)
at dispatchRequest (xxxxx/node_modules/js-data-http/dist/webpack:/~/axios/lib/core/dispatchRequest.js:19:1)
at process._tickCallback (internal/process/next_tick.js:103:7)
(node:25772) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): ReferenceError: window is not defined

Regarding this code

	      if (typeof config.adapter === 'function') {
	        // For custom adapter support
	        adapter = config.adapter;
	      } else if (typeof XMLHttpRequest !== 'undefined') {
	        // For browsers use XHR adapter
	        adapter = __webpack_require__(8);
	      } else if (typeof process !== 'undefined') {
	        // For node use HTTP adapter
	        adapter = __webpack_require__(8);
	      }

it require the same function for browser or node but in this function, window object is used without checking its existance.

BTW, thanks a lot for js-data and those adapter...your job is quite impressive

how to access to ALL respose headers?

The response contains many headers, for example:

Content-Type:application/json; charset=UTF-8
Date:Mon, 17 Aug 2015 09:34:01 GMT
Server:nginx/1.6.2 (Ubuntu)
Transfer-Encoding:chunked
X-Pagination-Current-Page:1
...

But js-data-http show only content-type:

adapter.defaults.deserialize = (resource, data) => {
  console.log(data.headers) // Object {content-type: "application/json; charset=UTF-8"}
}

How can i access to all?

DS.find Batching

@jmdobry What are your thoughts on an option to batch the DS.find requests for a particular resource? I wrote an implementation, but I think it would be more efficient / effective if it were built in rather than monkey patched.

This is my current implementation:

var find = DS.find.bind(DS);
DS.find = function (model, id, opts={}) {
    let resource = DS.definitions[model];
    if(id && ('batch' in opts ? opts.batch : resource.batchFinds)) {
        return batch_request(model, id);
    } else {
        return find(model, id, opts);
    }
};

let _batch_cache = {};
function do_batch_request (model) {
    let m = _batch_cache[model],
        ids = m.ids.splice(0, m.ids.length),
        deferreds = m.deferreds.splice(0, m.deferreds.length);
    DS.fetchAll(model, ids).then(objs => {
        ids.forEach((id, index) => {
            let obj = _.find(objs, {id: id}),
                deferred = deferreds[index];
            if(obj) {
                deferred.resolve(obj);
            } else {
                deferred.reject();
            }
        });
    }, err => {
        deferreds.forEach(deferred => {
            deferred.reject(err);
        });
    });
}

function batch_request (model, id) {
    let deferred = $q.defer(),
        batch;

    if(model in _batch_cache) {
        batch = _batch_cache[model];
        batch.ids.push(id);
        batch.deferreds.push(deferred);
    } else {
        batch = {
            debounce: _.debounce(do_batch_request, 60, {
                maxWait: 240,
            }),
            ids: [id],
            deferreds: [deferred],
        };
        _batch_cache[model] = batch;
    }
    batch.debounce(model);

    return deferred.promise;
}

DS.fetchAll = function (model, ids=[], opts={}) {
    return DS.findAll(model, {
        ids: ids.filter(id => id).join()
    }, opts);
};

Batching is more useful for high latency http requests, which is why I'm opening this here rather than on the main library. (But if you think it would make more sense otherwise, I'm all ears)

Update axios compatibility to 0.15.x, separate as dependency.

We use axios and would like to take advantage of some newer features/updates in js-data-http@3.
Most notably:

The second requires changes to the API, or at least additional lowercase methods, with uppercase methods still around for backwards compatibility.

Would also be great to be able to share the same axios module and save a few bytes. Kind of in the same way Promise is depended on, or was configurable in js-data@2. Yes, we can pass in an http option in the constructor, but axios is still baked in. Maybe a bring-your-own-http-lib build?

I would be more than willing to submit a PR, but wanted to check first if any of this would be in-line with the vision for the project.

Thanks!

Error when attempting to use js-data-http with sinon

I'm attempting to use js-data with JSPM and was starting by writing a test to understand how js-data / js-data-http works but have already ran into an issue. Below is the test I'm attempting to run with Karma / Chrome

import JSData from 'js-data';
import DSHttpAdapter from 'js-data-http';
import sinon from 'sinon';

describe("JSData Suite", function() {
  beforeEach(function() {
    this.xhr = sinon.useFakeXMLHttpRequest();
    this.requests = [];
    this.xhr.onCreate = function (xhr) {
      console.log('request found', xhr);
      this.requests.push(xhr);
      console.log('request pushed');
    };

    this.store = new JSData.DS();
    this.store.registerAdapter('http', new DSHttpAdapter(), { default: true } );
    this.User = this.store.defineResource('user');
  });

  afterEach(function() {
    // Restore the global timer functions to their native implementations
    this.xhr.restore();
  });

  it("User resource", function(done) {
    this.User.find(1).then(function(data) {
        console.log('RESPONSE');
        console.log(data);
        expect(data).to.exist;
        expect(data.id).to.equal(1);
        done();
    });

    setTimeout(() => {
        console.log('responding...');
        this.requests[0].respond(200, { "Content-Type": "application/json" }, JSON.stringify({id: 1, name: 'Sean'}));
    }, 100);
  });
});

and the output:

INFO: null, 'new data store created', Defaults{}, null, null
INFO: null, 'registerAdapter', 'http', DSHttpAdapter{defaults: Defaults{log: function (a, b) { ... }, error: function (a, b) { ... }}}, Object{default: true}
INFO: null, 'default adapter is http', null, null, null
INFO: 'user', 'Preparing resource.', null, null, null
INFO: 'user', 'Done preparing resource.', null, null, null
INFO: 'user', 'find', 1, Defaults{}, null
INFO: null, 'getAdapter', Defaults{}, null, null
LOG: 'request found', FakeXMLHttpRequest{readyState: 0, requestHeaders: Object{}, requestBody: null, status: 0, statusText: '', upload: UploadProgress{eventListeners: Object{progress: ..., load: ..., abort: ..., error: ...}}, responseType: '', response: '', withCredentials: false, eventListeners: Object{loadend: [...], abort: [...], load: [...], loadstart: [...]}}
ERROR: 'Potentially unhandled rejection [5] TypeError: Cannot read property 'method' of undefined
    at logResponse (http://localhost:9876/base/jspm_packages/npm/[email protected]/dist/js-data-http.js:150:73)
    at O (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:7439)
    at K (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:7071)
    at z.when (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:10953)
    at x.v.run (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:9781)
    at a._drain (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:1740)
    at drain (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:1394)
    at MutationObserver.b (http://localhost:9876/base/jspm_packages/es6-module-loader.js?7c8d992be9f4d67806fc861d6662acb5c4ad5c24:7:3302)'
LOG: 'responding...'
  JSData Suite
    ✖ User resource

Finished in 0.424 secs / NaN secs

SUMMARY:
✔ 0 tests completed
✖ 1 tests failed

FAILED TESTS:
  JSData Suite
    ✖ User resource
      Chrome 43.0.2357 (Mac OS X 10.10.3)
    Uncaught TypeError: Cannot read property 'respond' of undefined (/Users/smlynch/Development/playground/js-data-test/test/simple.test.js!eval:48)
    Error: Uncaught TypeError: Cannot read property 'respond' of undefined (base/test/simple.test.js!eval:48)

Here is my package.json:

{
  "jspm": {
    "directories": {},
    "dependencies": {
      "js-data": "npm:js-data@1",
      "js-data-http": "npm:js-data-http@1",
      "js-data-schema": "npm:js-data-schema@1",
      "sinon": "npm:sinon@^1.15.3"
    },
    "devDependencies": {
      "babel": "npm:babel-core@^5.1.13",
      "babel-runtime": "npm:babel-runtime@^5.1.13",
      "core-js": "npm:core-js@^0.9.4"
    }
  },
  "devDependencies": {
    "karma": "^0.12.36",
    "karma-chrome-launcher": "^0.1.12",
    "karma-jasmine": "^0.3.5",
    "karma-mocha": "^0.1.10",
    "karma-mocha-reporter": "^1.0.2",
    "karma-sinon-chai": "^1.0.0",
    "mocha": "^2.2.5"
  }
}

The primary error seems to come from this.requests.push(xhr); causing the error:

ERROR: 'Potentially unhandled rejection [5] TypeError: Cannot read property 'method' of undefined
    at logResponse (http://localhost:9876/base/jspm_packages/npm/[email protected]/dist/js-data-http.js:150:73)
...

I'm using js-data* 1.x as the 2.x betas (which are installed by default off npm if I didn't add @1) were giving me an error on new DSHttpAdapter() if I didn't pass an empty options object (ie. new DSHttpAdapter({}))

Handling Rails HEAD 204 on update

The problem

Rails default response to an update is :

    head :no_content

which is an empty response with a status code of 204 (NO CONTENT).

Even if you write :

    def update
        if @resource.update(params)
            render @resource, status: :ok
        end
    end

you'll still get an empty response (HEAD) with a 204 status code.

When you do a DS.find('resource', id), js-data will send a PUT request. It will then receive a HEAD 204 response and will try to inject the payload in the cache. So it will perform something like :

    DS.inject('resource', JSON.parse('')) // the '' comes from the empty payload in the HEAD response

and will throw an error (you can't inject an empty object).

The Rails solution

This stackoverflow question provides the Rails way to change the response.

The js-data solution

Step 1 : disable the injection

You can disable the injection when you update a resource.
You can disable it app wide :

    var DS = new JSData.DS({
        beforeUpdate = function (resource, data, cb) {
            resource.cacheResponse = false;
            cb(null, data);
        };
    });

or resource wide :

    var Resource = DS.defineResource({
        name: 'resource',
        beforeUpdate = function (resource, data, cb) {
            resource.cacheResponse = false;
            cb(null, data);
        };
    });

If you use Angular (app wide) :

angular.module('myApp', ['js-data'])
    .config(function (DSProvider) {
        DSProvider.defaults.beforeUpdate = function (resource, data, cb) {
            resource.cacheResponse = false;
            cb(null, data);
        };
    });

Step 2 : inject the resource manually

You just disabled the injection. If you stop here, this will happens :

    var myResource = DS.get('resource', 1);
    // { name: 'my resource' }
    myResource.name = 'a new name'
    myResource.DSSave();

    myResource = DS.get('resource', 1);
    // still { name: 'my resource' } because the updated resource wasn't injected

You have to inject the resource when the update is successful :

    var myResource = DS.get('resource', 1);
    // { name: 'my resource' }
    myResource.name = 'a new name'
    myResource.DSSave().then(function (data) { // data, the payload of the response, is empty
        DS.inject('resource', myResource);
    });

    myResource = DS.get('resource', 1);
    // { name: 'a new name' }

original question

I'm using Rails as my backend. It responds to successful PATCH/PUT request with a HEAD 204 (NO CONTENT).

When js-data gets the response, the data.data properties is "" and it triggers an error when js-data tries to inject it.

What is the proper way to handle this case (apart from tweaking Rails behaviour) ?

Overwrite config of an instance with typescript (v3)

hello,
I'm trying to change the http config (specifically the headers) after the adapter is instantiated.
I'm trying something like:

let adapter = new HttpAdapter({});
adapter.httpConfig = {headers: {}};
adapter.basePath = "test";

which results in "Property 'basePath' does not exist on type 'HttpAdapter'."

I can solve by setting the type of adapter to "any". Is there a better solution?

thanks

Apply new mjs file extension and remove imports from dependencies

I'm using Node 8.5's new es module import to run a SPA application in SSR mode in Node. In this case it's very useful to have the sourcecode for Node running without the need to transpile it. The implementation for Node dictates that the file extension for modules is '.mjs'. By renaming index.js to index.mjs, Node can easily import and use the file. Transpilers like rollup can handle different extensions without any problems, so it shouldn't be a problem for legacy builds.

Also, I'm not sure if that's due to my rollup settings, but when I do an import like:
import {HttpAdapter as DSHttpAdapter} from 'js-data-http'

Rollup will include js-data twice(once from js-data-http and once from js-data-adapter). Wouldn't it be much easier to keep the bundle size small, by assuming a global like:
const {utils} = JSData

Instead of import { utils } from 'js-data'

Using an external option for js-data in rollup seems a bit cumbersome when js-data is included in the same vendor.js file. I add a pull request just as demo(what works for me). Please let me know if I can help out. The same thing applies for js-data-adapter.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.