lundi 29 juin 2020

Is there a way in Ember to get component/view/route based on div id like ember8013?

Is there a way in Ember to get component/view/route based on div id like ember8013? This is just for debugging.




Root path of AJAX request in Ember.js app

I want to use ajax to load a file on the server as part of an ember application. I was originally using

fetch('filename.json').then((response) => response.json()).then((jsonResponse) =>  {
    this.service.use(jsonResponse);
});

Placing the filename.json file in public/assets, it was able to locate and load the file. However trying the same with

let response = await this.ajax.request('filename.json');
this.service.use(response.json());

doesn't work and can't locate the file. It is searching https://localhost/web/system/filename.json and 404s. In an ember application I'm not sure where the file should be located for it to find it. With ember how should I be loading a local file not meant to be served publicly?




Add if condition on array length directly in Handlebars template

In my Handlebars template, I want to enable/disable a button based on "selectedRows" array length (i.e. enable if selectedRows > 0 and disable it otherwise i.e. on array length 0) I want to avoid introducing any extra instance variable in the component JS. Is it possible to do this directly in handlebars ?

i.e. something like below


enabled is boolean (true/.false)




samedi 27 juin 2020

Front end not loading ember

I am more of backend guy. I need to make some minor modification on ember based front end to display true/false based on my api.

I am doing it like this (in related component). But, front end doesn't load with the changes. Why?

    var url = HOST_API + this.get("parameter");
    $.get(url, function(data){
        var docs = data;
        view.set("flag", docs);
        });

If I remove my mods the page do load!!!




vendredi 26 juin 2020

Ember.js segmentation fault - node-sass

I recently moved some of my older projects to the new MacOS Catalina. I have an Ember.js project that is giving me a segmentation fault when trying to run the app. I found this github that seems like they’re experiencing something similar and they claim the cause of this issue is the npm module node-sass. I’ve tried rebuilding node-sass, I’ve tried removing node_modules completely and re-installing, nothing works. I’ve found this module ‘segfault-handler’ which prints out a stack trace that’s suppose to help me debug this issue but I’m not sure how to interpret the output. Here’s what that output looks like, any help is greatly appreciated.

Livereload server on http://localhost:49152
Serving on http://localhost:4200/
PID 11228 received SIGSEGV for address: 0x0
0   segfault-handler.node               0x0000000101f9b0c0 _ZL16segfault_handleriP9__siginfoPv + 304
1   libsystem_platform.dylib            0x00007fff715a75fd _sigtramp + 29
2   ???                                 0x0000000102b97d30 0x0 + 4340677936
3   binding.node                        0x000000010a0dca0a _ZN4Sass4Util11isPrintableEPNS_7RulesetE17Sass_Output_Style + 192
4   binding.node                        0x000000010a09ff07 _ZN4Sass6OutputclEPNS_7RulesetE + 73
5   binding.node                        0x000000010a090383 _ZN4Sass7InspectclEPNS_5BlockE + 149
6   binding.node                        0x000000010a0357d6 _ZN4Sass7Context6renderEPNS_5BlockE + 50
7   binding.node                        0x000000010a0d2a7d sass_compiler_execute + 107
8   binding.node                        0x000000010a0d2697 _Z20sass_compile_contextP12Sass_ContextPN4Sass7ContextE + 34
9   node                                0x0000000100a17768 worker + 90
10  libsystem_pthread.dylib             0x00007fff715b3109 _pthread_start + 148
11  libsystem_pthread.dylib             0x00007fff715aeb8b thread_start + 15
zsh: segmentation fault  sudo ember s


ember-cli: 2.10.0
node: 6.17.1
os: darwin x64



can't import the test helper addon in ember-cli-mirage

Facing the same issue - https://github.com/miragejs/ember-cli-mirage/issues/1445

Uncaught Error: Could not find module project-name/tests/helpers/push-mirage-into-store imported from project-name/mirage/factories/addon

Initially got this error and tried @makepanic instructions

After that

Uncaught Error: Could not find module @ember/test-helpers imported from project-name/mirage/helpers/push-mirage-into-store

can you pls help here to resolve this.




jeudi 25 juin 2020

On a masked mobile website, show the Vimeo embed play buttons

I've really have been struggling with this as of late. I have a website that I'm masking and when I view it on a mobile device (www.wedding.brianhollowayjr.com) the Vimeo play buttons show on the small video but not on the two bigger videos.

How can I have the buttons be shown on the two bigger videos?




Failed to find a valid digest in the 'integrity' attribute for resource on a deployed emberjs application

I have an emberjs application which has been deployed and in google chrome browser im getting the following errors for 2 of the .js files.

Failed to find a valid digest in the 'integrity' attribute for resource 'https://ift.tt/3eAYO1k' with computed SHA-256 integrity 'Sb4Xc/Oub27QW0MKlqK0sbq0Mm476jU7MgJaCzd/gKk='. The resource has been blocked

When i inspect the file i can see script tags for the two .js files in question. I'm not 100% sure how this integrity check works. You can see the integrity attribute below with the sha's.

<script src="/assets/vendor-0ada2c9fb4d3e07ad2f0c6a990945270.js" integrity="sha256-s3XY9h9v9IThygF6UkWRvWZsf7zeTqYJ1rLfDgg1bS0= sha512-k3lfqdeZw3OcsECfD3t99Hidh6IoRlFSoIu5nJk0FkLYHwx0q/rddirj4jh4J73dmLwKfG9mx0U5Zf6ZzRBsvA==" ></script>
<script src="/assets/g-web-56670cf0485cf52f54589091e2a25cc8.js" integrity="sha256-jNmWqO61OPijscQ5cHVSbB1Ms5wKX78ZACYdhrUo3X4= sha512-oiksgRFsqgHaCvXPvd3SAsUuX4zPeVClQBIgrOgIKNBMa3hPqCHknoFqDGRtSyfN4EdIkfk/x1zSqBqRvONAGQ==" ></script>

The emberjs application is built using a docker image, deployed to kubernetes and an aws elb running haproxy is handling the routing for this application such that when i navigate to staging.x.com it routes to the internal dns in kubernetes of this service (emberjs web app).

What's interesting to note;

  1. Running ember serve locally works and the applications loads fine.
  2. Building and running the docker image locally works and the applications loads fine.

The issue is only occurring on my deployed staging environment.




How do you mock/mimic a cookie that is set server side?

First post here on SO. I was scraping a website just fine when they made some change. It's my bank website. The 'program' I made just reads the history of my transactions and write it in a file, it runs once a week or so and let me track my accounting. I don't use the API because it lacks some of the informations that I need regarding the type of expenses.

Recently, they start using ember (well I think from the content of the request) to generate a cookie.

I manage to access the sign-in page using requests, but the next request needs a specific cookie deviceId that comes from nowhere, I mean it is not returned by any of the previous requests.

How do you retrieve a cookie that is set server-side when scraping?

Do I have to execute the JS or do a special request ? Do I have to reverse-engineer the cookie writing fron the snippet below ?

In one of the .js file i found this bit of code where the cookie is generated I think :

 define("website/services/device-manager", [
    "exports",
    "ua-parser-js",
    "uuid",
    "website/config/environment",
    "webiste/utils/shared-cookie-domain",
  ], function (e, t, n, a, r) {
    Object.defineProperty(e, "__esModule", { value: !0 }), (e.default = void 0);
    var i = Ember.Service.extend({
      cookies: Ember.inject.service(),
      init() {
        this._super(...arguments);
        var e = this.cookies.read("deviceId"),
          i = new t.default().getDevice().type;
        if (!e) {
          e = (0, n.v4)();
          var o = {
            secure: "production" === a.default.environment,
            domain: r.default,
            maxAge: 31622400,
          };
          this.cookies.write("deviceId", e, o);
        }
        this.set("id", e), this.set("currentDevice", i);
      },
      isMobile: Ember.computed.equal("currentDevice", "mobile"),
    });
    e.default = i;
  }),

Regards, Martin




mercredi 24 juin 2020

How to specify a local file request with fetch in Javascript

So my goal is to retrieve a JSON file to parse and assign to a variable. I started with my idea to use XMLHttpRequest, but then switched to using fetch. The problem is it's converting my relative file path to an HTTP request. With our setup (its part of an ember application) since that's not an actual page, it returns a 404 page and thus the response is all the HTML of that page.

fetch('../folder/myobject.json'){
  .then(function(response) {
      return response.json();
  }) ... so on

Is there a way to specify to not make a HTTP call with fetch or just another way to retrieve a file that is part of the app?




A sinon.spy function that is called does not state it has been called

I'm trying to mock an EmberJS adapter which has a function that carries out a POST request. My test looks like this:

 test('should post something', async function (assert) {
    let controller = this.owner.lookup('path/to/ach-deposit');
  
    controller.setProperties({
      ...,
      store: {
        adapterFor: () => {
          return {postAchDeposit: sinon.spy()}
        }
      }
    })
    await controller.actions.postAchDepositHandler.call(controller);
    assert.ok(controller.store.adapterFor.call().postAchDeposit.called);

  })

This fails. Stepping into the code of where postAchDeposit is called throws no errors. If I were to change sinon.spy() to sinon.stub().return("Hi") it would return Hi but for whatever reason when I try to see if it has been called, it returns false.

In the debugger after postAchDeposit has been called if I check there using this.get('store').adapterFor('funding/ach-deposit').postAchDeposit.called still it returns false.

What am I missing?




Trying to assign JS object from JSON file

I'm trying to read a JSON file (located on the same server) with Javascript in my ember app. I've seen the use of $.getJSON(), but this is all on the JS side, html isn't being touched here. I have the file in the public directory and simply want to assign the JSON object of the file to a variable. I'm not trying to display it to the user or request a file from the user's system.




mardi 23 juin 2020

Ember 3+ passing action from component to controller not working

We have recently shifted from ember 2+ to Ember 3.18.0 and i am struggling to call the controller function from a component. In previous version we were using sendAction to bubble the action but now as sendAction is depreciated and closures are being used i am not able to make it correctly.

Below is my code

Controller.hbs


Controller.js

@action
closePromptDialog(){
    this.set("showErrorModal",false);
}

Component.hbs

    
  <PaperDialog id="genericModal" class="flex-50" @fullscreen= @onClose= @origin=>
      <PaperDialogContent class="text-align-center">
          
      </PaperDialogContent>
      <PaperDialogContent>
        <h2></h2>
      </PaperDialogContent>

      <PaperDialogActions @class="layout-row">
        <span class="flex"></span>
        <PaperButton @primary=true @onClick= @raised=true>Ok</PaperButton>
      </PaperDialogActions>

  </PaperDialog>

Component.js

@action
hideModal(){
    this.args.onSave();
}

on this i am getting error as

Uncaught TypeError: method is not a function

Any help will be very much appreciated.

Ember version i am using is 3.18.0




lundi 22 juin 2020

Expression inside expression in handebars

Is there any way to put }} I have code like this }} where name and place are expressions.The problem is I cannot do this in js and i wanted this to be done in handlebars So is there any way to solve this problem?




How to integrate EmberJS incrementally into an rails web app?

we're working on our opensource password manager cryptopus https://github.com/puzzle/cryptopus. since our last release we integrated emberjs and are updating one component after another from classic rails webapp to emberjs. For now, we used locationType: "hash" to trigger emberjs parts.

one challenge we're facing now is to make sure the URLs are still the same after moving the UI components to emberjs. So we should get rid of "hash"-URLs for emberjs and still be able to call some legacy rails webapp URLs.

is there a way to ignore routes in emberjs and sending the request to the backend? any other ideas to make an incremental integration of emberjs possible? It would be OK if the SPA would be re-initialized after coming back from an class rails webapp URL.

some example routes:

/session/new -> send to rails backend
/teams -> handle by emberjs
/teams/42 -> handle by emberjs
/admin/users -> send to rails backend



vendredi 19 juin 2020

Clear button on calendar Emberjs

Adding a clear button for a calendar but I keep receiving "Nothing handled the action" Here is the .hbs file

<button class ="clearBtn" > Clear </button>

.js controller file

   actions: {
      clear(){
          this.set(true, '')
        }
      },

What am I missing for the action not to be called?




Clear button on calendar Emberjs

Adding a clear button for a calendar but I keep receiving "Nothing handled the action" Here is the .hbs file

<button class ="clearBtn" > Clear </button>

.js controller file

   actions: {
      clear(){
          this.set(true, '')
        }
      },

What am I missing for the action not to be called?




jeudi 18 juin 2020

Only return parameters if they are not empty

I have a method to generate filters like below:

_generateFilters() {
    const status = get(this, 'controller.status');
    const type = get(this, 'controller.type');
    const name = get(this, 'controller.name');

    const statusFilter = isEmpty(status) ? [] : generateFilter(status);
    const typeFilter = isEmpty(type) ? [] : generateFilter(type);
    const nameFilter = isEmpty(name) ? [] : generateFilter(name);

    return {
       statusFilter,
       typeFilter,
       nameFilter,
    };
}

For now it will return all parameters, but I want to return the parameters only with not empty value. like if status is empty, type and name is non empty, then return { tyepFilter, nameFilter }. Does someone know how to do it in this method? Thanks in advance.




mercredi 17 juin 2020

How to debug Ember addon with breakpoints in VS Code

Am trying to get breakpoints to work in VS Code with an Ember addon (version 3.18). Have tried launch.json as:

{
"version": "0.2.0",
"configurations": [
    {
        "type": "edge",
        "request": "launch",
        "name": "Launch Edge against localhost",
        "port": 9222,
        "runtimeArgs": [ "--remote-debugging-port=9222" ],
        "url": "http://localhost:4200",
        "sourceMapPathOverrides": {
            "dummy/*": "${workspaceFolder}/tests/dummy/app/*",
            "test-addon/*": "${workspaceFolder}/addon/*",
        }
    }
]}

It works fine for setting breakpoints in files in the dummy test app. But when setting a breakpoint in files within the addon folder, VSCode says "Breakpoint set but not yet bound". How can this be fixed? I assume the 2nd sourcemap path override is wrong?




Can no longer login when upgrading from Ember 2.x -> 3.x using ember-simple-auth

As the title reads, I am having trouble logging into my application after upgrading from Ember 2.x to 3.x (specifically in this case, 2.18.2 to 3.12.1). I tried following this guide : https://github.com/simplabs/ember-simple-auth/blob/master/guides/upgrade-to-v3.md

But it didn't really make sense to me. I tried setting the authenticationRoute, routeAfterAuthentication, and routeIfAlreadyAuthenticated values respectively to the particular routes that my application uses, and as I step through code execution with breakpoints I see that the values are being correctly set, but no dice. None of the other steps there applied to my particular case.

Here are the changes I've made based on the guide --

protected.js (all I did here was add the authenticationRoute definition) :

import { inject as service } from '@ember/service';
import { isNone } from '@ember/utils';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import AutoScrollMixin from 'erm/mixins/auto-scroll';

export default Route.extend(AuthenticatedRouteMixin, AutoScrollMixin, {
  authenticationRoute: 'login',
  session: service(),
  userIdle: service(),
  currentUser: service(),

  model(/*params, transition*/){
    var self = this;

    self.get('userIdle').on('idleChanged', (isIdle) => {
      if (isIdle) {
        self.get('session').invalidate();
        self.replaceWith('login');
      }
    });

    if( this.get('session.isAuthenticated') ) {
      var user = self.get('currentUser.user');
      if( user && user.get('temp_password') ) {
        this.transitionTo('change-password');
      }
    } else {
      if( isNone(this.get('session.isAuthenticated')) ||
          this.get('session.isAuthenticated') !== true ) {
        self.replaceWith('login');
      }
    }
  },
});

application.js (just added the routeAfterAuthentication entry) :

import { inject as service } from '@ember/service';
import { isNone } from '@ember/utils';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Route.extend(ApplicationRouteMixin, {
  routeAfterAuthentication: 'risks.index',
  currentUser: service(),
  session:  service(),
  beforeModel() {
    return this._loadCurrentUser();
  },

  sessionAuthenticated() {
    this._super(...arguments);
    this._loadCurrentUser();
  },

  _loadCurrentUser() {
    var currUser = this.currentUser;
    return isNone(currUser.get('user')) ? currUser.load() : currUser.reload();
  }
});

login.js (all I did here was add the routeIfAlreadyAuthenticated entry) :

import UnauthenticatedRouteMixin  from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Route.extend(UnauthenticatedRouteMixin, {
  routeIfAlreadyAuthenticated: 'risks.index'
});



Use of setupcontroller in ember.js route?

Do routes actually need to use setupcontroller() to load model to templete? What is the use of setupcontroller?




How to hide a section in .hbs and .js while taking an ember production build

Our Ember application is developed in 2.8 version and we follow POD structure.

We are generating two different builds as below

1) For our dev server : No change in code,just do build

2) For our test server: Delete a section in HBS and also remove a route from router.js then do build

And we take build using "npm run-scripts build" which is configured in our package.json as below

"scripts": {
    "build": "ember build",
    "start": "ember server",
    "test" : "ember test"
  },

I would like to know in ember 2.8v can i have a condition written to remove the section based on build.

Like if i give npm run-scripts buildDev it will do the regular build

and if i give npm run-scripts buildTest it will do sections removals and give a build

but in package.json both will be configured like

"scripts": {
    "build"    : "ember build",
    "buildDev" : "ember build --environment=production",
    "buildTest": "ember build --environment=production",
    "start": "ember server",
    "test" : "ember test"
  },



mardi 16 juin 2020

Can I share state between two EmberJS apps

I'm trying to see if there is a possibility to share state (with ember-data) or any addon that can be added to it - if there is a possibility to share state between two (or more) separated EmberJS web applications? I have found a way to share the state of course only internally within the same web app but not between different web apps.




Ember promise aware headers in Adapter

Looking for a way to set header in Ember Adapter layer with the value returned from an async call.

Trying to set the idToken returend from Amplify's Auth.currentSession(), which is a promise function which internally handles refreshing the token on expiration.

.

.

I see that we can't make a promise aware computed property too for headers.

Also I am not looking for a solution using ember-simple-auth / ember-cognito or any other addons, I need to achieve this just with plain amplify library and Ember adapters header 😟.




lundi 15 juin 2020

FullCalendar Ember Support

Is there an Ember version of FullCalendar that uses the latest version of FullCalendar? I do not see Ember listed as a third party tool on there web site. https://fullcalendar.io/docs

I only see TypeScript, React, Vue and Angular listed.




samedi 13 juin 2020

How to use handlebars for autocomplete search bar with javascript?

Currently I am working to make a autocomplete search bar for ghost cms and I have to use handlebars for it. I have done it using html which is wrong so what can I do to implement handlebars template. this is the html part

<div class="autocomplete" style="width:300px;">
   <input id="myInput" type="text" name="myCountry" placeholder="Search">
</div>

Javascript part is:-

<script>
function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      this.parentNode.appendChild(a);
      for (i = 0; i < arr.length; i++) {
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          b = document.createElement("DIV");
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          b.addEventListener("click", function(e) {
              inp.value = this.getElementsByTagName("input")[0].value;
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        currentFocus++;
        addActive(x);
      } else if (e.keyCode == 38) { 
        currentFocus--;
        addActive(x);
      } else if (e.keyCode == 13) {
        e.preventDefault();
        if (currentFocus > -1) {
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    if (!x) return false;
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  }
 document.addEventListener("click", function (e) {
      closeAllLists(e.target);
  });
}

var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","];

autocomplete(document.getElementById("myInput"), countries);
</script>

So, what my problem is I am doing this in a .hbs file I don't know how to use handlebars for the search functionality. If I try to create a

 
  

It doesn't work how should I link my handlebars part with my javascript part. I have people doing it with jquery but it just went over my head. So can anyone help please. PS:- If you are unable to understand I share more details also.




jeudi 11 juin 2020

Database without server for Ember production app

I am developing an application in ember. I would host it locally in a machine using mangoose webserver after production. Now I need to store data for the application (json is most welcome) even in file database. I need a serverless local database without internet. I should not install node.js or any other software for database because the machine in which is going to be hosted has not given any provision for installation. The database or file must be directly acccessible from js. I have viewed about sqlite3 but i found no useful js library to connect without node.js. How could I achieve it. Guide me please.

Thanks in advance




import of geolib doesn't work in Ember-cli

Trying to import Geolib from npm by:

npm install geolib --save

which generates in package.json

  "dependencies": {
    "bower": "^1.8.8",
    "ember-cli": "~2.18.2",
    "ember-cli-less": "3.0.1",
    "geolib": "^3.3.1"
  },

then in my test.js component:

import { getDistance } from 'geolib';

But ( yes, there is but ) when i access a page, it generates error:

loader.js:228 Uncaught Error: Could not find module `geolib` imported from `wash-app-dashboard/components/test`
    at missingModule (loader.js:228)
    at findModule (loader.js:239)
    at Module.findDeps (loader.js:173)
    at findModule (loader.js:243)
    at requireModule (loader.js:26)
    at Class._extractDefaultExport (index.js:389)
    at Class.resolveOther (index.js:109)
    at Class.superWrapper [as resolveOther] (ember-utils.js:418)
    at Class.resolve (resolver.js:133)
    at _resolve (container.js:886)

Something wrong with my settings, or what ? Cant find any solution but comment out the code.




mercredi 10 juin 2020

Convert time string ("hours:minute") to date object

Here is time string with hours and minutes (e.g. "03:37"). I want to update date object that time and create date object in ember JS. Help me with this. The time goes by 24 hours.




mardi 9 juin 2020

Using two input fields to create Date object with computer property (getter and setter) Ember JS

So I am using two inputs fields and .

One returns date in 10 digits and one returns time in this format, e.g.) "09:23".

I would like to use computed properties with custom getters/setters to create Date() object.

activeFromDate: computed('model.active_from', {
  get() {
    // If model.active_from currently exists and is a JavaScript Date object, extract the date number
    // from it to pass to the `date-picker` component
    if (this.get('model.active_from')) {
      return doSomethingToGetDateNumberFromTimestamp();
    }
  },
  set(key, value) {
    // When the `date-picker` component updates the value, create a new Date object in the alert model
    this.set('model.active_from', doSomethingToGetTimestampFromDateString());
    return value;
  }
}),

activeFromTime...,

modal.active_from is where date&time needs to be saved on.




Ember sideload data not linked

I'm new to using Ember and was assigned to an ongoing project and need to resolve the following:

export default class OrderModel extends Model.extend(LoadableModel) {
  @attr('string') status;
  @attr('number') total;
  @hasMany('order-item', { async: true }) orderItems;
}

export default class OrderItemModel extends Model.extend(LoadableModel) {
  @attr('number', { defaultValue: 0 }) discount;
  @attr('number', { defaultValue: 0 }) price;
  @hasMany('item-fix', { async: false }) fixes;
}

export default class ItemFixModel extends Model.extend(LoadableModel) {
  @attr('number', { defaultValue: 0 }) price;
}

and when I do let order = await this.store.findRecord('order', order_id, { reload: true }); the json response is:

data: {
  type: "orders",
  id: "1584",
  attributes: {
    status: "in_progress",
    total: 1300
  },
  relationships: {
    order-items: {
      data: [
        {
          type: "order-items",
          id: "1801
        }
      ]
    }
  }
},
included: [
  {
    type: "order-items"
    id: "1801",
    attributes: {
      discount: 0,
      price: 1200
    },
    relationships: {
      item-fixes: {
        data: [
          {
            type: "item-fixes",
            id: "335"
          }
        ]
     }
  },
  {
    type: "item-fixes",
    id: "335",
    attributes: {
      price: 100
    }
  }
]

but when I inspect the orderItem inside the order variable, the itemFixes are empty, but the is in the sideload of the response.

¿How can I link this nested relationship?

Also, here is the serializer.

export default DS.JSONAPISerializer.extend({
  serialize(snapshot) {
    let serialized = this._super(...arguments);
    let { adapterOptions } = snapshot;

    if (adapterOptions && adapterOptions.addPromotionCode) {
      return { code: serialized.data.attributes.code }
    }

    serialized.included = A([]);
    snapshot.eachRelationship((key, relationship) => {
      if (relationship.kind === 'belongsTo') {
        if (!isBlank(snapshot.belongsTo(key))) {
          let node = snapshot.belongsTo(key).record.serialize({ includeId: true }).data;
          delete node.relationships;
          serialized.included.pushObject(node);
        }
      } else if (relationship.kind === 'hasMany') {
        if (!isBlank(snapshot.hasMany(key))) {
          snapshot.hasMany(key).forEach(ele => {
            let node = ele.record.serialize({ includeId: true }).data;
            delete node.relationships;
            serialized.included.pushObject(node);
          });
        }
      }
    });

    return serialized;
  }
});



lundi 8 juin 2020

How to load locale to moment in ember js?

config/environment.js

moment: {
        allowEmpty: true,
        includeTimezone: 'all',
        includeLocales: true
      }

component.js

import Ember from 'ember';
import moment from 'moment';
...
months: computed(function() {
    return moment.monthsShort();
  })

Here

moment.locale('en')
>>"en"

works as expected...
But When we change locale its not working..

moment.locale('en')
>>"en"

I think the locales are not loaded ....How to load them?
Dependencies

"moment": "2.18.1"
"ember-moment" : "7.4.1"



samedi 6 juin 2020

rails renders index.html before building ember app

I'm trying to build a web app with rails (backend) and ember (frontend) thanks to the ember-cli-rails gem and it works but I still have a problem.

When I launch my server with "rails s" and that I go to localhost:3000, I have an error page with "ActionView::Template::Error (:frontend has failed to build: - Building)". I think this is because rails renders the index page before waiting the end of ember build (the ember build is only launched the first time I request a page to be rendered). Because after few seconds when I refresh the page, the ember welcome page is well rendered.

enter image description here

Is it a normal behavior ? If not, do you have an idea to solve the problem ?

Thank you !




vendredi 5 juin 2020

Emberjs - use @model hook data in component

I have a route that grabs posts data from mirage like so:

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

export default class PostsRoute extends Route {
  async model() {
    return this.store.findAll('post');
  }
}

I can then do something like this


   ..do stuff

but let's say I want to rename @model to foo and use it in some other component - how can I do that?




How to pre load ember engines?

Am using ember-engines in my project, After user lands in host ember application, I want my other ember engines to preload (say after 10 seconds), so that when user navigates to other tabs, there wont be any lag in UI.. i dont want to disable lazyLoading of my ember engines since that will increase the size of vendor js and css of host app during initial load.. Any reference for this is appreciated (I was not able to find any example or reference for this).




How to use createRecord in ember data?

I have a foo model that has a relationship with bar. foo model has no relationship with baz. However, when creating a foo record a string of id's are needed to pass. I am setting the baz but it always returns null in my request payload.

/component.js

saveFoo() {
  let foo = this.store.createRecord('foo');
  let bar = this.get('bar');

  foo.set('name', "some value");
  foo.set('bar', bar);
  foo.set('baz', "1,2,3");

  return foo.save();
}

Request payload is like this when the return foo.save() is triggered

data: {
  attributes: {
    name: "some value"
  }
  relationships: {
    bar: {data: {id: "5898"}}
    baz: {data: {id: null}}
  }
}

But the request payload should be like this. (This is how api returns 200 if my request payload is like below)

data: {
  attributes: {
    name: "some value"
  }
  relationships: {
    bar: {data: {id: "5898"}}
    baz: {data: {id: "1,2,3"}}
  }
}



mercredi 3 juin 2020

Reuse types definitions from an in-repo addon via ember-cli-typescript

I am using ember-cli-typescript in both the main app and the in-repo addon that are located in one yarn workspace. In the addon I declared types for ember-concurrency which I also need in the main app. However, I don't want to copy-paste the file, I'd like to reuse it instead.

If no actions are performed the build of the main app fails yielding complaints on unknown module 'ember-concurrency' pointing on the files from the addon.

Is there a simple solution for this problem?