Giter Club home page Giter Club logo

ampersand-rest-collection's People

Contributors

bear avatar henrikjoreteg avatar latentflip avatar lukekarrys avatar pgilad avatar redclov3r avatar thisiserico avatar wraithgar avatar zefhemel 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ampersand-rest-collection's Issues

Issues when destroying multiple models from an ampersand-rest-collection

I have an instance of a rest collection with multiple models. When I request to destroy models from said collection via model.destroy(...), the first delete works, but subsequent ones fail. Note that I am trying to avoid re-fetching the entire collection between deletes.

I've created a gist to outline what I am doing and the results that I am seeing:
https://gist.github.com/gpicazo/f94e61e3b085f9f5840b

In the comments, I've re-stated what the issue is and how I am currently working around it.

length-property

Hi,

I have a rest-collection that I want to wait for. It is set on the view as such:

View.extend({
  initialize: function() {
    this.eventCollection = new HSEventCollection({
      url: url,
    });

   console.log(this.eventCollection.length)

   // this.eventCollection.fetch(); // <-- commented out to see what gets rendered
  }
})

Then, I want to wait for it to load before rendering in a sub-view:

subviews: {
  list: {
    container: '.item-container',
    waitFor: 'eventCollection.length',
    prepareView: function (el) {
      debug('prepareView', this.el, this.eventCollection)
      return new CollectionRenderer({
        el: el,
        collection: this.eventCollection,
        view: HSEventView
      });
    }
  },
}

The problem is that eventCollection.length is 1 before the fetch. It seems to contain an empty model.

Changing the log-statement to JSON.stringify(this.eventCollection.toJSON()) gives: "[{}].

Any ideas on what's going on / what I'm (again) missing?

Cheers!

Edit:
Just realized I cannot waitFor ''eventCollection.length'' as it is does not fire a change event in and by itself. Still the length issue...

How to handle header "Access-Control-Allow-Origin" for CORS

Trying to request cors request with code:

export default Collection.extend({
  model: person,
  url () {
    return 'http://127.0.0.1:5000/person/'
  },

  ajaxConfig: function () {
        return {
            headers: {
                'Access-Control-Allow-Origin': 'http//:127.0.0.1:3000'
            },
            xhrFields: {
                withCredentials: false
            }
        };
    },
})

I'm sending request with http//:127.0.0.1:3000 but if use ***** i still get error below

XMLHttpRequest cannot load http://127.0.0.1:5000/person/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

How to handle this kind of request?

fetchById should take secondary [xhr] options object

other examples:

collection.fetch([options])
collection.getOrFetch('id', [options], callback)

current: ๐Ÿ‘Ž

collection.fetchById('id', callback)

preferred: ๐Ÿ‘

collection.fetchById('id', [options], callback)

how can I use fetch() method

I use fetch() method like this :

let provinces = new ProvinceRestCollection();

provinces.fetch({
    success: function() {
        //$scope.provinces bind to the selectbox in view
        $scope.provinces = provinces.map(function (person) {
            return person.title;
        })
    }
});

but I want use it like this

let provinces = new ProvinceRestCollection();

provinces .fetch();

add success event listener in rest-collection like this :

let AmpersandRestCollection=require ("ampersand-rest-collection");

module.exports = AmpersandRestCollection.extend({
    url: 'https://jsonplaceholder.typicode.com/posts',
    success: function() {
        //$scope.provinces bind to the selectbox in view
        $scope.provinces = provinces.map(function (person) {
            return person.title;
        })
    }
});

constructor/initialize - suggestion

Hi again,

in ref to #26, I just wanted to get seconds on this opinion:

IMHO, it doesn't make sense for the rest-collection to have the same constructor as the basic collection; most use-cases will have the data loaded from an endpoint, not passed in to the constructor. So making the models-array param optional makes sense.

So the rest-collection constructor could do

module.exports = function(models, options) {
    // Resolve optional arguments
    if (isObject(models) && options === undefined) {
        options = models;
        models = null;
    }

    // [...]

   // Pass optional arguments to `initialize`
   var params = [options];
   if (isArray(models)) { params.unshift(models) };
   this.initialize.apply(this, params);

   if (models) this.reset(models, assign({silent: true}, options));
}

making sure you get the same arguments in your extended rest-collection.initialize as you pass into the constructor.

Then again, maybe I'm just a tad bit too fanatical here =)

Sync entire collection with server-side

I don't understand how it should be implemented. Manually (iterate and model.save / model.destroy one by one) or via some existing method?

There are something called "sync"

model.sync(method, collection, [options])

which is entirely undocumented and I had no luck trying to run this.
Even its signature looks broken (this is a quote from "ampersand-rest-collection" doc link so it ought to be collection.sync(...) at least!)

I thoroughly reviewed to this moment:

Someone states that this is low-level method and it should not be used for basic tasks. However the question remains. Basically I expected to empty entire collection on client and remove corresponding data on server by issuing next commands:

collection.reset();
collection.sync();

Technically, resulting error from the second line is

A "url" property or function must be specified

but this is obviously due to wrong arguments. By Backbone docs it looks like it should be called like

collection.sync("delete", collection, {})

which is totally bizarre. So I surrender and ask for help.

Preprocess XHR response

We are in the planning stages of implementing a new authentication scheme based on the HAWK signature authentications scheme. Using the planned scheme, we would need to generate a signature and append it to the AJAX header before each request for a protected resource. This can be accomplished easily enough with the ajaxConfig.beforeSend option ๐Ÿ‘

There are at least few scenarios under which the server may fail to authenticate the signature:

  1. The signature is invalid (was hashed using the wrong key/algorithm)
  2. The timestamp sent with the request is out of sync with the server's time

In the first case, we would like to catch the unauthorized response, and present a login-popup for the user to log in and re-generate their private key. Upon successful retrieval of a new key, we would like to resend the request. In the second case, we would like to re-send the request with a modified timestamp to compensate for skew between the client and server time.

How do you recommend handling these unauthorized responses without specifying an error handler for each .fetch, .sync call? Perhaps an ajaxConfig.error callback would allow us to intercept the unauthorized response, make adjustments and retry it.

Make type to POST

Where to deifn method, type, etc in the Collection.
Need to know how to use success too.

var Collection = AmpersandRestCollection.extend({
    url:'http://localhost:3000/users',
    model: SignupModel,
              type: "POST",
            method: "POST",
    ajaxConfig: function () {
        return {
            headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Accept':'text/html'
            },
            xhrFields: {
                withCredentials: false
            }
        };
    }
});

Fetching a model by id when model is dynamic

I have a particular collection that has a function for determining which model should be created instead of a model object as described in the documentation. However, I've run into an issue when fetchById is called for a model in that collection.

In the ampersand-collection-rest-mixins.js method fetchById() the line:

idObj[this.model.prototype.idAttribute] = id;

seems to assume that the model property will not be a generic function but instead some type of Ampersand-Model object. Has anyone run into this use case and if so what did they do to solve it?

collection.create doesn't save a model's children

I have a model that has children (i.e. links to other instances of 2 other model types).
The models are kept in a collection.

When calling collection.create with the data from the POST, the model is created with empty children. If I edit the model (at which point a simple model.save is performed), using the same form, the model properly gets its children populated.

I've gotten around this for now by calling collection.create which creates the model without the children and adds it to my collection, and then within that success function I'm calling model.save with the same data from the post. This is how it looks like:

prepareView: function (el) {
    return new ObjectForm({
        el: el,
        model: this.model,
        submitCallback: function (data) {
            //The form is submitted, data contains the info from the form, including the children models
            app.objects.create(data, {
                wait: true,
                success: function (model, response, options) {
                    // The children are not properly saved when using app.objects.create, so save the model again
                    // Note that the same data from the form is used, which does properly already contain the children
                    model.save(data, {
                        wait: true,
                        success: function (model, response, options) {
                          //Do other stuff
                          app.navigate('/admin/objects');

I would expect collection.create to create the model including the children, as those are present just fine in the data retrieved from the form.

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.