dimanche 29 septembre 2019

Not letting me import modules in Ember js for some reason or an another

I have just started a small Ember project just to get my self familiar with it and it's causing me a headache at the moment because it just refuses to play ball with npm imports.

So i have a component that i am trying to import axios into and it just keeps saying Could not find module npm:axios and for the life of me i cant figure our why.

Here is my code

import Component from '@ember/component';
import axios from 'npm:axios';

import emailValidate from '../validators/email';

export default Component.extend({
  isValidEmail: false,
  actions: {
    onChange: function(value) {
      this.set('isValidEmail', emailValidate(value));

      if (emailValidate(value)) {

        axios.get('http://localhost:3000/users/').then(function (response) {
      // handle success
      console.log(response);
    })
  }
  },

 }
});

I have also tried import axios from 'axios'




How to import jQuery from @ember/jquery

I am trying to import @ember/jquery in my component. I did install @ember/jquery and @ember/optional-features and imported as below import $ from '@ember/jquery' but I am getting error missing module @ember/jquery in my component.

Is this the right way to import it?




samedi 28 septembre 2019

Ember Corber iOS Satus Bar Color

Possibly very simple, but how would I change the iOS status bar in my Ember Corber project to be white. It's currently stuck on transparent.




vendredi 27 septembre 2019

EmberJs - unable to implement dynamic-import-polyfill

We are trying to implement dynamic-import-polyfill to import external file Ember compile time(build time).

Followed steps mentioned in https://github.com/GoogleChromeLabs/dynamic-import-polyfill

but got stuck when adding following lines of code in ember-cli-build.js.

following line of import works fine ,because with this I can successfully bring ember server up

import dynamicImportPolyfill from 'dynamic-import-polyfill';

but as soon as I am adding following lines ,ember server throws exception on start and stops

dynamicImportPolyfill.initialize({     modulePath: '/web-app', // Defaults to '.'     importFunctionName: '$$$import' // Defaults to 'import'   });

When checked in error logs found following error

stack: ReferenceError: location is not defined at Object.e.initialize (C:\code\Project-Chimps\source\web-app\node_modules\dynamic-import-polyfill\dist\dynamic-import-polyfill.umd.js:1:366)

tried lots of sites but no where I got the proper example:

while defining dynamicImportPolyfill.initialize({.... what should be the value for modulePath:

I did not understand following info mentioned for modulePath

modulePath string
A path for which all relative import URLs will resolve from.

Default Value: '.'

This should be an absolute path to the directory where your production modules are deployed (e.g. /public/). If given a relative path, it is resolve against the current page's URL.

Someone please help us with the example how I can use dynamic-import-polyfill with EmberJs




jeudi 26 septembre 2019

Ember.js: parallel loading parent and child models

I have these routes:

  • posts
    • index (all the posts)
    • single (with dynamic parameter post_id)
      • index (single post and it's comments view)
      • edit (editing post)

There are two separate requests for fetching post by ID and fetching post comments by post ID. I want to load post and comments for posts.single.index route in parallel, because I have a post ID in route name and I do not have to wait when post will be loaded.

But Ember loads posts.single model, and only AFTER post it loads comments.

Is it possible to call child model in parallel with parent model?

I have found a solution when posts.single does not load anything, and posts.single.index calls two requests in it's own model. On the other hand, I should load post model within all posts.single child routes, such as posts.single.edit. It could be a problem, when application will be grow.




How to return an excel file in a flask API when my Ember client expects a JSON result? [on hold]

I am creating an excel file and attempting to use the flask send_from_directory functionality to allow the client to download the file that was just created.

    df1 = data
    file_name = 'test' + '.xlsx'

    writer = pd.ExcelWriter(
        file_name,
        engine='xlsxwriter'
    )

    df1.to_excel(writer, sheet_name='Sheet1')

    writer.save()

    return send_from_directory("", file_name, as_attachment=True)

The response on the client side is showing the file, but in a really messy way.

PK?FjÒ»a¯[Content_Types].xmlÍ

etc.

And I am getting an error on my client side ajax request that hits the API that creates the file:

Unexpected token P in JSON at position 0.

Before I am able to do anything with the file on the client side.

How do I send a file back to the client when the client is expecting a JSON value being returned by the API?




mercredi 25 septembre 2019

emberjs: Passing selected value to select field in form

I am attempting to add a SELECT field from first principles using ember and am having difficulty working out how to pass the currently selected option to a form when editing a record.

I have set the form up as a component and am able to use it successfully when creating a new record, with the selected value being passed to the Rails backend. My issue is that I cannot work out a way to apply this selected value to the form component when editing an existing record.

Here is the component template section (book-form.hbs):

  <div class="form-group">
    <select id="format" onchange=>
      <option value=""></option>
      <option value="Paperback">Paperback</option>
      <option value="Hardcover">Hardcover</option>
      <option value="E-Book">E-Book</option>
    </select>

Template code (book-form.js):

import Component from '@ember/component';

export default Component.extend({
  actions: {
    submitChange(param) {
      this.onSave(param, this.selectedOpt);
    },
    selectedOpt: "",
    updateValue(value) {
      this.set('value', value);
      this.selectedOpt = value;
    },
  }
});

new & edit templates:


new controller:

export default Controller.extend({
  actions: {
    saveBook(newBook,format) {
      var tmp = this.store.createRecord('book', {
        title: newBook.title,
        author: newBook.author,
        genre: newBook.genre,
        format: format,
      });
      tmp.save();
      this.transitionToRoute('books.list');
    }
  }
});

edit controller:

  actions: {
    saveBook(book) {
      book.save();
      this.transitionToRoute('books.list');
    }
  }

I know I'm missing something somewhere to pass the model value through to the component but am not sure how to do it or where it belongs.

I would appreciate any assistance at all.




How can i call a Parse.Cloud function in a ember component

I create a function on my "main.js" (API). I have some afterSave, afterDelete function on this main.js which they are called when i save or delete some object in my ember components. Here's come my problem:

I create a function "Parse.Cloud.Define('myFunction'...)", but i can't call it on my ember component... i've tried to call the function with "Parse.Cloud.run" in my component, but i got a ReferenceError.

My question is, what should i do to call this function?

I create this function to provide parameters to my API, because with these parameters i can use the function to change the Password.




lundi 23 septembre 2019

Ember CSP: Change connect-src dynamically

Is there a way to change the connect-src at runtime in ember-cli-content-security-policy?

contentSecurityPolicy: {
            'default-src': "'none'",
            'script-src': "'self' 'unsafe-inline' 'unsafe-eval' www.google-analytics.com",
            'font-src': "'self' data: use.typekit.net fonts.gstatic.com",
            'img-src': "'self' data: image/png www.google-analytics.com",
            'connect-src': "'self' www.google-analytics.com wss://data-test/ws",
            'style-src': "'self' 'unsafe-inline' http://fonts.googleapis.com",
            'frame-src': "'self' http://test.com/ESTORERIA/Agreement/en/EULA.htm"
        }




dimanche 22 septembre 2019

How to properly use metadata in Ember query?

I have been trying to implement pagination (I've tried both ember-cli-pagination and ember-simple-pagination) for my application but I've had a lot of issues. So I decided to try custom pagination and noticed that I cannot pass metadata into my query. For instance, when visiting my api at: http://jsonplaceholder.typicode.com/posts?_start=0&_limit=10, start and limit both work properly. When calling it in my route, it seems to ignore that entirely and just give me all entries. I would appreciate all insight into what I am doing wrong or how to properly implement pagination in this case.

app/adapters/post.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  host:'https://jsonplaceholder.typicode.com',
  pathForType(){
    return 'posts';
  }
});

app/models/post.js

import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
  user:DS.belongsTo('user'),
  title:DS.attr('string'),
  body:DS.attr('string'),
});

app/routes/post.js

import Route from '@ember/routing/route';
import { set } from '@ember/object';
import { hash } from 'rsvp';

export default Route.extend({
  model() {
    return hash({
      post: this.store.query('post', {
                start: 0,
                limit: 10
            }),
      user: this.store.findAll('user')
    });
  },

  setupController(controller, model) {
    this._super(...arguments);
    set(controller, 'posts', model.post);
    set(controller, 'users', model.user);
  }

});




NGINX returns 404 error on page reload (Ember app)

I am using nginx to serve landing page, SPA (Ember), and Rails backend on same domain. All seems work well except when I refresh some SPA route, for example https://server_name.ru/app/login NGINX returns 404 error /home/aborovkov/apps/frontend/dist/login" failed. This doesn't happen when I enter this route manually, only after page refresh. How to fix this?

server {
        root /home/aborovkov/apps/landing;
        index index.html index.htm index.nginx-debian.html;
        try_files $uri $uri/ /index.html?/$request_uri;
        add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
        add_header Pragma "no-cache";

        server_name server_name.ru www.server_name.ru;
        access_log /etc/nginx/server_name.access.log;
        error_log /etc/nginx/server_name.error.log;

        location /app {
          alias  /home/aborovkov/apps/frontend/dist;
          index index.html index.htm index.nginx-debian.html
          try_files $uri $uri/ /index.html?/$request_uri;
          add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
          add_header Pragma "no-cache";
        }

        location /api/ {
          root /home/aborovkov/apps/api/current/public;
          proxy_pass  http://localhost:3000;

          passenger_enabled on;
          passenger_app_env production;
          client_max_body_size 100m;
        }

        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/server_name.ru/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/server_name.ru/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

 server {
    if ($host = www.server_name.ru) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = server_name.ru) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80;
        listen [::]:80;

        server_name server_name.ru www.server_name.ru;
    return 404; # managed by Certbot
}




samedi 21 septembre 2019

generate model syntax different to tutorial

ember octane tutorial. using: ember generate model person creates a build error when used for person model (and any other model for that matter).

I was looking at the ember octane tutorial and generated the person model. The generated code included code that significantly differs from the example. This extra code causes build errors.

This is after I run

"ember generate model person"

import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({

});

This is the example from https://octane-guides-preview.emberjs.com/release/models/

import DS from 'ember-data';
const { Model, attr } = DS;

export default class Person extends Model {

  @attr('string') firstName;
  @attr('date') birthday;

}

If I added the @attr code to the generated model, I get this build error.

testapp/models/person.js: Unexpected token, expected "," (5:27)
3 | 
4 | export default class Person extends Model ({
5 |   @attr('string') firstName;
  |                            ^
6 |     @attr('date') birthday;
7 | });

The issue was that the generated model includes a few things that the example does not.

export default Model.extend({

instead of

export default class Person extends Model {

I expected a clean build as I used the ember generate model method and added the pieces for the attr as per example.

I think the ember generated model blueprint needs updating for Octane?

I would also suggest the blueprint adds the 'class extends Model' as well?




vendredi 20 septembre 2019

What is the equivalent of react context in glimmerjs?

I've been using react for the past three years and just watched a few talks about ember and glimmer and got interested in glimmer. So excuse my ignorance if the question doesn't make sense.

What will be an equivalent of a global state / context in a glimmer app? What I'm looking for is a @tracked data which can be accessed deep in the component tree without passing it as argument at each level. Think redux without all those ceremonial action/action-creator/reducer.

A single global atom with bunch of functions to immutably modify it and re-actively see the change on the component tree.




jeudi 19 septembre 2019

My ember application fully reload when I add a queryParam in a transitionTo

I am doing a search based on the data entered by a user in a search form and redirecting to a route with this data as queryParam and this reloads the application completely.

I make the transition like this: 'search' is the data entered by the user.

this.get('router').transitionTo('private.route1', { queryParams: { search: search } });

In the controller of the destination route I have declared this queryParam

export default Controller.extend({
    queryParams: ['search'],
});

and there I do an API search based on this queryParam. Everything works fine but when I do a transitionTo to this route, for some reason the symbol '?' is added at the beginning of the path of my route and this reloads the page.

The result I expected is that the transition is made the url looks like this and the application don't fully reload: http://localhost:4200/#/private/route1?search=userdata

And the real result is:

http://localhost:4200/?#/private/route1?search=userdata

with the symbol '?' in the beginning of the path, which causes the application to fully reload.




Use electron with ember without using the ember-electron plugin

I am new to electron development. Is it possible to use electron with ember without using the ember electron plugin? I already wrapped my application using openfin and want to move to electron with minimal code changes.




How to test an ember.js engine route without the ember/no-restricted-resolver-tests eslint error?

My ember.js app uses an in-repo mountable engine called user-backoffice.

This engine provides a route called my-engine-route, and here is the unit test for it, located at my-app/lib/user-backoffice/test-support/unit/my-engine-route/route-test.js

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import engineResolverFor from 'ember-engines/test-support/engine-resolver-for';

const modulePrefix = 'user-backoffice';
const resolver = engineResolverFor(modulePrefix);

module('[user-backoffice] Unit | Route | my-engine-route', function(hooks) {
  setupTest(hooks, {resolver});

  test('it exists', function(assert) {
    let route = this.owner.lookup('route:my-engine-route');
    assert.ok(route);
  });
});

The engineResolverFor part is taken from the ember-engine.com docs.

My problem is that this code generates an eslint error because of the ember/no-restricted-resolver-tests rule.

my-app/lib/user-backoffice/test-support/test-support/unit/my-engine-route/route-test.js
  9:20  error  Do not use setupTest whose last parameter is an object unless used in conjunction with `integration: true`  ember/no-restricted-resolver-tests

In my opinion, the eslint rule and the ember-engine docs are in contradiction, so I'd like to know if the rule should be disabled in an engine's context, or if the ember-engine.com docs should be updated.




mercredi 18 septembre 2019

How can I re-use the same model template for different requests in Ember?

Imagine I have 20 charts on the index page of my application. I can request the data points for each chart in JSON:API form from the API:

export default Route.extend({
    model() {
        return {
            chart01: this.store.findAll('chart-timetable-01'),
            chart02: this.store.findAll('chart-timetable-02'),
            // ... etc

All routes from the API return a collection of documents that each represent a data point. Every document has the same attributes: name and value.

Now even though they are all exactly the same, I need to have 20 models:

models/chart-timetable-01.js
models/chart-timetable-02.js
# ... etc

Now that I want to introduce a second chart type with an actual different model, I want to simplify this. Can I use one model for all charts that are functionally the same, so that I don't have to duplicate the model for every new chart?

So in stead of chart-timetable-{01..20}.js I can have one simple chart.js model?

I can override the type with a serializer:

import DS from 'ember-data'

export default DS.JSONAPISerializer.extend({
    normalizeResponse(store, primaryModelClass, payload, id, requestType) {

        if (primaryModelClass.modelName.match(/^chart-timetable-/g)) {
            payload.data.forEach((doc, idx) => doc.type = 'chart')
        }

        return this._super(...arguments)
    }
})

But Ember still wants models named in the findAll to exist. How can I override this?




mardi 17 septembre 2019

How to fix type checking when using this.store.findRecod

In my ember.js project, I type check javascript files with Typescript and the checkJs option.

Here is a simple route.js file example

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

export default class UsersRoute extends Route {
  model() {
    return this.store.findAll('user');
  }

}

With this code, I get the following Typescript error

route.js:5:31 - error TS2345: Argument of type '"user"' is not assignable to parameter of type 'never'.

5     return this.store.findAll('user');
                                ~~~~~~

The ember-data type definitions are provided by the @types/ember-data package, and here is the findAll definition

findAll<K extends keyof ModelRegistry>(
    modelName: K,
    options?: {
        reload?: boolean;
        backgroundReload?: boolean;
        include?: string;
        adapterOptions?: any;
    }
): PromiseArray<ModelRegistry[K]>;

This is how far I could go while investigating how findAll was defined.

In theory, this.store.findAll('user'); is valid, but what should I do to fix this Typescript error?




How do I mock websocket in ember-cli-mirage?

I want to know of anyway using which I can mock a websocket in ember-cli-mirage. Currently ember-cli-mirage does not support this. They may in future I guess. Here's the link to the ticket : https://github.com/samselikoff/ember-cli-mirage/issues/1273 Meanwhile can you suggest anyway to achieve this? Or if you're already mocking a websocket using mirage, can you share how?




Ember Data returns an array of internal models instead of actual data

I'm creating a new adapter and model and trying to fetch data to use it in my template. When I make a request in route, the data in the model looks like this: data from ember

The actual response looks like this:

actual data

I really have no idea why ember store returns the data with wrong ID's(the first two objects are objects from the response - but the id fields don't match) and some internal methods.

Code for the adapter:

export default DS.RESTAdapter.extend(UrlTemplates, {
  session: Ember.inject.service('session'),
  findAll() {
    const token = this.get('session.data.authenticated.access_token');
    return this.ajax(`${window.App.host}/distributor/${1}/companies?access_token=${token}`);
  }
});

Code for the router:

model() {
    return Ember.RSVP.hash({
      companies: this.store.findAll('distributor/distributors')
    });
  },

As you can see, this is pretty usual process.If I log data from the request in route, it is already mixed up. Considering Ember Data's data flow I assume that the data is being mixed up in the store. Is there any way to fix this?




lundi 16 septembre 2019

How to customize ember-bootstrap components?

I'm new to learning Ember and it mostly makes sense except I'm having a bit of a problem with templating.

My model retrieves a record array and I want to display each record in a collapse-able bootstrap accordion. There is a native ember-bootstrap component (BsAccordion) that seems to make this super easy, but it includes some styling that I'd prefer not to use.

My template is simple and looks like this:

<BsAccordion as |list|>
  
    <list.item @value= @title=" : ">
      }
    </list.item>
  
</BsAccordion>

The problem I have is that it wraps each message in a div with class="card" and I do not wish to use bootstrap's card layout. How can I customize the component and prevent it from doing this?




Assertion Failed: No application initializer named 'store'

I've upgraded ember-cli from 2.x.x to 3.1.2, and suddenly one of my initalizers throwing this assertion error: Assertion Failed: No application initializer named 'store'

I think there is an ordering problem, one of my initalizers trying to import store which hasn't already been initialized.

Tried after: 'store' and after: 'ember-data' property in initalizers but none of them worked.

Thanks for your help!




dimanche 15 septembre 2019

How to send a POST request with dynamic queryparam to Mirage?

I'm firing an action in a component to create a record with an argument(mediaType) in Mirage like so:

// my-component

actions: {
  submitForm() {
    let mediaType = 3;
    let item = this.store.createRecord('movie', { mediaType });

    return item.save(); // => POST to '/movies'
  }
}

Here is the movie model:

const { attr, Model } = DS;

export default Model.extend({
  mediaType: attr('number'),
  ...
});

In the adapter I use urlForCreateRecord to take mediaType property off of the model. I add it to the query string:

// adapters/my-component

namespace: '/theater',
CreateRecord(modelName, snapshot) {
  let rootURL = `${ENV.APP.apiEndpoint}/${this.namespace}`;
  let mediaType = snapshot.attr('mediaType');
  let data = this.serialize(snapshot);
  delete data.mediaType;

  return `${rootURL}/movies?mediaType=${mediaType}`; // => POST to '/theater/movies?mediaType=3'
}

And in Mirage I have the route set up like so:

// mirage/config.js

this.post('/theater/movies', ({ movie }, request) => {
  let { mediaType } = request.queryParams;
  let movieData = JSON.parse(request.requestBody);
  let returnArray = movieData.map((item) => {
    return movie.create(item);
  });

  return new Response(200, {}, returnArray);
});


But Mirage cannot find any route that matches this endpoint.

I've also hardcoded the endpoint like so but Mirage still couldn't find it:

// mirage/config.js

this.post('/theater/movies?mediaType=3', ({ movie }, request) => {
  ...
});

Any idea why Mirage throws there was no route defined to handle this request error?




vendredi 13 septembre 2019

Loading binary file with webpack and converting to Blob

I have a <input id=file-chooser" type="file"/> control that I allow a user to upload a .zip file with and I then hand that off to jszip for further processing.

I am trying to test this by loading a local .zip test file in webpack, converting to a Blob, and then manually firing the change event with the content of the file.

jszip is complaining that the zip file is not valid and I think I am messing something up on the conversion.

I've tried:

// Load file at webpack compilation time
const zipFileRaw = require("raw-loader!../test.zip");

// Convert to ArrayBuffer
const bytes = new Uint8Array(zipFileRaw.length);
for (var i = 0; i < zipFileRaw.length; ++i) {
  bytes[i] = zipFileRaw.charCodeAt(i);
}

// Construct a 'change' event with file Blob
const file = new Blob(bytes, { type: "application/zip" });
file.name = "test.zip";
const event = { type: "change", target: { files: [file] } };

// Fire the event
$("#file-chooser").trigger(event);

Firing the event works and my event handler is called. In the event handler for the change event I call jsZip.loadAsync(file) and I get:

Error: Can't find end of central directory : is this a zip file ?




jeudi 12 septembre 2019

emberjs model data null in template after normalizeResponse

I've trying to data from an api in to a template. But i cannot get the data into the template. i can see the model data in the serializer. The model object is just null

./app/routes/blogpost.js

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


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

./app/adapters/blogpost.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
        host: 'http://localhost:5000',
        pathForType: function(modelName) {
                return "posts";
        }
});


./app/serializers/blogpost.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
        /*normalizeResponse: function(store, primaryModelClass, payload, id, requestType) {

                let newPayload = {};
                newPayload[primaryModelClass.modelName] = payload;

                return this._super(store, primaryModelClass, newPayload, id, requestType) 
        }*/
});

./app/templates/blogpost.hbs

test








  
  




and the model ./app/models/blogpost.js

import DS from 'ember-data';
const { Model } = DS;

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

i can see in the browser that the xhr request is made and i also get the data. In the serializer the data is still there, but after that i cannot access the model attribute/object in the template.

the browser console only outputs null.

any ideaas where i've gone wrong?

thanks for any help.




mercredi 11 septembre 2019

Not able to use Redux inside React/Ember project

My project is built in Emberjs and i'm trying to integrate React and Redux in my project. I'm able to use react inside the project with this helpful addon:

https://github.com/alexlafroscia/ember-react-components

Now i'm trying to add Redux for my state management, everything is okay until i use connect function to connect my component to store.

const mapStateToProps = {};
export default connect(null, {fetchData})(ReactComponent)

Its giving following error in console:

route.js:62 TypeError: C is not a constructor
    at Object._ClassMixinProps.create (core_object.js:282)
    at FactoryManager.create (container.js:439)
    at Proxy.create (container.js:197)
    at CurlyComponentManager.create (curly.js:155)
    at runtime.js:1671
    at AppendOpcodes.evaluate (runtime.js:70)
    at VM.next (runtime.js:7246)
    at TemplateIterator.next (runtime.js:7317)
    at RootState.render (renderer.js:60)
    at TransactionRunner.runInTransaction (ember-metal.js:826)

I'm following this simple tutorial to understand Redux: https://www.youtube.com/watch?v=93p3LxR9xfM

Do anyone have idea how i can resolve this issue?

Thanks for helping!!




mardi 10 septembre 2019

javascript: How can i access class methods and attributes inside a function in class

I have a class which contain a function, so i want to able to call some of class method inside this function

class Upload {
* uploadFiles(files: FileList | File[]) { 
let file;
for (let i = 0; i < files.length; i++) {
  if (filesAdded === 1) {
      break;
  }
  file = files[i];
   if (this.types.indexOf(file.type) > -1) {
       filesAdded++;
    } else {
        this._showBadExtensionError();
         return false;
    }
  }
        var worker_fn = () =>
        {
            this.send(file); // i want to able to access send() method and file attribute above 
            self.postMessage('upload sucessfully...');
        };
        var blob = new Blob(["onmessage ="+worker_fn.toString()], { type: "text/javascript" });

        var worker = new Worker(window.URL.createObjectURL(blob));

}
send(file: File, url) {
  let formData = new FormData(); 
  formData.append('file', file, file.name);
  const response = await this.apiRequest.POST(url, formData);
  return response.json();
}

}

i want to find away to access class method send and the attribute file inside worker function ?




lundi 9 septembre 2019

Add computed property to Route.Extend in Ember

So I have a main.js file which is a route:

import user from 'config/user';
import { computed } from '@ember/object';

export default Route.extend(SomeMixin, {
    firstName: computed(function () {
       return user.firstName;
    },
}),


in my hbs file I have

firstName is always empty in my hbs file. Is it possible to add a computed function to a route?




How to fix 'service injection' for EmberJS integration test?

I have a tasks-table component that uses 'current-user' service. I inject the service into the component as displayed below

import { inject as service } from '@ember/service';
export default Component.extend({
   currentUser: service(),
   showBatchAction: computed('currentUser.user.directRoles.@each.title', function() {
    return this.get('currentUser.user.directRoles').toArray().some((role) => {
      return (role.id == 13) || (role.id == 15)
    });
  }),
});

The code works fine however, the integration test fails.

Test:

module('Integration | Component | tasks-table export csv button', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    run(() => {
      this.owner.unregister('service:current-user');
    });

    this.owner.register('serivce:current-user', Service.extend({
      user: EmberObject.create({
        first_name: 'Bob',
        last_name: 'Newby',
        role: 'client',
        directRoles: {title: 'employee', id: 1}
      })
    }));
  });

  test('it renders', async function(assert) {
    var component = this.subject({
      authManager: stubMyService.create()
    });
    await render(hbs ``);

    assert.equal(this.$('.export-csv').text().trim(), 'Export as CSV');
  });

});

The error I'm getting is: TypeError: undefined is not an object (evaluating 'this.get('currentUser.user.directRoles').toArray')




Ember Integration Test: Component with each helper fails test

While following the emberjs tutorial I couldn't get my component to pass the testing
(https://guides.emberjs.com/release/tutorial/simple-component/).

The tutorial expected the each helper to be placed in the
template file (app/templates/rentals.hbs) to send each element of the array. Instead of placing the each helper in the template file I placed it in the component file
(app/templates/component/rental-listing.hbs) so I wouldn't have to write it out each time I needed to place the rental list.
The error in testing was:
Promise rejected during "should display rental details": Cannot read property 'textContent' of null

This works in testing:

<article class="listing">
  <a
    onclick=
    class="image "
    role="button"
  >
    <img src= alt="">
    <small>View Larger</small>
  </a>
  <div class="details">
    <h3></h3>
    <div class="detail owner">
      <span>Owner:</span> 
    </div>
    <div class="detail type">
      <span>Type:</span> 
    </div>
    <div class="detail location">
      <span>Location:</span> 
    </div>
    <div class="detail bedrooms">
      <span>Number of bedrooms:</span> 
    </div>
  </div>
</article>

While wrapping the previous code with this doesn't:





Here's the test:

// @rental is correctly renamed to @rentalListings

module('Integration | Component | rental-listing', function (hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function () {
    this.rental = EmberObject.create({
      image: 'fake.png',
      title: 'test-title',
      owner: 'test-owner',
      type: 'test-type',
      city: 'test-city',
      bedrooms: 3
    });
  });

  test('should display rental details', async function(assert) {
    await render(hbs`<RentalListing @rental= />`);
    assert.equal(this.element.querySelector('.listing h3').textContent.trim(), 'test-title', 'Title: test-title');
    assert.equal(this.element.querySelector('.listing .owner').textContent.trim(), 'Owner: test-owner', 'Owner: test-owner');
  });

  test('should toggle wide class on click', async function(assert) {
    await render(hbs`<RentalListing @rental= />`);
    assert.notOk(this.element.querySelector('.image.wide'), 'initially rendered small');
    await click('.image');
    assert.ok(this.element.querySelector('.image.wide'), 'rendered wide after click');
    await click('.image');
    assert.notOk(this.element.querySelector('.image.wide'), 'rendered small after second click');
  });
});

Should I not be placing an each helper in a component or is my testing file not setup correctly?

I can try to create a twiddle if the problem is not clear enough.




Ember Octane: how to do background upload with web worker?

I want to do background uploading with web worker in my ember octane app as we upload very large assets so i have a method inside class as following

export default class UtilsUploadComponent extends Component {

private asyncUpload() {
  var worker_fn = () =>
  {
     let data = yield this.sendData(file) // i want to achieve that 
     self.postMessage(data);
   };

   var blob = new Blob(["onmessage ="+worker_fn.toString()], { type: "text/javascript" });

   var worker = new Worker(window.URL.createObjectURL(blob));
   worker.onmessage = function(e)
   {
     console.log(e.data);
   };
   worker.postMessage("start");
   return -1
}

async sendData(file: File, url) { 
   let formData = new FormData();
   formData.append('data', file, file.name);
   const response = await this.apiRequest.POST(url, formData);
   return response.json()
}
}


so i want to call send data inside worker function and call post message after i received the data ?




dimanche 8 septembre 2019

Why does my current-client service get rebuilt everytime the URL is changed in the address bar?

I have a current-client service in Ember that is designed to pull the current user's information from the database and store it inside the service so that it can be used throughout the application. As long as I click on the navigation menu links, the current user information is preserved. But, when changing the URL in the address bar, the current user gets wiped out and the service has to go back and get the information again.

Why is this happening and how can I prevent it from happening?

Service: Current-client.js

import Service, { inject as service } from '@ember/service';

export default Service.extend({

    store: service('store'),

    isTwoFactorAuthenticated: false,

    twoFactorCodeSendMethod: null,

    client: null,

    loadCurrentClient() {

        this.get('store').queryRecord('client', {me: true})
        .then((client) => {

            this.set('client', client);
        });
    },
});

Route: Application.js

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

export default Route.extend({

    session: service('session'),
    currentClient: service('current-client'),

    beforeModel() {

        this._super(... arguments);
        this.loadCurrentClient();
    },

    activate() {

        this._super(...arguments);

        document.body.classList.add('gray-bg');
    }, 

    init() {

        this._super(... arguments);

        this.get('session').on('authenticationSucceeded', () => {

            this.loadCurrentClient();

            this.get('currentClient').set('twoFactorCodeSendMethod', null);
            this.get('currentClient').set('isTwoFactorAuthenticated', false);
        }),

        this.get('session').on('invalidationSucceeded', () => {

            this.get('currentClient').set('client', null);
            this.get('currentClient').set('isTwoFactorAuthenticated', false);
            this.get('currentClient').set('twoFactorCodeSendMethod', null);

            window.location.replace('/clients/login');
        });
    },

    loadCurrentClient() {

        if(this.get('session').get('isAuthenticated')) {

            this.get('currentClient').loadCurrentClient();
        }
    },
});




jeudi 5 septembre 2019

Select2 input closes before selecting in android chrome mobile

I have a problem when using select2 4.0.5 in android chrome mobile, it closes right before I select an option. What should I do ? Do I need an upgrade or is there any suggestion ?




How can I ember a 3rd party js lib via a script tag in Ember?

I'm trying to integrate Plaid with an Ember and am following the instructions on their site. It should be simple, the instructions say to just add

<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js" />

and it'll give you a Plaid class that can be used to interface with Plaid.

That works fine, but ideally I'd like to vendor this script and import it in a service where I can do my work on it. This does not work out of the box. Unfortunately, this script relies on being embedded with a script tag. If you unminify the thing, there's a line where it very explicitly tries to find the script tag that embedded it, and it throws an error if it can't find it.

From the unminified code:

findScriptTag: function() {
  for (var t = document.getElementsByTagName("script"), n = 0, e = t.length; n < e; n += 1)
    if (/link-initialize(\..*?)?\.js$/.test(t[n].src)) return t[n];
  throw new Error("Failed to find script")

My question is, can I configure ember to load certain vendored scripts separately from everything else, in its own script tag? I'd also need to control the name of the file, since the above expects the name to be link-initialize.js.

My current workaround is to just add the script tag to index.html, but I'd really like to be able to say import Plaid from 'plaid';, or something close to that... Unit testing is impossible without this.




Handlebars rendered in new line

I'm implementing Google strctured data using Ember and adding some dynamic values

  <script type="application/ld+json">
  [{
    "@context": "",
...

The rendered html is:

  <script type="application/ld+json">
  [{
    "@context": "  // ember adds new line before and after
         rendered-value-string
   ",
...




How do I render the components (iframe Rails view + React component) in my Ember view only after they have both finished loading?

I have an Ember view that returns both an iFramed Rails view and a React component. The React component sits below the iFrame and loads a lot quicker, so when it loads, it sits at the top of the page, then when the iFrame loads, it pushes it down. Because the iFrame takes a significantly longer amount of time than the React component, the page load looks unprofessional and janky. Is there a way to display both the elements at the same time? (This means the React component will have to wait until the iFrame loads)

The height of the iFrame is not set because it is dependent on the Rails view. It is simply set to display 100% of the Rails view. We don't want to set the height of the iFrame to a specific height because we want to cater it to different screens.

This is the code for the Ember view...

railsView: Em.computed(function() {
   return IFrameView.extend({
    src: '/farm/piglet'
   }).create();
}),

view: Em.computed(function() {
   const finalView = Ember.View.extend({
   reactComponent: 'structure/pigpen/piglet',
   railsView: this.get('railsView')
   })

   return finalView.create();
})

This is the handlebars template (structure/pigpen/piglet)...





I just want the Ember view to render both the Rails view and the React component at the same time.




mercredi 4 septembre 2019

How can I make a d3 force-directed graph recalculate its data after new data is inserted?

How do I make d3 format the newly inserted data correctly?

I am rendering a d3 force-directed graph. Double clicking on a node queries the server for connected nodes, which then get loaded back into the visualization.

The new links which are returned to the visualization are different than the original links which were created when the graph was initialized.

originalLink {
  id: "link1",
  index: 0,
   source: {
   color: "red",
   id: "node1",
   index: 0,
   name: "foo",
   vx: -0.06225449869763612,
   vy: -0.03959846823888954,
   x: 370.82436128143144,
   y: 280.0751827341487,
  },
  target: {
   color: "blue",
   id: "node2",
   index: 1,
   name: "bar",
   vx: -0.0624571225601514,
   vy: -0.039687630351824134,
   x: 368.8209911223153,
   y: 247.40939254717912,
  }
}


newLink: {
 id: "newLink1"
 source: "newNode1"
 target: "node2"
}

As far as I can tell, this formatting gets done here

let linkForce = d3.forceLink().id(link => link.id)

Here's a fiddle with a simplified version. New nodes and links are added in the application controller https://ember-twiddle.com/9059457d928f3e219d7370dc0e6f4d10?openFiles=controllers.application.js%2Ctemplates.components.force-graph.hbs

When new nodes/links are added, I am getting Uncaught TypeError: Cannot create property 'vx' on string 'node2'




Disable Ember Mirage when running tests in the browser

I would like to be able to run tests against my Mirage server, and my actual server in turn.

I've read these docs on disabling Mirage, and it works as expected for the development environment. Adding the code below disables Mirage at http://localhost:4200.

 ENV['ember-cli-mirage'] = {
    enabled: false
  };

However, this does not disable mirage when running tests in the browser at http://localhost:4200/tests.

I have added the code above outside of any of the environment specific conditionals, so it should apply to all environments. For good measure, I have also tried adding the code above inside each of the three environment specific conditionals as well:

 ENV['ember-cli-mirage'] = {
    enabled: false
  };

if (environment === 'production') {
  ENV['ember-cli-mirage'] = {
    enabled: false
  };
}
if (environment === 'development') {
  ENV['ember-cli-mirage'] = {
    enabled: false
  };
}
if (environment === 'test') {
  ENV['ember-cli-mirage'] = {
    enabled: false
  };
}

http://localhost:4200/tests still uses Mirage.

Is there a way to disable Mirage when testing in the browser? I would like to be able to enable it easily, so uninstalling Mirage is not an option.




mardi 3 septembre 2019

Ember 3.12: Cancel subscription for event from service

The following used to work:

export default Route.extend({
  device: service(),

  activate() {
    this._super(...arguments);

    let device = get(this, 'device');
    device.one('change', this, this._onDeviceChange);
  },

  _onDeviceChange() {
    // ...
  },

  deactivate() {
    this._super(...arguments);

    let device = get(this, 'device');
    device.off('change', this, this._onDeviceChange);
    },
});

But "now" (in v3.12 here, most probably since a couple of versions) I get

Error: Assertion Failed: You attempted to remove a function listener which did not exist on the instance, which means you may have attempted to remove it before it was added.

By removing the device.off()-part the error is gone, but I wonder: Is off() optional? Will removing off() produce some kind of leak? Why does the listener "not exist on the instance" anyway?

PS: I tried to off the listener before calling _super, but no difference...




lundi 2 septembre 2019

Connecting firebase from ember gets firebase.app is not a function getApp

I am working in an Ember.js app and currently trying to connect to firebase (is not my default adapter, the default is a Rest adapter). I followed the instructions given in https://github.com/firebase/emberfire but when I try to read data from the database I get:

Error while processing route: my.routingFile firebase.app is not a function getApp

In brief, this is my routing file:

import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import RouteMixin from 'ember-cli-pagination/remote/route-mixin';
import Ember from 'ember';
import RealtimeRouteMixin from 'emberfire/mixins/realtime-route';

export default Ember.Route.extend(AuthenticatedRouteMixin,RouteMixin, RealtimeRouteMixin, {

    firebaseApp: Ember.inject.service(),
    model(params) {
      return this.store.findAll('myModel');
    },

    setupController(){
      this._super(...arguments);
    },

    actions:{
    }
});

And, my adapter is defined as follows:

import RealtimeDatabaseAdapter from 'emberfire/adapters/realtime-database';

export default RealtimeDatabaseAdapter.extend({
  databaseURL: 'https://my-url.firebaseio.com/'
});

My ember-cli version is: 3.0.2

Then, what am I missing?




dimanche 1 septembre 2019

Remember me with OAuth2 in SPA

I know the concept of OAuth2 and OpenID. in our application authentication is happening through OKTA and we receive access-token in a response. Our architecture is a microservice-architecture and we are using EmberJS at frontend.
we have to implement remember-me functionality it will keep the user logged in for the next 30 days. I did some study on it and came to points that will satisfy my requirements.

  1. keep user session active for 30 days in OKTA.
  2. refresh access token periodically based on its expiry time.

How this refreshing will work if browser is closed? Let's say a user is logged in and closed the browser then reopened it after 3 days.