kurko / ember-json-api Goto Github PK
View Code? Open in Web Editor NEWJSON API adapter for Ember Data.
License: MIT License
JSON API adapter for Ember Data.
License: MIT License
Response:
{
"accounts": [
"2688051d-dcfa-42af-9c7b-72ac55192981"
],
"meta": {
"limit": 10,
"filters": {},
"includes": [],
"fields": [
"id"
]
},
"links": {},
"linked": {}
}
The specification allowing this body: http://jsonapi.org/format/#document-structure-resource-collection-representations
A collection of any number of resources SHOULD be represented as an array of resource objects or IDs, or as a single "collection object" (described below).
Emphasis mine.
ember-json-api error:
Error while processing route: index Assertion Failed: You must include an `id` for endorsemint@model:account: in an object passed to `push` Error: Assertion Failed: You must include an `id` for endorsemint@model:account: in an object passed to `push`
at new Error (native)
at Error.EmberError (http://localhost:4200/assets/vendor.js:26712:23)
at Object.Ember.assert (http://localhost:4200/assets/vendor.js:16896:15)
at Ember.Object.extend.push (http://localhost:4200/assets/vendor.js:72942:15)
at Ember.Object.extend.pushMany (http://localhost:4200/assets/vendor.js:73103:28)
at http://localhost:4200/assets/vendor.js:73467:15
at tryCatch (http://localhost:4200/assets/vendor.js:58992:16)
at invokeCallback (http://localhost:4200/assets/vendor.js:59004:17)
at publish (http://localhost:4200/assets/vendor.js:58975:11)
at http://localhost:4200/assets/vendor.js:42243:9
I'm in the process of creating an api to expose sequelize models with the JSON API format. Specifically this is for an ember project so I would like to support this module's implementation but I think I've already overshot with some of the URL relationships.
Some more documentation on the current support of the JSON API would be very helpful.
In my ember.js I use this adapter to use ember-data with fortunejs but the request in browser fail.
Ember:
this.store.find('post');
Here is a dump of the request which fires the browser as cURL:
curl 'https://localhost:61457/posts' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Cache-Control: max-age=0' -H 'Origin: http://localhost:9000' -H 'Referer: http://localhost:9000/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36' --compressed
cURL says on commandline on this:
curl: (35) Server aborted the SSL handshake
This should enable an API client to not worry about hard-coding resource paths, and also add the possibility to extract extra information from the top-level "meta" object.
According to the currently published JSON API spec, singular resources are to be wrapped in arrays and keyed with the plural form of the resource type.
ember-json-api expects:
{
"post": {
"id": 1,
"title": "First Post"
}
}
And what JSON API-compliant implementations provide:
{
"posts": [{
"id": 1,
"title": "First Post"
}]
}
I'm maintaining now this project (huge props to @daliwali) and I need to make some changes. First important one imo is moving to ES6. Some members expressed that this could end up being merged into Ember Data's itself (/cc @fivetanley).
phantomjs
)@raycohen @denisnazarov @egeriis @lukemelia @stefanpenner could you guys chime in? I am gonna work on this in the next couple of days and I know you guys opened PRs already, so if you see any drawbacks about moving to Broccoli, please leave a comment.
Sorry for my ignorance and if this is the wrong place to ask; but I'm confused as to what problem this package solves. Doesn't Ember Data's built-in REST adapter already support JSON API out of the box?
I have a JSON API where the API appears at the prefix /api/
, so that the collection of users is available at http://example.com/api/users . If an object has a link, it looks something like:
{
"posts": [{
"content": "My awesome post",
"links": {
"user": "123"
}
}],
"links": {
"posts.user": {
"href": "http://example.com/api/users/{posts.user}",
"type": "users"
}
}
}
I added a namespace to the adapter:
App.ApplicationAdapter = DS.JsonApiAdapter.extend({
namespace: 'api',
})
This makes the first request to fetch posts, but it adds the entry 'api/users/{post.user}' to DS._routes["user"]
. adapter.buildURL
then returns /api/api/users/1
as the URL for user 1, doubling the namespace prefix.
The namespace should be removed from URLs in DS._routes
, either in the serializer (but I'm not sure how to pass the namespace from the adapter to the serializer) or in the adapter (but only when loading a route).
I'm testing against ember-data 1.0.0-beta.9, but DS.RESTAdapter.urlPrefix()
was adding namespaces back in beta 3, so I don't think this is new in beta 9.
Anything in the works to support rc3 (or really the impending 1.0)?
README
installation instructionsThis also relates to #38
Currently, the adapter still follows the default REST adapter behaviour when updating records, which is to PUT the entire resource. A smarter, better approach would be to only serialize changes, and send the request as a PATCH.
The request might look something like this:
PATCH /animals/123
Content-Type: application/json-patch+json
[
{"op": "replace", "path": "/animals/0/name", "value": "Tomster"},
{"op": "replace", "path": "/animals/0/links/friends", "value": ["124"]}
]
This is a list of things we need to test to make sure the adapter abides to JSONAPI.org.
Strikethrough text is not planned.
Hey, thanks for your work on this. I experienced some confusion when I saw in the README that it’s compatible with JSON API 1.0 rc1 because I couldn’t find any versioning on their site. I tried out the JSON structure described on their site with this adapter and it didn’t work because the data
container, I now realise, is a change made in rc2.
So I’m wondering whether you have plans to update for rc2. Do you need any help with it?
@daliwali Have you tested the ember-json-api with pushPayload?
Hi,
Currently this library does not support urls for hasMany relations. In the server response, you have to pass all the IDs of the related resource in order to fetch it. Isn't it much better to also support URLs to point the client to the correct API call to fetch the related resources.
This is how you now would return a post with the related comments (these will be fetched async)
{
"posts": [
{
"id": 1,
"title": "First post",
"links": {
"comments": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
}
}
]
}
Those IDs could become huge and eventually you will even get an HTTP error for URI to long.
It would be much better to support something like this (using this in my Ember project too, along with this library):
{
"posts": [
{
"id": 1,
"title": "First post",
"links": {
"comments": {
"href": "/api/v1/post/1/comments"
}
}
}
]
}
WDYT? If you guys like it, I can create a pull request right away 👍
Per jsonapi.org spec it should be possible to pass errors alone or alongside other payload. But it appears that ember-json-api doesn't handle this correctly, as Ember Data is trying to look for an error model when I return an errors
array with my payload.
Example payload:
{
"goals": [
{
"id": 2,
"badge_id": 5,
"target": 100,
"target_type": "actions",
"target_title": "",
"target_description": "",
"start": "2014-09-18",
"end": "2014-09-25",
"name": "My goal",
"description": "Nullam quis risus eget urna mollis ornare vel eu leo. Donec sed odio dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nulla vitae elit libero, a pharetra augue. Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"visible_to": "select",
"created_at": "2014-09-11 10:48:08",
"updated_at": "2014-09-11 10:48:08",
"deleted_at": null,
"links": {
"category": 2
}
},
{
"id": 3,
"badge_id": 5,
"target": 150,
"target_type": "actions",
"target_title": "",
"target_description": "",
"start": "2014-09-19",
"end": "2014-09-25",
"name": "ABC",
"description": "Nulla vitae elit libero, a pharetra augue. Etiam porta sem malesuada magna mollis euismod. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam quis risus eget urna mollis ornare vel eu leo. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.",
"visible_to": "select",
"created_at": "2014-09-11 10:51:07",
"updated_at": "2014-09-11 10:55:53",
"deleted_at": null,
"links": {
"category": 2
}
}
],
"errors": [
{
"code": 2,
"title": "Unknown linked resources requested",
"description": "These linked resources are not available: departments"
}
]
}
When I save a new model to be persisted on the server, the payload for relationships appears to be wrong. In this example options
is a hasMany
relationship:
{
"surveys": [
{
"title": "abc",
"description": "test",
"end": "2014-09-11",
"links": {
"options": [
null,
null,
null
]
}
}
]
}
Model for option
looks like this:
module.exports = DS.Model.extend({
title: DS.attr()
});
README
, it needs to be made more clear that this is intended to be used with ember-cli
.url templating is only aware of the current model's ID, but to be compatible actually needs reference to the entire model.
This may need some ember-data level adjustments, but well worth it.
example:
{
"links": {
"posts.comments": "http://example.com/comments/{posts.comments}"
}
}
the built url, incorrectly templates {posts.comments}
with the primary models id.
http://jsonapi.org/format/#document-url-template-shorthands elaborates other variations.
(cc @rjackson you mentioned similar ideas earlier today)
Currently, this works for ember data 0.13 - 0.14, but the 1.0 beta breaks everything.
This is a list of things we need to test to make sure the adapter abides to JSONAPI.org.
test_frontend$ ember install:addon ember-json-api
version: 0.2.1
Installed packages for tooling via npm.
The package `ember-json-api` is not a properly formatted package, we have used a fallback lookup to resolve it at `/Users/<snip>/test_frontend/node_modules/ember-json-api`. This is generally caused by an addon not having a `main` entry point (or `index.js`).
Installed addon package.
Bower complaints that there are no tags to "satisfy ~0.0.8".
It seems that if I try and pass any query parameters to the store.find function the URL request gets a bit messed up. The following code works correctly:
export default Ember.Route.extend({
model: function() {
return this.store.find('account');
}
});
but the following
export default Ember.Route.extend({
model: function() {
return this.store.find('account', {"a":"b"});
}
});
results in a url request that looks like this: http://myapi.com/accounts/%5Bobject%20Object%5D?a=b
Any ideas what might be going wrong?
I'm using Ember 1.12.0 and Ember Data 1.0.0-beta.17
Currently the links data is saved on the global static DS object, which leaks data. For example when testing you could get old data.
In the latest jsonapi.org Standard, the url to fetch related records was renamed to resource
, see http://jsonapi.org/format/#document-structure-resource-relationships
With two models related in a 1:1 fashion:
Person:
lead: DS.belongsTo('lead', { async: true }),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
photo_url: DS.attr('string'),
Lead:
person: DS.belongsTo('person', { async: true }),
username: DS.attr('string'),
I'm receiving the following JSON from my web service:
{
"leads": [
{
"id": 13,
"person_id": 56,
"username": "[email protected]"
"type": "leads"
"href": "/leads/13",
"links": {
"person": 56
},
},
{
"id": 14,
"person_id": 57,
"username": "[email protected]"
"type": "leads"
"href": "/leads/14",
"links": {
"person": 57
},
},
],
"linked": {
"person": [
{
"id": 56,
"first_name": "Emily",
"last_name": "Dougals",
"gender": "Female",
"type": "peoples",
"href": "/people/56",
},
{
"id": 57,
"first_name": "Joe",
"last_name": "Ingersoll",
"gender": "Male",
"type": "peoples",
"href": "/people/57",
},
]
},
"links": {
"leads.person": {
"href": "/people/{person.person_id}",
"type": "peoples"
}
}
}
All four objects are being loaded as expected into their respective models, as seen in the Ember Inspector. However, the warning WARNING: The payload for 'people@model:lead:' contains these unknown keys: [href,person_id,peoples]
is received, and the objects are not acting like they are linked. In other words, I'm able to access 'lead.username' in my templates, but not 'lead.person.firstName' or any other field on the person object.
When I convert my web service response and use the standard ActiveModel Adapter/Serializer in Ember it functions as expected.
I'm happy to provide more information as needed. Thank you.
This would fit nicely as a bower component.
Then we could setup a package.json
for fortune. Then a bower.json
for ember, ember-data, and ember-json-api.
The beta-15 breaking changes may delay some apps from upgrading. I'm disappointed with the lack of semantic versioning of ember data but it does perhaps call for tracking to ember-data versions here.
Ugly, but perhaps branches 1.0.0-beta.14-v0.2.3
and 1.0.0-beta.15-v0.3.0
might be good names until data hits 1.0. Basically I may need to stick with beta.14 for now.
Thoughts?
The Ember Data team has decided to support JSON API out of the box in the upcoming v1.0 release. Given these developments we have decided to deprecate this library and move our users to the official Ember Data solution.
This issue is to keep track of other issues related to this topic. But should also serve as a place to discuss what we can do to make the migration as smooth as possible.
Maybe I'm just doing something wrong, but this package isn't working for me. My very simple server response looks like
{"links":{"self":"http://localhost:8080/api/bulletins"},"data":[]}
and Ember fails while warning me Encountered "data" in payload, but no model was found for model name "datum"
.
If, during, the serialization, I do
payload.bulletins = payload.data;
delete payload.data;
it works. Am I missing something, or are you?
This warning shows up when running ember s
:
The package `ember-json-api` is not a properly formatted package, we have used
a fallback lookup to resolve it at `/Users/marcoprins/Desktop/Project/ember_test/censored/node_modules/ember-json-api`.
This is generally caused by an addon not having a `main` entry point (or `index.js`).
And when I try to update , I get this error:
$ npm update ember-json-api
npm ERR! cb() never called!
Ember cli v0.2.7
Ember v1.13.0
Node.js v0.10.35
In the findHasMany
function, the relationship is being queried in the first line:
var hasManyLoaded = snapshot.hasMany(relationship.key).filter(function(item) { return !item.record.get('currentState.isEmpty'); });
However, it looks like now the result of snapshot.hasMany(relationship.key)
is coming back as undefined instead of an empty array, which I believe was the original result when I first wrote that line.
Changing to something like the following should resolve the issue:
var hasMany = snapshot.hasMany(relationship.key);
var hasManyLoaded = hasMany ? hasMany.filter(function(item) {
return !item.record.get('currentState.isEmpty');
}) : [];
I keep getting this error although I receive valid json api responses from the server.
example:
{"locations": [{"id":166,"lat":"51.4986658","lng":"-0.0593145","name":null,"type":null,"hyperlocation":null,"created_at":"2014-09-19T00:00:00+0100","updated_at":"2014-09-19T00:00:00+0100","distance":"0.0007320925290059726"}]}
this is the full error description:
Error: No model was found for 'toString'
at new Error (native)
at Error.EmberError (http://localhost/feelatlas/web/js/libs/ember.js:2965:23)
at DS.Store.Ember.Object.extend.modelFor (http://localhost/feelatlas/web/js/libs/ember-data.js:2979:29)
at DS.RESTSerializer.DS.JSONSerializer.extend.extractArray (http://localhost/feelatlas/web/js/libs/ember-data.js:8726:24)
at apply (http://localhost/feelatlas/web/js/libs/ember.js:7996:27)
at superWrapper (http://localhost/feelatlas/web/js/libs/ember.js:7570:15)
at DS.JSONSerializer.Ember.Object.extend.primaryKey as extractFindQuery
at DS.JSONSerializer.Ember.Object.extend.extract (http://localhost/feelatlas/web/js/libs/ember-data.js:549:33)
at http://localhost/feelatlas/web/js/libs/ember-data.js:3561:26
at invokeCallback (http://localhost/feelatlas/web/js/libs/ember.js:10558:19)
Here's my serializer:
DS.RESTSerializer.extend({
modelNameFromPayloadKey: function (payloadKey) {
return this._super('blabla' + payloadKey);
}
});
Using a JsonApiSerializer
, the modelNameFromPayloadKey
is not called:
JsonApiSerializer.extend({
modelNameFromPayloadKey: function (payloadKey) {'
// Not Called
return this._super('blabla' + payloadKey);
}
});
Hi,
I followed the instructions to install from the README, but it fails with this error:
Error: EACCES, mkdir '/usr/lib/node_modules/broccoli-cli'
Apparently the version at npm repo is outdated since it is running a postinstall command from package.json, which was removed in master:
npm install --save-dev broccoli && npm install --global broccoli-cli
I installed directly from github, the installation then succeeds, but running ember-cli serve, fails with this error:
File: rafee/adapters/application.js
ENOENT, no such file or directory '/home/pablo/projects/rafee/frontend/tmp/tree_merger-tmp_dest_dir- H1IaEAAE.tmp/json_api_adapter.js'
Using ember-cli 0.1.2
Not sure what I'm missing here
Just found out about the latest changes to the spec, wondering if support for them is in the works?
I couldn't find any hint in http://jsonapi.org/, but how should URLs for models like PlaceRequest
look like? api/place_requests
(ED uses this today) or api/place-requests
(Everything is hyphenated in ember-cli)
//cc @stefanpenner
When model has length
field and we have single model returned from server like this:
{
"tracks": {
"title": "bla-bla",
"length": 42,
}
}
Note that tracks
is not an array.
Problem caused by extractSingle()
method which uses Ember.isArray()
which assumes anything to be an array if it has length
property =(
Not sure is it an Ember issue or not.
After an attempt to use this adapter all data-binding was lost. API calls are being made, but in the store.find promise method an empty array is always returned even though it can be seen that data is returned via the inspector.
The only method that seems to be called through the lifetime of the app is the buildURL. The previously existing code that was using the RESTAdapter was working and the code below is what is currently being used. The only change involved replacing the DS.RESTAdapter
with DS.JsonApiAdapter
.
Am I missing something?
import AppRoute from "./app";
export default AppRoute.extend({
model: function() {
return this.store.find('class').then(function(classes) {
// classes is always an empty array
return classes.sortBy('name');
});
}
});
export default DS.JsonApiAdapter.extend({
needs: ['service:session'],
host: AppENV.APP.API_URL,
headers: function() {
return {
'accept': 'application/json',
'Content-Type': 'application/json',
'x-auth-token': this.get("session.token"),
};
}.property("session.token")
});
Hello,
Is there a specific reason why the adapter does not set these two JSON Api Specific headers automatically?
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json
I was wondering if there is a specific reason before I submit a PR :)
ember-json-api/src/json-api-serializer.js
Line 47 in 899825d
linkValue
is null
it will pass the typeof 'object'
test. Should just add linkValue &&
to the start of that conditional.
I will try to PR soon.
the file naming convention of ember-cli and the ember ecosystem in general is dasherized rather than snake case (underscores).
it would be great if json_api_adapter.js
and json_api_serializer.js
were renamed to json-api-adapter.js
and json-api-serializer.js
Using stable-beta-3, how do I save a model with a new belongsTo value of null?
I'm not sure if you're going to update this library to support JSON API 1.0, but if you are, I submitted this PR eneuhauser#14 to a more up to date fork that you might want to build on.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.