lundi 30 novembre 2020

Map update periodically in forest admin using leaflet

I am using map to show riders while driving. Map is showing location as a marker on Map. But my map is not updating after data updated in mongodb. I am using forestadmin and node js. In forestadmin, I am using smartview where I will have to use ember.js. I am showing leaflet OpenStreetMap map.

here is the javascript I am using:

export default Component.extend(SmartViewMixin, {
  store: service(),

  tagName: "",

  map: null,
  loaded: false,

  init(...args) {
    this._super(...args);

    this.loadPlugin();
  },

  didInsertElement() {
    this.displayMap();
  },

  onRecordsChange: observer("records", function () {
    this.displayMap();
  }),

  loadPlugin() {
    scheduleOnce("afterRender", this, () => {
      $.getScript(
        "//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js",
        () => {
          $.getScript(
            "//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js",
            () => {
              this.set("loaded", true);
              this.displayMap();
            }
          );
        }
      );

      const headElement = document.getElementsByTagName("head")[0];
      const cssLeafletLink = document.createElement("link");
      cssLeafletLink.type = "text/css";
      cssLeafletLink.rel = "stylesheet";
      cssLeafletLink.href =
        "//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css";

      headElement.appendChild(cssLeafletLink);

      const cssDrawLink = document.createElement("link");
      cssDrawLink.type = "text/css";
      cssDrawLink.rel = "stylesheet";
      cssDrawLink.href =
        "//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.css";

      headElement.appendChild(cssDrawLink);
    });
  },

  displayMap() {
    if (!this.loaded) {
      return;
    }

    if (this.map) {
      this.map.off();
      this.map.remove();
      this.map = null;
    }

    const markers_arr = [];

    this.records.forEach(function (record) {
      markers_arr.push([
        record.get("forest-latitude"),
        record.get("forest-longitude"),
        record.get("id"),
        record.get("forest-userId.forest-email"),
       
        record.get("forest-userId.forest-bikeModel"),
        record.get("forest-userId.forest-bikeRegNo"),
        record.get("forest-userId.forest-phone"),
      ]);
    });
    var map = L.map("map").setView(
      new L.LatLng(markers_arr[0][0], markers_arr[0][1]),
      7
    );

    const osmUrl =
      "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png";
    const osmAttrib =
      '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';
    const osm = new L.TileLayer(osmUrl, { attribution: osmAttrib });
    map.addLayer(osm);

    var markers = [];

    markers_arr.forEach(function (mark) {
      var foo = "ID: "+mark[2] + "\n <br>Email: " + mark[3]+ "\n <br>Phone: " + mark[6]+ "\n <br>Bike Model: " + mark[4] + "\n <br>Bike #: " + mark[5]
      var marker1 = L.marker([mark[0], mark[1]] )
        .addTo(map)
        .bindPopup(foo);
      markers.push(marker1);

      marker1.on("mouseover", function (ev) {
        marker1.openPopup();
      });
    });

    function markerFunction(id) {
      for (var i in markers) {
        var markerID = markers[i].options.title;
        if (markerID == id) {
          markers[i].openPopup();
        }
      }
    }
  },
});

and here is the HTML:

<style>
  #map {
    width: 100%;
    height: 100%;
    z-index: 4;
  }  
</style>
<div id="map"></div>

I also use fetchRecord in HTML but it not updating latest data.

<button >
  Refresh data
</button>

Help me 🙏🏻🙏🏻🙏🏻




vendredi 27 novembre 2020

How to use ember-2-legacy?

We have the post in the documentation for Ember 2.16 about addition deprecation ember-2-legacy:

Ember 2 Legacy until: 3.4 id: ember-2-legacy Ember provides ember-2-legacy which is an addon to help app with deprecations during the transition from the 2.x series to 3.x.

https://deprecations.emberjs.com/v2.x/#toc_ember-2-legacy

We also have some configuration in README:

In ember-cli-build.js you can specify a config for ember-2-legacy

https://github.com/emberjs/ember-2-legacy#what-deprecations-are-covered

So, as I understand, if we specify some flag with false, like this:

new EmberApp(defaults, {
  'ember-2-legacy': {
    'enumerable-contains': false

then this particular feature will be off in ember app.

Should my App raise some error or notify me by console warning? In general, I have a case of all flags false and all tests passed, so my question is: is it mean that my application has no those deprecations usage cases?

Shall I keep ember-2-legacy with config in ember-cli-build.js til Ember upgrade 3.0

or

case with no errors on CI build means that: my App already has no deprecation and I can remove this addon at all?




jeudi 26 novembre 2020

Ember required component arguments

How can I require a parameter in an ember component.

E.g.:

class MyComponent extends Component {
  get my_value() {
    return this.args.my_argument + 1
  }
}

I want the component to throw an error when the component is instantiated and not when the function is called.

The only way I can think of is like this:

class MyComponent extends Component {
  constructor(owner, args) {
    super(owner, args)
    assert(!!args.my_argument, "MyComponent requires my_argument")
  }
  ...
}

This however seems a bit tedious and does not look right :/

EDIT:

It would be even better if I could specify the type of the argument.




mercredi 25 novembre 2020

EmberJS: Injecting owner to native class from component

The thing i'm trying to do, is to inject owner to my JS native class in Ember(3.15.0). It looks something like this:

  component.ts

  export default class ClassOne extends Component {
    constructor() {
      super(...arguments);
      const myClass = new ClassTwo();
      ...
    }
  }

  ClassTwo.ts

  export default class ClassTwo {
    @service() someService: ServiceType;
    ...
  }
  

Because of that, on someService, i'm getting expectable Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container

I've seen similar questions that were solved by using getOwner(this).ownerInjection() but those were all based on Class.create() that was extended by Ember.Object.

Is there any way to do that?

Thanks in advance for any help.




lundi 23 novembre 2020

Timezone sensitive date comparisons in Javascript

I'm determining the difference between two calendar dates in Javascript in an Ember app. I'm currently using date-fns's differenceInCalendarDays.

Now that mostly provides the desired results, the only issue is that I need to handle calculating the difference between 2 dates that is sensitive to a timezone (not the local timezone to the browser).

As far as I'm aware JS Dates are tracked as UTC, with no timezone stored on the date object itself. Any timezone localization I've done in JS has been outputting a string. Is there a good library or way to accomplish differenceInCalendarDays while taking into account the timezone?

const daysAgo = this.intl.formatRelative(-differenceInCalendarDays(new Date(), someOtherDay), {
    unit: 'day', 
    numeric: 'auto', 
    timeZone: 'this.intl.timeZone
});

This is a small sample of what I'm doing, obviously differenceInCalendarDays will resolve to a number which won't take into account any timeZone. The docs for differenceInDays is timezone sensitive to the browser's local time (which is not helpful here), but differenceInCalendarDays makes no such mention. Any help would be greatly appreciated!




Ember JS 3.20 app with SailsJS 0.12.x backend and websocket connection

I am using sails 0.12.14 version back-end with EmberJS 3.20 front-end. I am currently dealing with a websocket connection problem in production.

Using "sails.io.js": "^1.1.0", "socket.io-client": "^1.4.5" for sails compatibility in Ember ( same goes for sails back-end ).

Both servers are on AWS. When i use app in development (localhost), everything is OK, socket is connected, messages are pushed from back-end to fron-end via socket. But when i deploy Ember app to production, i get this:

WebSocket connection to 'ws://{my-page-domain}/socket.io/?__sails_io_sdk_version=1.1.0&__sails_io_sdk_platform=node&__sails_io_sdk_language=javascript&EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400

Where is this comming from and why can't ember app access sails.io ? Back-end is running just fine.

Any idea what is happening ?

Any insight whatsoever is appreciated.




dimanche 22 novembre 2020

How to click on the ember.js enabled button using Selenium and Python

I have been trying to make this clickable and I just cannot understand what I am doing wrong. I am also trying to induce webdriverwait, so that it is clicked when it appears.

This is my code so far:

def order(k):
    driver = webdriver.Chrome(os.getcwd()+"\\webdriver\\chromedriver.exe") 
    driver.get("website.com/login-to-checkout")
    driver.find_element_by_id('i0116').send_keys(k["email"])
    driver.find_element_by_id('i0118').send_keys(k["password"])
    driver.find_element_by_id('idSIButton9').click()
    delay()
    #sign in button
    driver.find_element_by_id('idSIButton9').click()
    #Button below I cant get to be clicked
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver, 7)
        wait.until(presence_of_element_located((By.CSS_SELECTOR, "#ember1053")))
        driver.find_element(By.id, "ember1053").click()

this is the source code for the button that I am trying to make clickable:

<div id="ember1037" class="btn-group m-b-lg m-t-lg order-call-to-action ember-view"><!---->        <!--biBehavior 80 means place order Place Order-->

<button aria-live="polite" type="button" tabindex="0" data-m="{&quot;aN&quot;:&quot;shoppingCart&quot;,&quot;cN&quot;:&quot;PlaceOrder&quot;,&quot;bhvr&quot;:80}" id="ember1053" class="btn theme-default btn-primary cli-purchase ember-view"><!---->            Place order

</button></div>



How trigger a function inside component whenever arguments change in Emnber octane

so i have a parent in controller like this

import Controller from '@ember/controller';

export default class IndexController extends Controller {
@service firebaseApp;
@service fastboot;
@tracked user =false;

async init(){
 super.init(...arguments);
 if (!this.fastboot.isFastBoot){
  const auth =  await this.firebaseApp.auth();
  auth.onAuthStateChanged((user)=>{
     if(user){
       this.user = true
     } else {
       this.user = false
     }
      })
     }
   }

then call a component loadData like this <LoadData @user=/>

the question is how to execute a function inside component loadData when @user change?




vendredi 20 novembre 2020

is it possible to identify a value being changed by server in ember?

is there any attribute in the ember model which indicates the value being altered by the server?. I don't want to observe the value in that model as it will get triggered when the user changes also. so I was wondering if there is any attribute like isSaving, hasDirtyAttributes like that to indicate the value is changed by the server for a short moment of time like how isLoading and isLoaded in ember does.




jeudi 19 novembre 2020

ember hasDirtyAttributes do not work with object (json)

I have a model:

export default Model.extend({
  title: attr('string'),
  attributes: attr('jsonb')
});

Where attributes is a custom json filed stored as jsonb in Postgres.

let say:

{
"name":"Bob",
"city":""
}

So I can easily manipulate attributes using template
<form.element .. @property="attributes.city"/> or model.set('attributes.city','city name')

Problem: hasDirtyAttributes do not changing because technically we have old object. But when I try to copy object let say JSON.parse(JSON.stringify(this.get('attributes')) hasDirtyAttributes works as expected

So how to write some Mixin for a Model or other workaround which on the change of any attribute property will mark hasDirtyAttributes as true. I will update whole object so doesn't matter which property actually was changed.

Same problem: https://discuss.emberjs.com/t/hasdirtyattributes-do-not-work-with-nested-attributes-json-api/15592

existing solution doesn't work for me at all:

  • ember-dirtier
  • ember-data-relationship-tracker
  • ember-data-model-fragments (a lot of changes under the hood and broke my app)



Error: 'ReferenceError: pauseTest is not defined' in integration tests with moduleForComponent syntax

The pauseTest() function from ember-qunit does not work as expected in Integration tests with the old syntax

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('my-component, 'Integration | Component | MyComponent', {
  integration: true
});

test('it renders', function(assert) {
  return pauseTest();
  this.render(hbs`/>`);
  ...
}

Failed:

Died on test #1     at Module.callback (http://localhost:4200/assets/tests.js:118959:24)
at Module.exports (http://localhost:4200/assets/vendor.js:111:32)
at requireModule (http://localhost:4200/assets/vendor.js:32:18)
at EmberExamQUnitTestLoader.<anonymous> (http://localhost:4200/assets/test-support.js:29031:11)
  at EmberExamQUnitTestLoader.require (http://localhost:4200/assets/test-support.js:29021:27)
at http://localhost:4200/assets/test-support.js:29545:90
  at Array.forEach (<anonymous>): pauseTest is not defined@ 698 ms
  Source:
  ReferenceError: pauseTest is not defined
  at Object.<anonymous> (http://localhost:4200/assets/tests.js:118960:5)
    at runTest (http://localhost:4200/assets/test-support.js:20889:30)
    at Test.run (http://localhost:4200/assets/test-support.js:20875:6)
    at http://localhost:4200/assets/test-support.js:21096:12
    at advanceTaskQueue (http://localhost:4200/assets/test-support.js:20488:6)
    at Object.advance (http://localhost:4200/assets/test-support.js:20469:4)
    at begin (http://localhost:4200/assets/test-support.js:22241:20)
    at http://localhost:4200/assets/test-support.js:21483:6

It's working fine in Acceptance tests, because of:

// ./tests/helpers/start-app.js
export default function startApp(attrs) {
  ...
    application.injectTestHelpers();
  ...
}

How to make it works in Integration tests?

Note: In modern syntax, it's working fine too:

import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | MyComponent', function(hooks) {
  test('it renders', async function(assert) {
    return this.pauseTest();
    await render(hbs`/>`);
  });
}



Ember The Resource from 'path' was blocked due to MIME type error with blank screen

I'm working on an Ember application with a .NET backend. In building the ember app, it complies into the proper directory. My directory structure looks like below:

myProjectRoot
   |
   |-> NETProject
   |       |
   |        -> Compiled-Ember 
   |
    -> Ember project

I currently have it running as an IIS application pointing to NETProject, though if I run via ember serve I get the same results. All the IIS config is proper and works. The issue is trying to load the page I get the following errors, one for each vender.css, vendor.js, projectName.js, and projectName.css:

The resource from “http://localhost/404.aspx?404origin=%2fcompiled-ember%2fassets%2fprojectName.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)

The title and favicon load, but the rest of the page is blank. It should be noted that the app will redirect to a 404 page upon not finding the requested URL.

Now the resources do exist where they are supposed to, the project builds without issue and all compiled files exist in compiled-ember. Now I have seen that this is a common issue with the path, I have messed with the path in the compiled index.html file (which is where it sources from as changing the path here changes the error to match). I've gotten no other results, than the error above. Here is the index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ProjectName</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" type="image/x-icon" href="https://hostedimagelocation.com">
    <base href="/" />

    
<meta name="projectName/config/environment" />
    <link integrity="" rel="stylesheet" href="/compiled-ember/assets/projectName.css">

    
</head>
<body>


<script src="/compiled-ember/assets/vendor.js"></script>
<script src="/compiled-ember/assets/projectName.js"></script>


</body>
</html>

The index.html file is located directly in compiled-ember. I have tried switching the paths to be like assets/vendor.js and others to no avail. Any help to solving this error would be very helpful. Thank you




After bump ember-data from 2.13 to 2.14 the request payload not contain hasMany relations when the relation model had empty relation

with ActiveModelSerializer usage after the ember-data upgrade, the values of has_many case on the request payload had changed when the model has no records by relation, for example:

// app/models/user.js
import Model from 'ember-data/model';
import { hasMany } from 'ember-data/relationships';

export default Model.extend(Validations, {
  posts: hasMany('post'),
...
}
// app/models/post.js
import Model from 'ember-data/model';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend(Validations, {
  user: belongsTo('user'),
...
}

so, if User has no posts, previously was sent [] into BE, but after ember-data bump to 2.14.11 no key-values sent, for example: (request payload)

Before:

user: { id: 1, post_ids: [] }

After:

user: { id: 1 }

Note:

"active-model-adapter": "2.2.0"
"ember-data": "2.14.11"



Is it necessary to migrate from ember-data/active-model-adapter to DS.JSONAPISerializer for ember 3?

Documentation for DS.ActiveModelAdapter is exists only for 1.13 (for 2 - 404: https://api.emberjs.com/ember-data/1.13/classes/DS.ActiveModelAdapter So, it looks like it's moved out from DS: https://github.com/ember-data/active-model-adapter

We have ember-data 2.13.2 and it's working fine with active-model-adapter But we got some issues with the bump to ember-data 2.14.11 with nested behavior

The big issue here is to rewrite the backend part. We also may use RESTAdapter: https://www.emberscreencasts.com/posts/113-restadapter-vs-jsonapiadapter-vs-activemodeladapter but it looks like ember way is JSONAPIAdapter way: https://api.emberjs.com/ember-data/release/classes/JSONAPIAdapter

So, generally, the question is: what way is better for ember-upgrade?

  • keep backend API and maintain active-model-adapter
  • rewrite backend API and migrate to JSONAPIAdapter (with data/relationships approach)
  • rewrite backend API and migrate to RESTAdapter
  • keep backend API and implement custom serializer to change on the fly input/output to use JSONAPIAdapter or RESTAdapter (pick best) logic on FE (maybe it's some crazy way, but it's just to ask)

Note: backend API on RubyOnRails




Command like "ember s" gets stuck and not loading

I’ve been following Getting started https://guides.emberjs.com/release/getting-started/quick-start/.

I did:

npm install -g ember-cli ember new ember-quickstart cd ember-quickstart ember serve

After ember serve or server or ember s It just keeps loading and never load server.

Thank you for your help.




mercredi 18 novembre 2020

How do I update data in the service store in Ember?

I created a service where I declared the store:

store.js:

import Service from '@ember/service';

export default class StoreService extends Service {
  store = {
    lang: 'EN'
  }
}

I also got access to the store from the route:

first.js:

import Route from '@ember/routing/route';
import { inject } from '@ember/service';

export default Route.extend({
  store: inject(),
  model() {
    console.log(this.store);
    return this.store;
  }
});

And the template. first.hbs:

<div class="wrapper">
  <h3>First</h3>
  <hr class="gold">
  <p><button type="button">CN</button></p>
  
</div>


Please tell me how you can change the data in the storage from the route by pressing the "CN" button?

Regards.




Unwanted two-way data binding when passing data to Ember Octane component

I'm following the Full Stack Ember with Rails course on Embercasts. As they don't use Octane yet, I change the code where necessary to work with Ember 3.22. I'm stuck in video 22 where I need to pass data to a component. This data should only be passed to the component, but when updating a value inside it, I don't want to see the change in other places.

In the video, this is taken care of in a didReceiveAttrs() handler, but this is not available in Octane. Instead, the Ember docs describe one way data flow as what happens automatically. In my case, it doesn't:



<h3>Editing: ,  </h3>
<AuthorForm @autor= />



<div class="field">
  <label for="first">First name</label>
  <Input @id="first" type="text" placeholder="First name" @value=/>
</div>  

<div class="field">
  <label for="last">Last name</label>
  <Input @id="last" type="text" placeholder="Last name" @value=/>
</div>

The h3 updates whenever I change the value in one of the component's inputs. What's wrong here?




Not able to bind data in posts.hbs

templates/posts.hbs

<h2>Posts</h2>
    
      <div>
        <h3></h3>
        <h3></h3>
        <h3></h3>
        <h4></h4>
      </div>
    
    

serializers/posts.js

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
  normalizeResponse(store, primaryModelClass, payload, id, requestType){
    console.log(payload); //in console getting data here properly
    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

routes/posts.js

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.findAll('post');
  }
});

Getting data from backend API point and printing data in console properly. Everything fine. But not binding in handlebars (posts.hbs). Can someone help me with this? New to ember Js.




mardi 17 novembre 2020

ember install ember-modifier-manager-polyfill ERROR: RangeError: Maximum call stack size exceeded

After install addon: ember install ember-modifier-manager-polyfill Got failed testing suite on CI only (if run each particular test alone locally - test passed)

Here is the issue in status open about it: https://github.com/ember-polyfills/ember-angle-bracket-invocation-polyfill/issues/110 but in my case I have no similar case in templates:


  

So, it's something different... coz the failed are different tests (Integration/Acceptance) in different parts of the system

Notes:

ember-source: 2.14.1
ember-angle-bracket-invocation-polyfill: 2.0.2
jquery: 3.5.1
ember-modifier-manager-polyfill: 1.2.0

it's not a duplicate of this: What could be reason of the error 'Maximum call stack size exceeded' inside Ember Data? or this: Ember Uncaught RangeError: Maximum call stack size exceeded but the error with the same message

Output example:

stack: >
                at DOMAssertions.exists (http://0.0.0.0:4200/assets/test-support.js:24416:16)
                at DOMAssertions.exists (http://0.0.0.0:4200/assets/test-support.js:24737:18)
                at Object._callee$ (http://0.0.0.0:4200/assets/tests.js:141899:45)
                at tryCatch (http://0.0.0.0:4200/assets/vendor.js:6235:40)
                at Generator.invoke [as _invoke] (http://0.0.0.0:4200/assets/vendor.js:6509:22)
                at Generator.prototype.<computed> [as next] (http://0.0.0.0:4200/assets/vendor.js:6268:21)


browser log: |
            ERROR: RangeError: Maximum call stack size exceeded
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72303:51)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)
                at CurlyComponentManager.manager.didCreateElement (http://0.0.0.0:4200/assets/vendor.js:72304:45)

Appreciate any help




Is it possible to access sessionStorage from handlebars?

<h4 id="logout_button" >Logout Sign Up Login

above code throwing error




lundi 16 novembre 2020

EmberJS testing: target id created from each loop

I used an each loop to create a unique id for every input that's created. Ex: id='amount0', id='amount1', etc.. but I can't target them during testing, it says the element is not found.

Error

Promise rejected during "Amount input works": Element not found when calling `fillIn('#amount0')`.

HBS file:


<p output-test-info>
    <button onclick=>-</button>
    
    <input id="amount" onchange=>
</p>

Test file:

test('Amount input works', async function(assert){
    const itemList = document.queryCommandValue('output-test-info');
    this.set('tempName', [{name: 'bobby'}, {name: 'peter'}]);
    this.set('tempAct', [{activity: 'dinner'}, {activity: 'movies'}])
    await render(hbs`<Output @userinfo= @userAct=/>`);

    await fillIn('#amount0', '20');
  })



dimanche 15 novembre 2020

While starting ember server I'm getting this error like SyntaxError: Unexpected identifier async postBuild()

While starting ember server I'm getting this error What could be the reason for this error?

Unexpected identifier
/Users/chraju/Desktop/sites/blog-front-end/node_modules/ember-cli-typescript/js/addon.js:47
    async postBuild() {
          ^^^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/chraju/Desktop/sites/blog-front-end/node_modules/ember-cli-typescript/index.js:9:20)






mercredi 11 novembre 2020

Get the value of an Ember Component in the controller

Lets say I have a custom component called X.

<X>my value</X>

I now want to access the "my value" in the controller of X. How can I do that?




mardi 10 novembre 2020

How to setup JsonApiSerializer as default input and output seriliazers C# .NET Core 3+

I've been trying to setup JsonApiSerializer (https://github.com/codecutout/JsonApiSerializer) as the default serializer for both input and output so I can have an json:api compliant .NET server for an Ember application with Ember Data.

I have succesfully setup the output serializer by writing the following code to the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("myDb")));

            var sp = services.BuildServiceProvider();
            var logger = sp.GetService<ILoggerFactory>();
            var objectPoolProvider = sp.GetService<ObjectPoolProvider>();

            services.AddMvc(opt =>
            {
                var serializerSettings = new JsonApiSerializerSettings();
**
                var jsonApiFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool<Char>.Shared, opt);
                opt.OutputFormatters.RemoveType<NewtonsoftJsonOutputFormatter>();
                opt.OutputFormatters.Insert(0, jsonApiFormatter);
**
                var mvcNewtonsoftSettings = new MvcNewtonsoftJsonOptions();

                var jsonApiInputFormatter = new NewtonsoftJsonInputFormatter(logger.CreateLogger<NewtonsoftJsonInputFormatter>(), serializerSettings, ArrayPool<Char>.Shared, objectPoolProvider, opt, mvcNewtonsoftSettings);
                opt.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
                opt.InputFormatters.Insert(0, jsonApiInputFormatter);
                //opt.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().FirstOrDefault().SupportedMediaTypes.Add("application/vnd.api+json");

            }).AddNewtonsoftJson();
        }

But the Input part isn't working yet!

I've been triyng to receive code from a Ember application that follows this structure:

{
  "data": 
  {
    "type": "manufacturer",
    "name": "Fabricante 1",
    "relationships": {
      "products": {
        "data": [
          {
            "type": "product",
            "id": "1"
          },
          {
            "type": "product",
            "id": "2"
          }
        ]
      }
    }
  }
}

The binding model of the .NET server for POSTing a manufacturer is like this:

public class CreateManufacturerBindingModel
    {
        public string Type { get; set; } = "manufacturer";
        public string Name { get; set; }
        public AssignProductBidingModel[] Products { get; set; }
    }

public class AssignProductBidingModel
    {
        public string Type { get; set; } = "product";
        public int Id { get; set; }
    }

I've been trying out some variations of those codes for a while and all I can get is Null values for "Name" and "Products" attributes of the CreateManufacturerBindingModel

Does anyone has any clue of why I keep on getting null values at the .NET server?

Thank you for your attention!




jeudi 5 novembre 2020

Yield not stopping the flow in ember concurrency task

if (isEmpty(contact) || isEmpty(get(contact, 'emails'))) {
  contact = yield store.findRecord('contact', contactId);
}

if (isEmpty(contact) || isEmpty(get(contact, 'emails'))) {
  flashMessages.danger(i18n.t('email.cpq_document_email_missing'));
  return false;
}

The second block runs when the promise is running and Im getting an error. Shouldn't it stop the flow until the promise is resolved.

The promise runs fine and it works the next time




Facing issue after update ember from 3.0.0 to 3.22.0

After updating ember from 3.0.0 to 3.22.0 using ember-cli-update and install npm packges. And finally hit ember s it throws the bellow error.

Build Error (SourceMapConcat)
ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'

Stack Trace and Error Report: /var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/error.dump.a86e097d39858aa6e4eacea11b04401c.log

Here is the full log file

ERROR Summary:

  - broccoliBuilderErrorStack: Error: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at FSMerger.handleOperation (/Applications/MAMP/htdocs/pm-client/node_modules/fs-merger/dist/index.js:82:32)
    at SourceMap.addFile (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:78:38)
    at headerFiles.forEach.file (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:203:18)
    at Array.forEach (<anonymous>)
    at Concat.concat.end.concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:201:26)
    at /Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:432:14
    at new Promise (<anonymous>)
    at SourceMap.end (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:419:12)
  - code: [undefined]
  - codeFrame: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
  - errorMessage: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
        at SourceMapConcat (Package /assets/vendor.js)
-~- created here: -~-
    at new Plugin (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/broccoli-plugin/dist/index.js:45:33)
    at new Concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:28:5)
    at module.exports (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/index.js:28:10)
    at importPaths.map (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1312:14)
    at Array.map (<anonymous>)
    at DefaultPackager.packageVendorJs (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1306:35)
    at DefaultPackager.packageJavascript (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1182:27)
    at EmberApp._legacyPackage (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1613:48)
    at EmberApp.toTree (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1659:27)
    at module.exports (/Applications/MAMP/htdocs/pm-client/ember-cli-build.js:30:14)
-~- (end) -~-
  - errorType: Build Error
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
    - treeDir: [undefined]
  - message: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
        at SourceMapConcat (Package /assets/vendor.js)
-~- created here: -~-
    at new Plugin (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/broccoli-plugin/dist/index.js:45:33)
    at new Concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:28:5)
    at module.exports (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/index.js:28:10)
    at importPaths.map (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1312:14)
    at Array.map (<anonymous>)
    at DefaultPackager.packageVendorJs (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1306:35)
    at DefaultPackager.packageJavascript (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/default-packager.js:1182:27)
    at EmberApp._legacyPackage (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1613:48)
    at EmberApp.toTree (/Applications/MAMP/htdocs/pm-client/node_modules/ember-cli/lib/broccoli/ember-app.js:1659:27)
    at module.exports (/Applications/MAMP/htdocs/pm-client/ember-cli-build.js:30:14)
-~- (end) -~-
  - name: Error
  - nodeAnnotation: Package /assets/vendor.js
  - nodeName: SourceMapConcat
  - originalErrorMessage: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
  - stack: Error: ENOENT: no such file or directory, open '/var/folders/wm/w121z2bs7yngf13gc_qbsn_w0000gn/T/broccoli-51053YM0PSytfuMoE/out-881-broccoli_debug_debug_5_vendor_js/vendor/simple-module/lib/module.js'
    at Object.openSync (fs.js:439:3)
    at Object.readFileSync (fs.js:344:35)
    at FSMerger.handleOperation (/Applications/MAMP/htdocs/pm-client/node_modules/fs-merger/dist/index.js:82:32)
    at SourceMap.addFile (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:78:38)
    at headerFiles.forEach.file (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:203:18)
    at Array.forEach (<anonymous>)
    at Concat.concat.end.concat (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/concat.js:201:26)
    at /Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:432:14
    at new Promise (<anonymous>)
    at SourceMap.end (/Applications/MAMP/htdocs/pm-client/node_modules/broccoli-concat/node_modules/fast-sourcemap-concat/lib/source-map.js:419:12)

=================================================================================

Can anyone give me an answer why this is happening and how should I resolve this?




mardi 3 novembre 2020

Get current route name from corresponding loading route in ember

As per ember document If any model hook in routes taking time to fetch data from server, ember will insert loading route. for example test-loading, at that time if we try to get current route name like this, it returns only the loading route. for example if sample route is getting too much of time to load, ember will transition into sample-loading until sample route resolved. Then again it will change to sample route. So at the time of sample-loading getCurrentRoute is returns the sample-loading. In my case I need to know the actual route name which is changed into -loading. I can't find any documentation in internet for doing this. If anyone know the way or idea to implement kindly share with me..




lundi 2 novembre 2020

ember-qunit-notifications bower package is not working for node version 6.9.2, but working for latest node versions

When I try to execute some bower packages in my laptop (hp- Intel(R) Core(TM) i7-1065G7 - 10th gen) for older node versions(6.9.2) it shows SSL certification error like in this image. and not with the latest versions(14.15.0). But this issue is not related to other computers and works all bower packages with any node versions. enter image description here




Is there any way to listen to eventbus from an ember-modal dialog?

The scenario is to listen to an eventbus notification when the ember modal is open, refresh the route page while closing the modal, as i am not able to subscribe to the event from ember modal, unable to do the conditional refresh.