Giter Site home page Giter Site logo

amiel / ember-data-url-templates Goto Github PK

View Code? Open in Web Editor NEW
129.0 6.0 23.0 1.27 MB

an ember-addon to allow building urls with url templates instead of defining buildURL

Home Page: https://github.com/amiel/ember-data-url-templates/wiki

License: MIT License

JavaScript 92.14% HTML 7.86%
hacktoberfest ember-data addon ember

ember-data-url-templates's People

Contributors

aklkv avatar amiel avatar bcardarella avatar courajs avatar cwhittl avatar dependabot[bot] avatar dfreeman avatar ember-tomster avatar florianthiel avatar hodofhod avatar igort avatar rmharrison 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  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  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

ember-data-url-templates's Issues

Adapter tests not returning proper URLs

I'm trying to fix some adapter unit tests I've written to make sure that the url generated for the route, in this case a query grabbing the current user, but the urlForQueryRecord isn't returning the correct URL, even when passing the correct options.

The route works just fine in my application, just not the tests. I'm not even doing anything fancy. Here's a look at the adapter:

  queryRecordUrlTemplate: '{+host}/{+namespace}/{pathForType}{/current}{/id}{?query*}',

  urlSegments: {
    current: function(type, id, snapshot, query) {
      if (query && query.current) {
        delete query.current;
        return 'current';
      }
    }
  }

and the test:

let adapter = this.subject(),
     urlForCurrentUser = adapter.urlForQueryRecord({ current: true }, 'users');
assert.equal(urlForCurrentUser, 'http://test/v1/users/current', 'the url hits the users/current endpoint');

but in the end it returns a URL without the /current at the end. I tried reaching out on the Slack ember-data channel but sadly didn't get any responses to what is probably a simple answer.

What do I do if my create and update api is different?

This is how my api looks:

Find all - /api/contacts/{contact_id}/notes
create - /api/contacts/{contact_id}/notes
update - /api/contacts/{contact_id}/notes/{note_id}

// adapter:
{
  urlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  createRecordUrlTemplate: '{+host}/{+namespace}/contacts/{contactId}/notes',
  urlSegments: {
    contactId: (type, id, snapshot) => snapshot.adapterOptions.contactId,
    noteId: (type, id, snapshot) => snapshot.adapterOptions.noteId
  }
}

query keys in query string

The docs for query show how to include just certain keys in a request, but in my use I am still seeing the query keys being included in the query string. For example:

// example request and template
this.store.query('app', { 'appName': 'foo' })
queryUrlTemplate: '{+host}/apps/{appName}/app'

Yields this url:

https://foo.com/apps/foo/app?appName=foo

When I really want just this:

https://foo.com/apps/foo/app

Are the docs incorrect or is there something I'm doing incorrectly here?

Forward slash is being encoded

I have namespace set to api/v1 in my environment. After using template like

urlTemplate: '{+host}{/namespace}/post/{postId}/comments'

I get following path /api%2Fv1/post/1/comments which unfortunately is not recognized properly in Mirage server.

My temporary solution is by doing replace('%2F', '/') in overrided buildUrl but would be great to have that in base code.

findRecord(id) uses queryRecordUrlTemplate, not findRecordUrlTemplate

with these definitions;

  urlTemplate: '{+host}/commerce/stores/{storeId}/catalogues/{catalogueId}/product-groups{/id}{?query*}',
  queryUrlTemplate: '{+host}/commerce/stores/{storeId}/catalogues/{catalogueId}/product-groups{/id}{?query*}',
  queryRecordUrlTemplate:
    '{+host}/commerce/stores/{storeId}/catalogues/{catalogueId}/product-group{?query*}',
  findRecordUrlTemplate: '{+host}/commerce/stores/{storeId}/catalogues/{catalogueId}/product-groups{/id}{?query*}',

If I do

 .findRecord('commerce/product-group', productGroupId, {
        reload: true,
        include: 'parent.parent.parent.parent'
      })

The queryRecordUrlTemplate is used.

When I comment queryRecordUrlTemplate out findRecordUrlTemplate is used.

Am I doing this wrong? What logic is behind this?

Update to match ED 1.13

So in ED 1.13 it's no longer findQuery, but query and queryRecord, and so on. Are there plans to update this addon to follow the new API?

Namespace is escaped

(Sorry, this should probably be in an issue and not a PR)

I just ran into the problem that the "namespace" part of the URL is escaped. This makes it impossible to use namespaces like api/v1/... with this.

I "fixed" the original test to demonstrate it is failing. #3

If you point me into the right direction I could also try and fix this.

Conflict between ember-data-url-templates and Route's error action

I'm running into an issue where the Route's error event/action is not triggered when using this addon. (http://emberjs.com/api/classes/Ember.Route.html#event_error)

// Index Route
import Ember from 'ember';

export default Ember.Route.extend({
  ...
  actions: {
    error(error) {
      console.log('APPLICATION ERROR');
      this._super(...arguments);
      console.log('ERROR', error);
      if (error.status === '404') {
        this.transitionTo('not-found');
      }
    },
  },
});
// Application Adapter
import DS from 'ember-data';
import UrlTemplates from 'ember-data-url-templates';

export default DS.JSONAPIAdapter.extend(UrlTemplates, {
  host: '',
  namespace: 'v1/foo',

  urlTemplate: '{+host}/{+namespace}/{pathForType}{/id}{?query*}',
});

With the above setup the error action is never triggered so I'm unable to write custom error handling.

Using URL templates in serializer links

Hi,

I'm loving ember-data-url-templates, thanks for making it!

My REST serializers are for a non-standard API, and I find myself needing to override normalize response functions to add links to the data. If I don't add links in the serializer, Ember-Data will not recognize that there is a has many relationship.

Problem is, I don't want to hard-code each relative link by modifying the payload. I would rather just use ember-data-url-templates and have Ember assume there is a relationship if the template exists. Alternatively, I would like some way to expand/render the template myself while I add links (but the former method would be better)

What is the recommended way to accomplish this?

Thanks in advance!

404 from npmjs.org on install

Hi all,

When I try to install the addon, I get the following error:

$ember install ember-data-url-tempates
version: 1.13.14
Registry returned 404 for GET on https://registry.npmjs.org/ember-data-url-tempates
Error: Registry returned 404 for GET on https://registry.npmjs.org/ember-data-url-tempates

Array params have indexes now

Since the introduction of nested params, there seems to be something weird going on.
The nested array params have now number inside. include[0]: 'Foo', include[1]: bar

I know it's this way because we cannot have duplicate keys in a javascript object, but would it be possible to go back to work with an array. Or is this intended behavior @amiel ๐Ÿ˜… ?

Before:
screenshot 2018-10-18 at 15 11 02

After:
screenshot 2018-10-18 at 15 05 42

Docs not comprehensive

urlTemplate: '{+host}/posts/{postId}/comments{/id}',
What does it mean to put the + or the leading / in the brackets?

What arguments are available to the urlSegments callbacks?

Arrays not working right

Querying with something like:

{ foo: ["1", "2"] }

I cannot seem to construct any template that will actually give me

?foo[]=1&foo[]=2

Based on the documentation the following SHOULD work:

queryUrlTemplate: '{+host}/api/v2/whatever{?foo[]*}'

But in fact {?foo[]*} is entirely ignored.

Fastboot Support

Hello! Curious if it is anywhere in the roadmap to support FastBoot? (We love and have used ember-data-url-templates on just about every project.)

Working on converting my existing ember app to use FastBoot for the first time and I'm getting a There was an error running your app in fastboot. More info about the error: ReferenceError: UriTemplate is not defined.

References this block:

compileTemplate: function compileTemplate(template) {
  return new UriTemplate(template);
},

Custom urlSegments fails de build URL

I have a custom adapter defined as follows:

# adapters/shop-language.js

import ApplicationAdapter from './application';
import UrlTemplates from "ember-data-url-templates";

export default ApplicationAdapter.extend(UrlTemplates, {
  urlTemplate: '/shops/{shopId}/languages',
  findAllUrlTemplate: '/shops/{shopId}/languages',
  createRecordUrlTemplate: '/shops/{shopId}/languages',

  urlSegments: {
    shopId: function(type, id, snapshot, query) {
      console.log('query: ' + query.shop_id);
      //return snapshot.belongsTo('shop', { id: true }); -> fails to call belongsTo on undefined
    }
  },
});

When I try to save a new shop-language like that:

# controllers/shops/shop-languages.js

export default Controller.extend({
..
actions: {
  saveLanguage(aLanguage) {
       let shopLanguage = this.store.createRecord('shop-language', {
         language: aLanguage,
         shop: this.get('currentShop.shop')
       });

       shopLanguage.save().then(function() {
          console.log('New language added with success');
      });
     }
   }
});

I get the following displayed in the browser console:

query shop_id: 2
jquery.js:9600 XHR finished loading: GET "http://localhost:4200/languages".
XHR finished loading: GET "http://localhost:4200/shops/2/languages".

+++ in saveLanguage: lang: 3
Uncaught TypeError: Cannot read property 'shop_id' of undefined
    at Class.shopId (shop-language.js:16)
    at template.fill.name (url-templates.js:31)
    at subFunction (uri-templates.js:103)
    at UriTemplate.fill (uri-templates.js:391)
    at Class.buildURL (url-templates.js:27)
    at Class.superWrapper [as buildURL] (ember-utils.js:420)
    at Class.createRecord (rest.js:697)
    at _commit (-private.js:12280)
    at Class.flushPendingSave (-private.js:11342)
    at invoke (backburner.js:205)

It seems like I have no more querypresent when I trigger saveLanguage action.
When inspecting the values passed in to urlSegments, here is what I have:

 type = "shop-language", id = null, snapshot = null, query = {shop_id: "1"}

If I use return snapshot.belongsTo('shop', { id: true }); sa described in common urlSegments wi-ki page, it fails saying that:

Cannot read property 'belongsTo' of null

How is it possible to create a shop-language when the models are defined as follows:

# models/shop.js
import DS from 'ember-data';

export default DS.Model.extend({
  name:      DS.attr('string'),
  shopLanguages: DS.hasMany('shop-language'),
  languages:     DS.hasMany('language')
});

# models/shop-language.js

export default DS.Model.extend({
  modifiedBy:      DS.attr('string'),
  shop: DS.belongsTo('shop'),
  language: DS.belongsTo('language')
});

# models/language.js

export default DS.Model.extend({
  tag:      DS.attr('string')
});

Used JS versions:

  • Ember 3.0
  • ember-data-url-templates": "^0.4.0",

Thank you.

Return custom adapter URL outside adapter

I'm writing a custom ajax request in a route and I'd like to be able to return the URL that is generated by a custom adapter using data-url-templates.
Is this possible?

So, call the specific adapter's urlFor... method

this.get('store').adapterFor('custom_endpoint').urlForFindAll('custom_endpoint');

Currently it returns: /api/commerce/v1/custom_endpoint
Ideally have this return: /api/commerce/v1/custom/5/endpoint (whatever is setup in urlTemplates)

Update documentation to include `adapterOptions` example

The addon uses urlSegments for dynamic portions of nested routes. How to pass information from the model to the functions of urlSegments is non-obvious.

As of 72c1aad, the README uses sessions.
Catch: Managing state in a singleton; bad bad. That's what the router is for.

A stackoverflow post mentions the use of query.
Catch: Query is null for most common urlFor* methods such as urlForFindAll() <-- this.store.findAll(). Must use this.store.query() or this.store.queryRecord()

I prefer snapshot.adapterOptions, as snapshot is available for all urlFor* methods.

Details...
slides, video

Nested query objects not working

Not sure if I'm doing something wrong, but I've checked the docs and played around a lot, and I can't seem to get a query with nested params working.

Eg: with the following query object:

{ filter: { offset: 0 }}

I'd expect the {?query*} part of the template to render as ?filter[offset]=0, but instead I get ?filter=%5Bobject%20Object%5D

IDs are double URI-encoded

It looks as though the id segment provided out of the box gets escaped both in the mixin and again in the uri-templates library itself.

This twiddle demonstrates the issue โ€“ you can see the space in the ID gets double encoded into %2520.

Should the call to sanitize just be taken out of the default id segment?

Example of Custom URL for Nested Resources

I currently have the following URL I am trying to get all photos belong to a user:

/users/:user_id/photos

I see in the wiki that it is possible to use URL Segments for createRecordUrlTemplate using snapshots to get the ID. However, what is the best way to handle building the path for findAllUrlTemplate to get the ID for the parent aka users?

In the URL Segments, the snapshot will be null for findAll and query.

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.