mardi 31 août 2021

How to call a route function in Ember js controller function test?

I have an ember js controller function onRefreshClicked which call a function inside the route refreshData.

I would like to run a unit/integration test for this controller's function, but then it cannot find the link to the route's function and error out.

How do I do this in ember v3.2.x?

addon/controllers/scan-monitor.js

import { action } from '@ember/object';
export default class ScanMonitorController extends Controller {

  @action
  onRefreshClicked(clickEvent) {
    debugger;
    clickEvent.preventDefault();
    // Some extra logic
    this.send('refreshData'); // ----> ERROR OUT!
  }
}

addon/routes/scan-monitor.js

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class ScanMonitorRoute extends Route {
  @service store;

  @action
  refreshData() {
    debugger;
    this.refresh();
  }
}

tests/unit/controllers/scan-monitor-test.js

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Controller | scan-monitor', function (hooks) {
  setupTest(hooks);

  let scanMonitorController;

  hooks.beforeEach(function () {
    scanMonitorController = this.owner.lookup('controller:scan-monitor');
  });

  test('controllers.scan-monitor.onRefreshClicked', function (assert) {
    debugger;
    // Assigning or not assigning the route doesn't make any difference.
    // scanMonitorController.route = this.owner.lookup('route:scan-monitor');

    scanMonitorController.onRefreshClicked(new MouseEvent('click', {}));

    assert.ok(scanMonitorController);
  });
});

The error

TypeError: Cannot read property 'trigger' of undefined
    at Router.send (http://localhost:7357/assets/vendor.js:31600:28)
    at ScanMonitorController.send (http://localhost:7357/assets/vendor.js:34358:16)
    at ScanMonitorController.onRefreshClicked (http://localhost:7357/assets/vendor.js:173217:12)
    at Object.<anonymous> (http://localhost:7357/assets/tests.js:527:29)



lundi 30 août 2021

memory leak issues after upgrading ember cli from 3.4.3. to 3.24.0

We are facing an issue on JS heap size grows substantially over time, indicating a memory leak after ember upgrade to 3.24.0, DOM nodes also increase seemingly without bound.

Over time, our test cases are failing due to shortage of node memory and few apps are working after setting the node --max-old-space-size=8192 whereas few apps are not working after increasing node space

Environment • Ember 3.24.0 (upgraded version ) • Node.js/npm: node 12.22.1, npm 6.14.12 • Browser: Chrome We are seeking the help to find the right direction to fix the issue

Note: Due to security concerns, we cant share more info/code snippet/part of our code here.

Thanks,




samedi 28 août 2021

what is this syntax meaning in javascript function [duplicate]

I am beginner for javascript, there's a function call that the syntax I don't understand:

Suppose I have a list of products and each product has id 1,2..

export default class ItemRoute extends Route {
  model(params) {
    const { item_id } = params;
    const product = products.find(({ id }) => id === item_id);
    return product;
  }
}

I am confused: what is ({ id }) => id doing? Is this another function like: function getId(id) and it returns the id?, why we can't directly doing like that: product.find(id === item_id)?




mardi 24 août 2021

How to pass parameters to an ember component?

I'm still new in ember js and currently using ember version 3.2.6.

I cannot seem to pass parameter to ember component, what did I missed?

app/templates/application.hbs

<UserCard
  @userName='James123'
  @firstName='James'
  @lastName='Smith'
/>
<UserCard
  @userName='Jane123'
  @firstName='Jane'
  @lastName='Smith'
/>

app/components/user-card.hbs

<br/>
<strong>User Card</strong><br/>
<label>UserName: </label><br/>
<label>First Name: </label><br/>
<label>Last Name: </label><br/>

Result

enter image description here




dimanche 22 août 2021

When trying to authenticate, doorkeeper returns a 401 error "Client authentication failed due to unknown client, no client authentication included..."

So, I'm building an application using Rails for the backend and Ember.JS for one of the clients. I used CodingItWrong's apiup and emberup to generate project directories with some stuff pre-installed. I'm working on authentication currently, and OAuth2 is what apiup configures Rails to use. So, loosely watching the VOD of the stream where he implemented this, I tried to implement it myself. However, every time I'd send a request to the Rails server (via ember-simple-auth [ESA]), I would get an HTTP 401 with the JSON response:

{
    "error": "invalid_client",
    "error_description": "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method."
}

This surprised me, as ESA is meant to support OAuth2 out-of-the-box (and I'm sure it does-I did something wrong here!!). So, what would typically cause doorkeeper to send an error like this? Here is some of the troubleshooting I tried:

  • I checked to make sure the database query used was good (manually via psql)
  • I checked to make sure the doorkeeper authenticate statement worked (it did):
Doorkeeper.configure do
  # Change the ORM that doorkeeper will use (needs plugins)
  orm :active_record

  grant_flows %w[password]

  resource_owner_from_credentials do
    user = User.find_by(email: params[:username])
    if user&.authenticate(params[:password])
      puts 'Authentication Success'
      user
    else
      raise Doorkeeper::Errors::DoorkeeperError.new('invalid_user_or_password')
    end
  end

...

And low and behold, "Authentication Success" was printed to the console.

  • I checked my Ember app to make sure the host was correct (https://localhost:3000)

One thing I'm not 100% sure on is what the token endpoint is by default on doorkeeper? Ember has it set as '/oauth/token', generated by emberup.

Thank you so much for hearing me out :)

If you need any more code to help diagnose this, please let me know and I can edit this question.

Thanks!




assign Ember component variable with a Map

I have an Ember Component, Inside it, I declared a variable and after that I put a map inside the variable like this:

const SubscriptionForm = Ember.Component.extend({
     messagesFilter: Ember.Map.create(),
     
      init() {
          this.set('messagesFilter', this.getMessagesFilter());

and this is the getMessagesFilter function:

  getMessagesFilter() {
     let map = new Map();
     for (var i = 0; i < this.get('availableMessages').length; i++){
       let array = [];
       map.set(this.get('availableMessages').get(i), array);
     }

   return map;
 },

I verified that getMessagesFilter return a map with data inside. I don't undestand why when I do console.log(this.get('messagesFilter')) returns undefined.

Could someone help me with this?




samedi 21 août 2021

Cannot read property 'type' of undefined ember and firebase

I am trying to retrieve data from my firestore using ember.js and emberfire.

i have a simple movie database. All that is in it right now is 1 document but for some reason when i try and retrieve the data, i keep getting "Cannot read property 'type' of undefined"! i understand that this is a JSONAPI issue but nothing seems to fix it.

My Route:

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

export default class MovieRoute extends Route {
  async model() {
    this.store.findAll('movies').then(function(movie) {
      console.log(movie);
    });
  }
}

My Model:

import Model, { attr } from '@ember-data/model';

export default class MoviesModel extends Model {
  @attr('string') title;

}

Now it was my understanding that the default JSONAPISerializer is the default one but i tried adding a serializer anyway and my error changes to: Assertion Failed: normalizeResponse must return a valid JSON API document.

My adapter:

import FirestoreAdapter from 'emberfire/adapters/firestore';

export default FirestoreAdapter.extend({
  // Uncomment the following lines to enable offline persistence and multi-tab support
  // enablePersistence: true,
  // persistenceSettings: { synchronizeTabs: true },
});

My Serializer:

import JSONAPISerializer from '@ember-data/serializer/json-api';

export default class ApplicationSerializer extends JSONAPISerializer {}

it is also my understanding that the way the JSON is to be accepted is:

{
  data {
    type: 'movies',
    id: 1,
    attributes {
      title: 'ghostbusters'
    }
  }
}

so i also created a new document in the firestore, following this same format. Still no luck.

Can anyone point me in the right direction as to how to get the correct data returning from the firestore?




vendredi 20 août 2021

How to get Ember to detect a checkbox on change along with a glimmer tracked?

In ember js version 3.2.6, how do we get a checkbox to do extra logic on value changed?

Example, I have a checkbox (a toggle true/false) for updateServer. The existing code is using a glimmer @tracked and this work fine for showing some instant UI modification as can be seen on the application.hbs.

Value of update server:
 

But then I need to add some logic on value change, see onCheckboxChange. That function is called, but it seem the value of updateServer is not the one after click. It's the older one, before click. See picture.

How do I get the latest value of updateServer?

The value of update server is not the latest ones

application.js

import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  @tracked updateServer = false;

  @action
  onCheckboxChange() {
    //some extra logic
    console.log(`at controller, updateServer is: ${this.updateServer}`);
  }
}

application.hbs



<label>
  <Input @type='checkbox' @checked= />
  Update Server</label>
<br />
Value of update server:

<br />




EmberJS: Cannot read property '_application' of undefined

I'm working through the emberJS tutorial and every time I update the code it crashes with the following error:

Uncaught TypeError: Cannot read property '_application' of undefined
    at appStarted (<anonymous>:9601:45)
    at Object.initialize (<anonymous>:9721:11)
    at index.js:136
    at Vertices.each (dag-map.js:231)
    at Vertices.walk (dag-map.js:145)
    at DAG.each (dag-map.js:75)
    at DAG.topsort (dag-map.js:83)
    at App._runInitializer (index.js:151)
    at App.runInstanceInitializers (index.js:134)
    at Class._bootSync (instance.js:111)

The only way to get rid of it is to keep restarting the server. Any idea what is going on?




jeudi 19 août 2021

How to access in `this.owner` as a property in Ember js test?

I added an ember adapter with some extra logic, then I would like to test that logic in ember test.

In the test file, I see this line repeated multiple times let adapter = this.owner.lookup('adapter:assessment'); inside each test.

I would like to move that line into a class level attribute for accessing my adapter. How do I do that? I think it has something to do with this.owner.lookup is only accessible within test().

(Using ember js 3.2.6)

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Adapter | assessment', function (hooks) {
  setupTest(hooks);
  let myVar = 'abc';
  let adapterVar = this.owner.lookup('adapter:assessment'); // This fails! How to do this correctly?

  test('it exists', function (assert) {
    let adapter = this.owner.lookup('adapter:assessment');
    console.log(myVar); // This works!
    assert.ok(adapter);
  });

  test('Test 1', function (assert) {
    let adapter = this.owner.lookup('adapter:assessment');
    console.log(myVar);      // This works!
    console.log(adapterVar); // This fails!
    assert.ok(adapter);
  });

  test('Test 2', function (assert) {
    let adapter = this.owner.lookup('adapter:assessment');
    console.log(myVar);      // This works!
    console.log(adapterVar); // This fails!
    assert.ok(adapter);
  });

  test('Test 3', function (assert) {
    let adapter = this.owner.lookup('adapter:assessment');
    console.log(myVar);      // This works!
    console.log(adapterVar); // This fails!
    assert.ok(adapter);
  });

});





How to get cookies (basically I need jwt token) in Ember.js which was set in Django?

Django Rest Framework

class LoginView(APIView):
        password = request.data['password']
        user = User.objects.filter(email=request.data['email']).first()

        if user is None:
            return Response({
                'success': False,
                'message': 'Username or password is invalid',
                'errors': 'Username or password is invalid',
            }, status=status.HTTP_401_UNAUTHORIZED)

        if not user.check_password(password):
            return Response({
                'success': False,
                'message': 'Username or password is invalid',
                'errors': {'username-or-password': ['Username or password is invalid']},
            }, status=status.HTTP_401_UNAUTHORIZED)

        payload = {
            'id': user.id,
            'iat': datetime.datetime.utcnow()
        }

        token = jwt.encode(payload, 'secret', algorithm='HS256')
        response = Response()
        response.set_cookie(key='token', value=token, httponly=True)

        response.data = {
            'success': True,
            'data': {
                'token': token
            }
        }
        return response

Here I send token in response data and also set token in cookies.

How can I get/receive/retrieve token from cookies in Ember.js?




mercredi 11 août 2021

Babel deoptimises styling of big files in ember.js app

I have an ember.js app with a big file that started to have this problem:

[Babel: notes > applyPatches][BABEL] Note: The code generator has deoptimised the styling of /home/user/code/notes-frontend/notes/components/model-wps/edit.js as it exceeds the max of 500KB.

Although the functionality is not affected, this makes it impossible to debug as Babel won't print the file nicely.

I've seen that setting babel compact option to false should solve my problem, but I can't make that configuration work in my project.




lundi 9 août 2021

What is the best way to mock ember services that use ember-ajax in ember-cli-storybook to post and fetch data?

I'm using Ember CLI Storybook to create a story of a component than internally relies upon services that communicate to the internet, to fetch and post information to the backend. The way I'm doing that is using ember-ajax.

I see how to mock an ember model from this section but wondering if there is a workaround for ember ajax service.




dimanche 8 août 2021

Ember-qunit Unit test failed with Global error Ajax aborted

Does anyone meet this issue before? I am running a unit test for ember-qunit from my local, get this global error, and the Ajax was aborted. Thanks!

ok 1 Chrome 92.0 - [1 ms] - ESLint | app: services/something.js
ok 2 Chrome 92.0 - [0 ms] - ESLint | tests: unit/services/something-test.js
not ok 3 Chrome 92.0 - [undefined ms] - Global error: Uncaught Error: The ajax operation was aborted at http://localhost:7357/assets/vendor.js, line 36784
 While executing test: Unit | Service | something: should correctly concat foo
    ---
        browser log: |
            testContext: [object Object]
            ERROR: Uncaught Error: The ajax operation was aborted at http://localhost:7357/assets/vendor.js, line 36784

    ...
not ok 4 Chrome - [undefined ms] - error
    ---
        message: >
            Error: Browser timeout exceeded: 10s
            Error while executing test: Unit | Service | something: should correctly concat foo
            Stderr:

            DevTools listening on ws://127.0.0.1:9222/devtools/browser/53946c78-c3da-4f52-9744-bd71040066fc


        browser log: |
            [object Object]
            [object Object]
            [object Object]
    ...

1..4
# tests 4
# pass  2
# skip  0
# fail  2
Testem finished with non-zero exit code. Tests failed.



vendredi 6 août 2021

How to modify the google sitelinks of an ember app?

enter image description here

For example, I want to limit the sitelinks like I want to show Log In an Business only. Is there a way in the code of ember app to modify the contents and the links to show in google?




jeudi 5 août 2021

How to properly deploy Ember.js App to Azure App Service using Azure CI/CD Pipeline?

I have a simple Ember.js single page web application that was created using this Ember.js tutorial (finished part 1 & 2):

Ember.js Tutorial

I am now trying to get familiar with Azure CI/CD pipelines by first creating an Azure DevOps Git Repo for the application, then a Build pipeline that is triggered by a push to the Git Repo, and finally a Release pipeline to publish the site to an Azure App Service after the build has succeeded.

The build and release pipelines both succeed, but when I visit the site, it shows a blank node.js page:

Blank node.js page

Can someone help me figure out where I went wrong here? My guess is it has to do with something in the configuration of the build and/or the release pipeline. Just can't seem to find what specific part is not correct. Any help is much appreciated. I can provide more information if needed :)

Here are my configurations for the build pipeline

  1. YAML code for build pipeline
    # Build a general Node.js project with npm.
    # Add steps that analyze code, save build artifacts, deploy, and more:
    # https://docs.microsoft.com/azure/devops/pipelines/languages/javascript
    
    trigger:
    - master
    
    pool:
      vmImage: ubuntu-latest
    
    steps:
    - task: NodeTool@0
      inputs:
        versionSpec: '6.x'
        checkLatest: true
    
    - task: Npm@1
      inputs:
        command: 'install'
        workingDir: 'app/'
    
    - task: ArchiveFiles@2
      inputs:
        rootFolderOrFile: '$(System.DefaultWorkingDirectory)'
        includeRootFolder: true
        archiveType: 'zip'
        archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'
        replaceExistingArchive: true
    
    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

Here is the configuration in the Release Pipeline

  1. Artifact Configuration

artifact configuration

  1. Continuous deployment configuration

continuous deployment configuration

  1. Stage 1: Deployment Process

enter image description here

  1. Agent Job

enter image description here enter image description here

  1. YAML for Deploying to Azure App Service
steps:
- task: AzureRmWebAppDeployment@4
  displayName: 'Deploy Azure App Service'
  inputs:
    azureSubscription: '$(Parameters.ConnectedServiceName)'
    appType: '$(Parameters.WebAppKind)'
    WebAppName: '$(Parameters.WebAppName)'
    RuntimeStack: 'NODE|14-lts'
    StartupCommand: '$(Parameters.StartupCommand)'
    WebConfigParameters: '-Handler iisnode -NodeStartFile server.js -appType node'
    AppSettings: '-WEBSITE_NODE_DEFAULT_VERSION 6.9.1'

I would also like to mention that the Azure App Service stack setting is Node 14 and is running on linux.

Thanks!




lundi 2 août 2021

ember-simple-auth user stays logged in despite browser relaunch

For some reason my user is still logged in despite closing my Safari browser.

These are the versions of Ember & stuff that I'm using:

ember-cli: 3.25.3
node: 14.16.0
os: darwin x64

This is my authentication code:

this.session.authenticate('authenticator:devise', this.fields.email, this.fields.password)

And this is my app/services/session.js file:

import { inject as service } from '@ember/service';
import BaseSessionService from 'ember-simple-auth/services/session';

export default class SessionService extends BaseSessionService {
  @service currentUser;

  async handleAuthentication(routeAfterAuthentication) {
    try {
      await this.currentUser.load();
      super.handleAuthentication(...arguments);
    } catch(err) {
      await this.invalidate();
    }
  }
}

and I'm checking my logged in status via:

this.session.isAuthenticated

It says here https://ember-simple-auth.com/api/classes/CookieStore.html that:

By default the cookie session store uses a session cookie that expires and is deleted when the browser is closed.

So how come my user is still authenticated despite closing my browser - any ideas or suggestions?