jeudi 7 février 2019

Ember component POST to Express API gives error

When trying to do a post from a component in my ember app to my express api I am receiving

SyntaxError: Unexpected token V in JSON at position 0

When checking what response I'm receiving in the network inspector on chrome I see

ValidationError: body: Path `body` is required., title: Path `title` is required. undefined



The blogpost.title and .body both return the correct values but the blogpost gives me

adapterError: SyntaxError: Unexpected token V in JSON at position 0 at parse

EmberApp/App/Components/create-new-post/Component.js

export default Component.extend({
  blogpost: null,
  router: inject('-routing'),
  actions: {

    save: function (blogpost) {
      console.log(blogpost.title);
      console.log(blogpost.title);
      console.log(blogpost);

      blogpost.save()
          .then(
            (value) => {
              Ember.Logger.info(value);
              this.get('router').transitionTo('index')
            }
          )
          .catch(
            (err) => {
              Ember.Logger.info('failure to save');
              console.log(err);
            }
          )

    }
  }
});

EmberApp/App/Components/create-new-post/template.hbs

<form  >
  <p>
    
  </p>
  <p>
    
  </p>
  <p>
    <button class="btn btn-primary btn-block" type="submit" value="Save">Publish</button>
  </p>
</form>

EmberApp/App/routes/createpost.js

import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return this.store.createRecord('blogpost');
  }

});

EmberApp/App/templates/createpost.hbs

<div class="container">
  <div class="col-sm-12 pull-left">
    
  </div>
</div>

I have confirmed that the api route for post is working with postman so I'm not sure what the issue is with ember.




EmberJS hasMany doesn't fetch relationships

I have a problem with serializing my response which looks like:

{
"data": [
    {
        "id": 930,
        "uniqueId": "0d3a04cb-231c-4998-b4d3-9436a0a3138e",
        "name": "DRINKI",
        "lastEditDate": "2018-02-12T13:30:32",
        "lastEditDateUTC": "2018-02-12T12:30:32",
        "deleted": false,
        "discountable": true,
        "productCategoryPointOfSales": []
    },
    {
        "id": 921,
        "uniqueId": "5fbf423a-4932-47ca-b32f-5d3612dd73ee",
        "name": "BALOTYNKI SOLO",
        "lastEditDate": "2019-02-07T14:20:15",
        "lastEditDateUTC": "2019-02-07T13:20:15",
        "deleted": false,
        "label": "",
        "color": "#a0a5a9",
        "discountable": true,
        "productCategoryPointOfSales": [
            {
                "id": 142,
                "pointOfSaleUniqueId": "98e370f2-9d37-4473-9446-d82e442593fe",
                "directionId": 54,
                "directionUniqueId": "f0c986c0-ef85-4a46-86ea-cd997981fe8a",
                "kitchenUniqueId": "f0c986c0-ef85-4a46-86ea-cd997981fe8a",
                "inactive": false
            }
        ]
    }
],
"total": 0
}

And the error I get:

Encountered a relationship identifier without a type for the hasMany relationship 'productCategoryPointOfSales' on <category:5fbf423a-4932-47ca-b32f-5d3612dd73ee>, expected a json-api identifier with type 'product-category-point-of-sale' but found '{"id":"142","pointOfSaleUniqueId":"98e370f2-9d37-4473-9446-d82e442593fe","directionId":54,"directionUniqueId":"f0c986c0-ef85-4a46-86ea-cd997981fe8a","kitchenUniqueId":"f0c986c0-ef85-4a46-86ea-cd997981fe8a","inactive":false}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.

Models:

export default DS.Model.extend({
productCategoryPointOfSales: DS.hasMany('product-category-point-of-sale'),

uniqueId: DS.attr('string'),
name: DS.attr('string'),
label: DS.attr('string'),
color: DS.attr('string'),
discountable: DS.attr('boolean')
});

export default DS.Model.extend({
category: DS.belongsTo('category'),

pointOfSaleUniqueId: DS.attr('string'),
directionId: DS.attr('string'),
directionUniqueId: DS.attr('string'),
kitchenUniqueId: DS.attr('string'),
inactive: DS.attr('boolean')
});

And my serializer:

export default DS.RESTSerializer.extend(EmbeddedRecordMixin, {
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
payload = {
  category: payload.data,
};

return this._super(store, primaryModelClass, payload, id, requestType);
},
primaryKey: 'uniqueId',

attrs: {
  productCategoryPointOfSales: {embedded: 'always'}
}
});

I'm very new to EmberJS and have no idea how to solve this problem. It looks like root tags for my embedded object are missing. I followed some tutorials and tried with EmbeddedRecordMixin but it didn't help me. Could you please help me figuring this out?




How to keep data synchronized in ember using ember-apollo-client?

I have an app built using Ember and ember-apollo-client.

// templates/collaborators.hbs

// opens an ember-bootstrap modal
Create collaborator
// submit button in modal triggers "createCollaborator" in controller    


     


// routes/collaborators.js
import Route from '@ember/routing/route';
import { RouteQueryManager } from 'ember-apollo-client';
import query from '../gql/collaborators/queries/listing';

export default Route.extend(RouteQueryManager, {
    model() {
        return this.get('apollo').watchQuery({ query }); 
    }
});

// controllers/collaborator.js
export default Controller.extend({
  apollo: service(),

  actions: {
    createCollaborator() {
      let variables = { 
        firstName: this.firstName, 
        lastName: this.lastName, 
        hireDate: this.hireDate 
      }

      return this.get('apollo').mutate({ mutation, variables }, 'createCollaborator')
        .then(() => {
          this.set('firstName', '');
          this.set('lastName', '');
          this.set('hireDate', '');
      });
    }
  }
});

Currently, after creating a collaborator the data is stale and needs a browser refresh in order to update. I'd like the changes to be visible on the collaborators list right away.

From what I understood, in order to use GraphQL with Ember, I should use either Ember Data with ember-graphql-adapter OR just ember-apollo-client. I went on with apollo because of its better documentation.

I dont think I quite understood how to do that. Should I somehow use the store combined with watchQuery from apollo? Or is it something else?




How would i know which object has been updated on model.@each EmberJS

Im trying to change an object property in a list of object and would like to get that object right after it was changed.

My approach is to observe property changes on that list through model.@each.property_1

export default Ember.Controller.extend({

  onModelProperty1Change: function(){
    // How can i get that particular object after one of it 
    // property was changed inside here?
    //
    // do some database action to the object...

  }.observes('model.@each.property'),

});

I wonder if this is a right approach. Or should I go for change event on element instead? Either way I need to know it is possible to get that object inside observes helper.




How to reload route model from controller in Ember?

I am currently struggling with a task that I expected to be quite easy or common: I'd like to initiate a reload of the route model in the controller. As far as I can see, there is no easy way of doing this? Yes, I can access a RouteInfo object by the target property of the controller, but from there I see no way to refresh the model.

A little background about the task I try to solve: I have a route with a model that provides the last object from a collection that has a certain flag not set (e.g. "not indexed" in route /index-object). Now the user works on this object an triggers an action in the controller which set this flag (to "indexed"). So if I reload the route by navigating back and forth the next object is shown. But I want to trigger this reload directly in the action (without reloading the whole page, of course).

My question: Is this possible or is there another/right way of accomplishing what I try to achieve?




how to access ENV variables in index.html in ember.js

I am using ember.js, there is a requirement for us where we have to show a script tag(index.html file) only in production and not in development. Is there a way to achieve this?




mercredi 6 février 2019

How to fix "stretched view" of camera stream on some devices

I stream my "environment" camera to a video element on my DOM using navigator.mediaDevices.getUserMedia. The issue is that on my test-device (Samsung Tab) this video seems to be stretched. I'm not using any constraints other than facingMode: "environment", during my tests. I don't have this problem on my mobile device.

I already tried setting width and height constraints, this only works if I staticly set the values of my tablet cam, but my application has to support all devices. Note: my application is locked to portrait. built for android using cordova.

//code streaming

setup() {
    const constraints = {
      video: {
        facingMode: "environment",
        //tablet
        //width: {min:1280, ideal: width},
        //height: {min:720, ideal: height}
      },
      audio: false
    };

    navigator.mediaDevices.getUserMedia(constraints)
      .then(function (s) {
        video.srcObject = s;
        video.play();
      })
      .catch(function (err) {
        console.log("An error occured! " + err);
      });

    if(!this.get('streaming')) {
      video.addEventListener("canplay", function () {
        _this.set('videoReady', true);
        _this.processMedia();
      }, false);
    }
}
processMedia() {
    let _this = this;
    let video = document.getElementById('videoInput');
    if (!this.get('streaming')) {
      video.width = video.videoWidth;
      video.height = video.videoHeight;
      this.placeIndicators(video.width, video.height);
    }
   //process functionality//
}

Expected behaviour: to get a video element with my environment camera stream with a correct aspect ratio on all devices.

Actual behaviour: on my tablet my video stream is "stretched when the device is held landscape and "squeezed" when held portrait