Ember Multitple belongTo relationships not working with JSONAPI - json

I have the following json api document:
{
"data": [
{
"type": "haves",
"id": "2708f443-0857-4ae9-9935-9aa4b4e9f721",
"attributes": {
"quantity": 1
},
"relationships": {
"card": {
"data": {
"type": "cards",
"id": "3be08f31-3361-404c-9977-23535ed837f3"
}
}
}
}
],
"included": [
{
"type": "cards",
"id": "3be08f31-3361-404c-9977-23535ed837f3",
"attributes": {
"name": "Name"
},
"relationships": {
"set": {
"data": {
"type": "sets",
"id": "0fec70de-02e0-4646-bdcf-f86acea90d23"
}
}
}
},
{
"type": "sets",
"id": "0fec70de-02e0-4646-bdcf-f86acea90d23",
"attributes": {
"name": "Name"
}
}
]
}
With the following ember models:
// app/models/have.js
export default DS.Model.extend({
quantity: DS.attr('number'),
minPrice: DS.attr('number'),
account: DS.belongsTo('account'),
card: DS.belongsTo('card')
});
// app/models/set.js
export default DS.Model.extend({
name: DS.attr('string'),
cards: DS.hasMany('card')
});
// app/models/card.js
export default DS.Model.extend({
name: DS.attr('string'),
set: DS.belongsTo('set'),
haves: DS.hasMany('have')
});
And a custom inflector rule:
inflector.irregular('have', 'haves');
When I load the json document with this structure though, I can't seem to do something like have.card.set.name in my template when I iterate this jsonapi document. I'm guessing my jsonapi structure is incorrect. What am I missing? I don't get any errors in my chrome console or in the ember server running. When I load Ember Inspector, I see the set model under Data.

Related

Fetching for each element within array in MongoDb

I have an 'users' collection. I store id's of users I follow in 'following' field.
{
"_id": {
"$oid": "5eab360253ec352e3cc791d6"
},
"email": "koray#gmail.com",
"password": "81dc9bdb52d04dc20036dbd8313ed055",
"following": ["5ea8879dfc286e1154a866cb", "5ea8879dfc286e1154a866c"],
"posts": [{
"head": "deneme header",
"body": "deneme body",
"is_private": false
}]
}
I want to get posts of users I follow as well as posts belogs to me but can't manage to pull it off.
You can use $lookup with custom pipeline and fetch documents from the same collection:
db.collection.aggregate([
{ $match: { _id: "5eab360253ec352e3cc791d6" } },
{
$lookup: {
from: "collection",
let: { following_users: "$following" },
pipeline: [
{ $match: { $expr: { $in: [ "$_id", "$$following_users" ] } } },
{ $project: { posts: 1 } }
],
as: "following_posts"
}
}
])
Mongo Playground

Json to Angular object

I have following JSON and I try to map it to Angular 7 object with no result:
[
{
"id": "123456",
"general": {
"number": "123",
"name": "my name 1",
"description": "My description with <li> html tags </li>"
},
"option1": {
"name": "option1 name"
},
"option2": {
"suboption2": {
"name": "suboption2 name"
}
}
},
{
"id": "789123",
"general": {
"number": "456",
"name": "my name 2",
"description": "My description with <li> html tags </li>"
},
"option1": {
"name": "option2 name"
},
"option2": {
"suboption2": {
"description": "My description with <li> html tags </li>"
}
}
}
]
I tried to create MyClass instance with fields with the same name as in the JSON file and cast that JSON file to this class but with no success.
I would create a mapper (service) that receives your DTOs (data transfer object, essentially your JSON response) as parameter and output your MyClass object.
In your map function (in your service), you would iterate over your array of DTOs and create a new instance of MyClass for each DTO and then return your array of MyClass
map(myClassDtos:MyClassDTO[]):MyClass[]{
return myClassDtos.map(dto=>{
return new MyClass(...);
});
}
First I would change your JSON structure for something like this, it's more structured:
[
{
"id": "123456",
"general": {
"number": "123",
"name": "my name 1",
"description": "My description with <li> html tags </li>"
},
"options": [
{
"name": "option1 name"
},
{
"name": "option2 name",
"suboptions": [
{
"name": "suboption1 name"
}
]
}
]
},
{
"id": "789123",
"general": {
"number": "456",
"name": "my name 2",
"description": "My description with <li> html tags </li>"
},
"options": [
{
"name": "option1 name"
},
{
"name": "option2 name",
"suboptions": [
{
"name": "suboption1 name"
},
{
"name": "suboption2 name"
}
]
},
{
"name": "option3 name",
"suboptions": [
{
"name": "suboption1 name"
},
{
"name": "suboption2 name"
}
]
}
]
}
]
After that write model interfaces to model all your JSON array items:
main-element.ts
import { General } from './general';
import { Options } from './options';
export interface Element {
id?: number;
general?: General;
options?: Options[];
}
generl.ts
export interface General {
number?: number;
name?: string;
description?: number;
}
import { Suboptions } from './suboptions';
options.ts
export interface Options {
name?: string;
suboptions?: Suboptions[];
}
suboptions.ts
export interface Suboptions {
name?: string;
}
And finally, where you want to map, simply do this:
import { Component } from '#angular/core';
import { Element } from './models/main-element';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private elementsList: Element[] = [];
constructor(){
}
mapJSON(){
this.elementsList = this.someJsonString; //Here you need to insert your json string data
console.log(this.elementsList);
}
}
As result you will get this, if you print in console the elementsList object that's defined on the last part of code.

Vue.js Filtered list Method

I am still learning Vue.js. At the moment I am trying to make a simple filtered list method that pulls the data from a json file in Vue. I think that I am having trouble figuring out the correct syntax.
I just cant seem to get it right. Any help is more than welcome :)
This is Vue file:
<template>
<section>
<ul>
<li v-for="product in rings" :key="product">
{{product.title}}
</li>
</ul>
</section>
</template>
<script>
import data from '#/assets/data.json';
export default {
data() {
return {
products: []
}
},
methods: {
computed: {
rings(){
return this.products.filter(product => product.type == 'Ring')
}
}
}
}
</script>
And this is the Json file:
{ "products": [
{
"title": "Ring 1",
"description": "something",
"type": "Ring",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Halskæde 1",
"description": "something",
"type": "Halskæde",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Armbånd 1",
"description": "something",
"type": "Armbånd",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Ørering 1",
"description": "something",
"type": "Ørering",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
}
]
}
You imported the data but never used anywhere inside the component:
import data from '#/assets/data.json';
// notice the data here is just a variable and it has nothing to do with the
// component's data property
export default {
data () {
return {
products: data.products // init products with imported data
}
},
Or with the destructuring syntax:
import { products } from '#/assets/data.json';
export default {
data () {
return {
products // init products with imported data
}
},

Using JSON API Serializer to create more complicated JSON

The examples here don't go nearly far enough in explaining how to produce a more complicated structure...
If I want to end up with something like:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": {
"title": "Watch"
},
"relationships": {
"mobile_screen_components": {
"data": [
{
"id": "1_1",
"type": "mobile_screen_components"
},
{
"id": "1_2",
"type": "mobile_screen_components"
},
...
]
}
}
},
"included": [
{
"id": "1_1",
"type": "mobile_screen_components",
"attributes": {
"title": "Featured Playlist",
"display_type": "shelf"
},
"relationships": {
"playlist": {
"data": {
"id": "938973798001",
"type": "playlists"
}
}
}
},
{
"id": "938973798001",
"type": "playlists",
"relationships": {
"videos": {
"data": [
{
"id": "5536725488001",
"type": "videos"
},
{
"id": "5535943875001",
"type": "videos"
}
]
}
}
},
{
"id": "5536725488001",
"type": "videos",
"attributes": {
"duration": 78321,
"live_stream": false,
"thumbnail": {
"width": 1280,
"url":
"http://xxx.jpg?pubId=694940094001",
"height": 720
},
"last_published_date": "2017-08-09T18:26:04.899Z",
"streams": [
{
"url":
"http://xxx.m3u8",
"mime_type": "MP4"
}
],
"last_modified_date": "2017-08-09T18:26:27.621Z",
"description": "xxx",
"fn__media_tags": [
"weather",
"personality"
],
"created_date": "2017-08-09T18:23:16.830Z",
"title": "NOAA predicts most active hurricane season since 2010",
"fn__tve_authentication_required": false
}
},
...,
]
}
what is the most simple data structure and serializer I can set up?
I get stumped after something like:
const mobile_screen_components = responses.map((currentValue, index) => {
id[`id_${index}`];
});
const dataSet = {
id: 1,
title: 'Watch',
mobile_screen_components,
};
const ScreenSerializer = new JSONAPISerializer('mobile_screens', {
attributes: ['title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
}
});
Which only gives me:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": { "title": "Watch" },
"relationships": {
"mobile-screen-components": {
"data": [
{ "type": "mobile_screen_components", "id": "1_0" },
{ "type": "mobile_screen_components", "id": "1_1" },
{ "type": "mobile_screen_components", "id": "1_2" },
{ "type": "mobile_screen_components", "id": "1_3" },
{ "type": "mobile_screen_components", "id": "1_4" },
{ "type": "mobile_screen_components", "id": "1_5" }
]
}
}
}
}
I have no idea how to get the "included" sibling to "data." etc.
So, the question is:
what is the most simple data structure and serializer I can set up?
Below is the simplest object that can be converted to JSON similar to JSON in the question using jsonapi-serializer:
let dataSet = {
id: '1',
title: 'Watch',
mobile_screen_components: [
{
id: '1_1',
title: 'Featured Playlists',
display_type: 'shelf',
playlists: {
id: 938973798001,
videos: [
{
id: 5536725488001,
duration: 78321,
live_stream: false
},
{
id: 5535943875001,
duration: 52621,
live_stream: true
}
]
}
}
]
};
To serialize this object to JSON API, I used the following code:
let json = new JSONAPISerializer('mobile_screen', {
attributes: ['id', 'title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
attributes: ['id', 'title', 'display_type', 'playlists'],
playlists: {
ref: 'id',
attributes: ['id', 'videos'],
videos: {
ref: 'id',
attributes: ['id', 'duration', 'live_stream']
}
}
}
}).serialize(dataSet);
console.log(JSON.stringify(json, null, 2));
The first parameter of JSONAPISerializer constructor is the resource type.
The second parameter is the serialization options.
Each level of the options equals to the level of the nested object in serialized object.
ref - if present, it's considered as a relationships.
attributes - an array of attributes to show.
Introduction
First of all we have to understand the JSON API document data structure
[0.1] Refering to the top level (object root keys) :
A document MUST contain at least one of the following top-level
members:
data: the document’s “primary data”
errors: an array of error objects
meta: a meta object that contains non-standard meta-information.
A document MAY contain any of these top-level members:
jsonapi: an object describing the server’s implementation
links: a links object related to the primary data.
included: an array of resource objects that are related to the primary data and/or each other (“included resources”).
[0.2]
The document’s “primary data” is a representation of the resource or
collection of resources targeted by a request.
Primary data MUST be either:
a single resource identifier object, or
null, for requests that target single resources
an array of resource identifier
objects, or an empty array ([]), for reqs. that target
collections
Example
The following primary data is a single resource object:
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
},
"relationships": {
// ... this article's relationships
}
}
}
In the (jsonapi-serializer) documentation : Available serialization option (opts argument)
So in order to add the included (top-level member) I performed the following test :
var JsonApiSerializer = require('jsonapi-serializer').Serializer;
const DATASET = {
id:23,title:'Lifestyle',slug:'lifestyle',
subcategories: [
{description:'Practices for becoming 31337.',id:1337,title:'Elite'},
{description:'Practices for health.',id:69,title:'Vitality'}
]
}
const TEMPLATE = {
topLevelLinks:{self:'http://example.com'},
dataLinks:{self:function(collection){return 'http://example.com/'+collection.id}},
attributes:['title','slug','subcategories'],
subcategories:{ref:'id',attributes:['id','title','description']}
}
let SERIALIZER = new JsonApiSerializer('pratices', DATASET, TEMPLATE)
console.log(SERIALIZER)
With the following output :
{ links: { self: 'http://example.com' },
included:
[ { type: 'subcategories', id: '1337', attributes: [Object] },
{ type: 'subcategories', id: '69', attributes: [Object] } ],
data:
{ type: 'pratices',
id: '23',
links: { self: 'http://example.com/23' },
attributes: { title: 'Lifestyle', slug: 'lifestyle' },
relationships: { subcategories: [Object] } } }
As you may observe, the included is correctly populated.
NOTE : If you need more help with your dataSet, edit your question with the original data.

normalizeResponse not recognizing link between nested relationships

The API endpoint I'm working with is returning data that has multiple nested relationships inside it, and I am using normalizeResponse() within DS.JSONAPISerializer to massage it into something that is fully JSON-API compliant.
The ember inspector shows that all data gets placed within its respective container correctly. The link between the top-level model and its hasMany child does work, but the link between the nested models does not work. I verify this by navigating within the inspector to the nested model's child model, clicking on it, and observing that its 'content' property is null.
First, take a look at how my models are set up:
// models/search.js
// i am able to browse from the search model to children with success
export default DS.Model.extend({
articles: DS.hasMany('article'),
});
// models/article.js
// i CANNOT browse from an article down to its digest in ember inspector
export default DS.Model.extend({
search: DS.belongsTo('search'),
type: DS.attr(),
created: DS.attr(),
updated: DS.attr(),
digest: DS.belongsTo('digest'),
});
// models/digest.js
export default DS.Model.extend({
title: DS.attr(),
desc: DS.attr(),
date: DS.attr(),
article: DS.belongsTo('article'),
});
Now, here's my modified JSON after my functions inside normalizeResponse complete. AFTER returning this data from normalizeResponse, the "digest" object under the parent "relationships" object disappears. Is there something wrong with my JSON? I've tried so many permutations of this with no success, and I am pretty sure this matches the JSON-API spec for Compound Documents.
{"data":{
"type":"searches",
"id":"17482738723",
"attributes":{
},
"relationships":{
"articles":{
"data":[
{
"type":"articles",
"id":"19988"
},
{
"type":"articles",
"id":"19989"
},
]
},
"digest":{
"data":[
{
"type":"digest",
"id":"19988_digest"
},
{
"type":"digest",
"id":"19989_digest"
},
]
}
}
},
"included":[
{
"id":"19988",
"type":"articles",
"attributes":{
"type": "internal",
"created":"2016-09-27T00:13:11.000Z",
"updated":"2016-09-27T00:13:11.000Z",
}
},
{
"id":"19988_digest",
"type":"digest",
"attributes":{
"title":null,
"desc":"four five six",
}
},
{
"id":"19989",
"type":"articles",
"attributes":{
"type": "internal",
"created":"2016-09-27T00:13:11.000Z",
"updated":"2016-09-27T00:13:11.000Z",
}
},
{
"id":"19989_digest",
"type":"digest",
"attributes":{
"title":"one two three",
"desc":null,
}
},
]
}
Your response indicates the following relationship model:
// models/search.js
export default DS.Model.extend({
articles: DS.hasMany('article'),
dignists: DS.hasMany('digest'),
});
// models/article.js
export default DS.Model.extend({
search: DS.belongsTo('search'),
});
// models/digest.js
export default DS.Model.extend({
search: DS.belongsTo('search'),
});
So you have to fix your response:
remove the digest relationship on the search
add a digest relationship to every article
So you will end with something like this:
{
"data":{
"type":"searches",
"id":"17482738723",
"attributes":{
},
"relationships":{
"articles":{
"data":[
{
"type":"articles",
"id":"19988"
},
{
"type":"articles",
"id":"19989"
},
]
}
}
},
"included":[
{
"id":"19988",
"type":"articles",
"attributes":{
"type": "internal",
"created":"2016-09-27T00:13:11.000Z",
"updated":"2016-09-27T00:13:11.000Z",
},
"relationships":{
"digest": {
"data": {
"type":"digest",
"id":"19988_digest"
}
}
}
},
{
"id":"19988_digest",
"type":"digest",
"attributes":{
"title":null,
"desc":"four five six",
},
"relationships":{
"digest":{
"data": {
"type":"digest",
"id":"19989_digest"
}
}
}
},
{
"id":"19989",
"type":"articles",
"attributes":{
"type": "internal",
"created":"2016-09-27T00:13:11.000Z",
"updated":"2016-09-27T00:13:11.000Z",
}
},
{
"id":"19989_digest",
"type":"digest",
"attributes":{
"title":"one two three",
"desc":null,
}
},
]
}
Know that you can also do it the other way around and specify the article on the digest. ember-data will automatically keep everything in sync. I personally prefer to specify both sides of the relationship for clarity.