mercredi 29 décembre 2021

Is it even possible to run an ember 2.18 application in this decade?

I have to make some adjustments to the project done with ember 2.18.2, and it is a complete disaster right now.

I'm using macOS BigSur(11.6) and this is the pckage.json:

"body-parser": "^1.15.2",
"broccoli-asset-rev": "^2.4.5",
"ember-ace": "1.3.2",
"ember-ajax": "^3.0.0",
"ember-browserify": "^1.2.1",
"ember-changeset": "1.2.0",
"ember-changeset-validations": "1.2.4",
"ember-cli": "2.18.2",
"ember-cli-app-version": "^3.0.0",
"ember-cli-babel": "^6.6.0",
"ember-cli-clipboard": "0.13.0",
"ember-cli-dependency-checker": "^2.0.0",
"ember-cli-eslint": "^4.2.1",
"ember-cli-head": "^0.4.1",
"ember-cli-htmlbars": "^2.0.1",
"ember-cli-htmlbars-inline-precompile": "^1.0.0",
"ember-cli-inject-live-reload": "^1.4.1",
"ember-cli-markdown-editor": "^0.1.0",
"ember-cli-mirage": "0.2.9",
"ember-cli-moment-shim": "2.0.0",
"ember-cli-page-object": "1.8.0",
"ember-cli-qunit": "4.2.1",
"ember-cli-release": "^0.2.9",
"ember-cli-sentry": "3.0.0-beta.1",
"ember-cli-shims": "^1.2.0",
"ember-cli-spinner": "0.0.9",
"ember-cli-sri": "^2.1.0",
"ember-cli-stylus": "1.0.6",
"ember-cli-uglify": "^2.0.0",
"ember-click-outside": "1.3.0",
"ember-data": "2.18.2",
"ember-data-has-many-query": "0.2.0",
"ember-export-application-global": "^2.0.0",
"ember-file-upload": "^3.0.5",
"ember-font-awesome": "3.1.1",
"ember-inflector": "^3.0.1",
"ember-intercom-io": "0.1.4",
"ember-load-initializers": "^1.0.0",
"ember-maybe-import-regenerator": "0.1.6",
"ember-metrics": "0.14.0",
"ember-modifier-manager-polyfill": "^1.2.0",
"ember-moment": "7.0.0-beta.3",
"ember-power-select": "1.10.4",
"ember-power-select-with-create": "0.4.0",
"ember-qunit": "3.3.0",
"ember-radio-buttons": "4.1.0",
"ember-resolver": "^4.0.0",
"ember-route-action-helper": "2.0.6",

As far as I understood I need watchman 4.9 for this project, which I tried to install from their git, by using something like this:

  1. git clone https://github.com/facebook/watchman.git (or download zip file from link above) ,
  2. cd watchman ,
  3. git checkout v4.6.0 ,
  4. ./autogen.sh ,
  5. ./configure ,
  6. make ,
  7. sudo make install

I can't install this version, since step 4 starts to break, and the thread regarding the issue contains absolutely nothing.

I tried to use autoconf to compile it, but still, same errors as from the git issue above.

So my question is simple, can I run it? Maybe avoid using watchman at all?




dimanche 26 décembre 2021

Ember js Build Error (broccoli-persistent-filter:EslintValidationFilter)

After cloning the repository from Github then install npm and try to execute ember s. but I got this error. Then I delete node modules directory and package-lock.json file and install npm again. But i can't solve it.I am googling this error but can't solve it. Plz, Help me. Here is my Error:

Build Error (broccoli-persistent-filter:EslintValidationFilter) in helpers/flash- 
message.js

Package subpath './lib/util/traverser' is not defined by "exports" in 
/home/ag/Office/ecommerce/front-end/node_modules/eslint/package.json


Stack Trace and Error Report: /tmp/error.dump.a671c24c39f689554c47c73d068f7e9f.log

My Package.json:

{
"name": "front-end",
"version": "0.0.0",
"private": true,
"description": "Small description for front-end goes here",
"repository": "",
"license": "MIT",
"author": "",
"directories": {
"doc": "doc",
"test": "tests"
},
"scripts": {
"build": "ember build",
"lint:hbs": "ember-template-lint .",
"lint:js": "eslint .",
"start": "ember serve",
"test": "ember test"
},
"devDependencies": {
"@ember/jquery": "^0.6.0",
"@ember/optional-features": "^0.7.0",
"broccoli-asset-rev": "^3.0.0",
"ember-ajax": "^5.0.0",
"ember-aria-tabs": "^3.0.0",
"ember-auto-import": "^1.10.1",
"ember-cli": "~3.12.0",
"ember-cli-app-version": "^3.2.0",
"ember-cli-babel": "^7.7.3",
"ember-cli-bootstrap-4": "^0.12.0",
"ember-cli-dependency-checker": "^3.1.0",
"ember-cli-eslint": "^5.1.0",
"ember-cli-flash": "^2.1.0",
"ember-cli-form-data": "^2.1.1",
"ember-cli-htmlbars": "^3.0.1",
"ember-cli-htmlbars-inline-precompile": "^2.1.0",
"ember-cli-inject-live-reload": "^1.8.2",
"ember-cli-moment-shim": "^3.8.0",
"ember-cli-sass": "^10.0.1",
"ember-cli-shims": "^1.2.0",
"ember-cli-sri": "^2.1.1",
"ember-cli-swiper": "^1.0.6",
"ember-cli-template-lint": "^1.0.0-beta.1",
"ember-cli-uglify": "^2.1.0",
"ember-composable-helpers": "^2.4.0",
"ember-concurrency": "^1.3.0",
"ember-cp-validations": "^4.0.0-beta.12",
"ember-crumbly": "^3.0.1",
"ember-data": "~3.12.0",
"ember-drag-drop": "^0.9.0-beta.0",
"ember-export-application-global": "^2.0.0",
"ember-fetch": "^8.1.0",
"ember-font-awesome": "^4.0.0-rc.4",
"ember-load-initializers": "^2.0.0",
"ember-local-storage": "^1.7.2",
"ember-maybe-import-regenerator": "^0.1.6",
"ember-modal-dialog": "^3.0.1",
"ember-moment": "^8.0.1",
"ember-pickr": "^2.2.1",
"ember-power-select": "^3.0.2",
"ember-qunit": "^4.4.1",
"ember-resize": "^0.3.4",
"ember-resolver": "^5.0.1",
"ember-source": "~3.12.0",
"ember-toggle": "^7.1.0",
"ember-tooltips": "^3.4.5",
"ember-uuid": "^2.1.0",
"ember-welcome-page": "^4.0.0",
"eslint-plugin-ember": "^6.2.0",
"eslint-plugin-node": "^9.0.1",
"loader.js": "^4.7.0",
"popper.js": "^1.16.1",
"qunit-dom": "^0.8.4",
"sass": "^1.30.0"
},
"engines": {
"node": "8.* || >= 10.*"
},
"dependencies": {
"drift-zoom": "^1.5.0"
}
}

If anyone has any idea about this error then comment or answer it. I will vote and accept the answer.




vendredi 24 décembre 2021

Component in a loop does not show the last component in ember js

I'm a beginner to ember js. Here I'm looping a component called colored-box in the 'reading.hbs' file. This loop of components shows all the other elements with relevant properties. But the last element is not showing. In the component js file, I have used observes method with init. I'm downloading a pdf which is generated using the html rendered with this code with pdfReadctor. I got this issue in the downloaded pdf. I have attached the image of the place where I have the issue. I can't figure out what the reason is. Can anyone please help me to figure out the problem? Below I have attached the code.

Figure 1.) reading.hbs enter image description here

Figure 2.) colored-box.hbs - component file enter image description here

Figure 3.) colored-box.js enter image description here

enter image description here




jeudi 16 décembre 2021

EmberJs new project throws Decorating class property failed

I tried to use ember cli to generate local project, but when visiting localhost:4200, I met below errors:

Error occurred:

- While rendering:
  -top-level
    application

Uncaught Error: Decorating class property failed. Please ensure that proposal-class-properties is enabled and runs after the decorators transform.

and ember -v gives this:

ember-cli: 3.28.4
node: 16.13.1
os: darwin x64

Please help to point out the reason.

Thanks




samedi 11 décembre 2021

Ember Octane on 'keyup' or 'keydown' is not firing

I have a glimmer Component in an Ember Octane app like this

import Component from '@glimmer/component';
import { action } from '@ember/object';


export default class TestComponent extends Component {
  @action
  handleEvent(event) {
    console.log(event);
  }
}

and in my HTML I have

<div ></div>

but handleEvent is not firing even when changing to 'keyDown' for example. It says in the documentation

The event can be any event name, not just the click event, which makes perfect for handling any kind of DOM event. For a list of native browser events, see the MDN documentation

But that doesn't seem to be true!

Is there an "Ember way" to handle keyboard events without installing an outer library (modifier) or should I stick with native event listeners?




mardi 7 décembre 2021

What is the windows cmd equivalent of the command target=mock country=UK ember s?

How can we write the same command

target=mock country=UK ember s

in windows command prompt?

Are we supposed to use any of these?

ember s & target=mock & country=UK
ember s && target=mock && country=UK



samedi 4 décembre 2021

Is using an api server like rest for my backend a secure way?

Nowadays I see websites are made using a sperate api backend server which provides the data from the database called a REST API server. When I was at school they taught me how to connect to apache using php to access the database!! I was thinking is this is safe (using api)?? Like if I have such an api which gives data from the database anyone can request a direct api call and steal that data. I know there is something called api token and private apis. But if somehow someone manages to break that then the my server will make all data public. Isnt the old method more safe because only my website has access to the database. I just want to know how exactly does this backend rest api works? I had done a project and my rest api can be accessed by anyone using my websites url.

Please someone explain the foundation of using such separate app for backend




vendredi 3 décembre 2021

Emberjs : Open modal from otther modal only when the first has left the DOM

I use Emberjs 3.19.0 (actually I can't change the version) whith "ember-modal-dialog": "^3.0.0-beta.4".

In my index.hbs I have 2 buttons which allow me to open 2 different modals. These modals have different models but both have a captcha generated on the fly, I want to be able to initiate the opening of a modal from another modal. I am having an issue with the source modal lifecycle that causes the target modal's captcha to not load. I think the captcha is still part of the dom on the first modal.

Currently I am transmitting a function of the index.js to the first modal but I had to put a await new Promise(resolve => setTimeout(resolve, 400)); that allows me to wait until the first modal is completely outside the dom before opening the second. This solution is not clean, I ask you if you have another idea?




ember-cordova - Invalid or unexpected token on __dirname

I'm trying to build Android app using my Ember frontend and Cordova.

  1. I've configured project as described in ember-cordova docs (changed rootURL and locationType),
  2. I installed ember-cordova via ember install ember-cordova,
  3. Changed app name and widget id in cordova/config.xml,
  4. Added required platform - ember cdv:platform add android,
  5. And I'm trying to build first version of my app using ember cdv:build --platform=android --environment=production.

Unfortunatelly, build fails with error:

EmberCordovaError: Invalid or unexpected token


Stack Trace and Error Report: /tmp/error.dump.0bfefb855ac286c6b6600c600e92d126.log

It happens both on Ubuntu 21.10 and macOS Monterey. I'm using node v12.22.7 installed via node version manager (tried using node from apt packages on Ubuntu, but it didn't help), ember-cordova v1.0.9, and ember v3.12.1.

Full error log:

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

ENV Summary:

  TIME: Fri Dec 03 2021 12:37:28 GMT+0100 (GMT+01:00)
  TITLE: ember
  ARGV:
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin/node
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin/ember
  - cdv:build
  - --platform=android
  - --environment=production
  EXEC_PATH: /home/tomasz/.nvm/versions/node/v12.22.7/bin/node
  TMPDIR: /tmp
  SHELL: /bin/bash
  PATH:
  - /home/tomasz/.rvm/gems/ruby-3.0.3/bin
  - /home/tomasz/.rvm/gems/ruby-3.0.3@global/bin
  - /home/tomasz/.rvm/rubies/ruby-3.0.3/bin
  - /home/tomasz/.rvm/bin
  - /home/tomasz/.local/bin
  - /home/tomasz/bin
  - /home/tomasz/.nvm/versions/node/v12.22.7/bin
  - /home/tomasz/.local/bin
  - /home/tomasz/bin
  - /usr/local/sbin
  - /usr/local/bin
  - /usr/sbin
  - /usr/bin
  - /sbin
  - /bin
  - /usr/games
  - /usr/local/games
  - /snap/bin
  - /home/tomasz/.rvm/bin
  PLATFORM: linux x64
  FREEMEM: 18971971584
  TOTALMEM: 33553645568
  UPTIME: 4862
  LOADAVG: 6.15,4.98,3.74
  CPUS:
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3505
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3565
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3800
  - Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz - 3800
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.17.2
  - brotli: 1.0.9
  - cldr: 37.0
  - http_parser: 2.9.4
  - icu: 67.1
  - llhttp: 2.1.4
  - modules: 72
  - napi: 8
  - nghttp2: 1.41.0
  - node: 12.22.7
  - openssl: 1.1.1l
  - tz: 2019c
  - unicode: 13.0
  - uv: 1.40.0
  - v8: 7.8.279.23-node.56
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: [undefined]
  - code: [undefined]
  - codeFrame: [undefined]
  - errorMessage: EmberCordovaError: Invalid or unexpected token
  - errorType: [undefined]
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
  - message: EmberCordovaError: Invalid or unexpected token
  - name: EmberCordovaError
  - nodeAnnotation: [undefined]
  - nodeName: [undefined]
  - originalErrorMessage: [undefined]
  - stack: (function (exports, require, module, __filename, __dirname) { #!/usr/bin/env node
                                                              ^

SyntaxError: Invalid or unexpected token
    at new Script (vm.js:88:7)
    at createScript (vm.js:261:10)
    at Object.runInThisContext (vm.js:309:10)
    at wrapSafe (internal/modules/cjs/loader.js:902:15)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Api.getPlatformInfo (/home/tomasz/Projects/app-ember/ember-cordova/cordova/platforms/android/cordova/Api.js:174:22)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/src/cordova/prepare.js:53:67
    at Array.map (<anonymous>:null:null)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/src/cordova/prepare.js:51:43
    at _fulfilled (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:787:54)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:816:30
    at Promise.promise.promiseDispatch (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:749:13)
    at /home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:557:44
    at flush (/home/tomasz/Projects/app-ember/node_modules/cordova-lib/node_modules/q/q.js:108:17)
    at processTicksAndRejections (internal/process/task_queues.js:79:11)


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

What could be a reason of such a failure?




dimanche 28 novembre 2021

Find-by with multiple attribute in Ember.js Octane

I have a route with RSVP that load several models (categories with items, treatments, prices) which return in JsON API Forrmat and want to show them in a table:

Item Name Treatment Name 1 Treatment Name N
Category 1
Item 1 in Cat 1 Price item 1 in Cat 1 for Treatment 1 Setup Price
Item 2 in Cat 1 Setup Price Price item 2 in Cat 1 for Treatment N
Category 2
Item 1 in Cat 2 Price item 1 in Cat 2 for Treatment 1 Price item 1 in Cat 2 for Treatment N

Setup Price only show if there isn't any price found, so the user can setup the price for the item in that treatment

I already can iterate the categories, items and treatment; but still do not know how to configure to show the correct price.

How can I find the correct prices by 2 attributes? I tried using find-by helper in the template:


  

, but it seems it only support 1 attributes.

Well, if in SQL it would be something like:

select * from prices where item.id = [currentItemId] and treatment.id = [currentTreatmentId]

but I want it to search in the already loaded price model...

Any help ? thank you...




jeudi 25 novembre 2021

Ember Upgrade from 3.23 to 3.24 failing at build

Was planning to migrate ember application from 3.23 to 3.24. During ember serve the following error is coming:

I have tried upgrading broccoli and babels libs to the latest version. Still the issue persists.

ERROR Summary:

  - broccoliBuilderErrorStack: TypeError: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
    at PluginPass.ClassBody (/home/abc/dev/sample-ui/node_modules/@babel/plugin-proposal-class-static-block/lib/index.js:56:21)
    at newFn (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/visitors.js:177:21)
    at NodePath._call (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:53:20)
    at NodePath.call (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:40:17)
    at NodePath.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:100:31)
    at TraversalContext.visitQueue (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:103:16)
    at TraversalContext.visitSingle (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:77:19)
    at TraversalContext.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:131:19)
    at Function.traverse.node (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/index.js:82:17)
    at NodePath.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:108:18)
  - code: [undefined]
  - codeFrame: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
  - errorMessage: @ember/test-helpers/-internal/debug-info.js: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
        in /home/abc/dev/sample-ui/node_modules/@ember/test-helpers/addon-test-support
        at broccoli-persistent-filter:Babel > [Babel: @ember/test-helpers] (Babel: @ember/test-helpers)
  - errorType: Build Error
  - location:
    - column: [undefined]
    - file: @ember/test-helpers/-internal/debug-info.js
    - line: [undefined]
    - treeDir: /home/abc/dev/sample-ui/node_modules/@ember/test-helpers/addon-test-support
  - message: @ember/test-helpers/-internal/debug-info.js: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
        in /home/abc/dev/sample-ui/node_modules/@ember/test-helpers/addon-test-support
        at broccoli-persistent-filter:Babel > [Babel: @ember/test-helpers] (Babel: @ember/test-helpers)
  - name: Error
  - nodeAnnotation: Babel: @ember/test-helpers
  - nodeName: broccoli-persistent-filter:Babel > [Babel: @ember/test-helpers]
  - originalErrorMessage: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
  - stack: TypeError: /home/abc/dev/sample-ui/ngcoreui/@ember/test-helpers/-internal/debug-info.js: path.isStaticBlock is not a function
    at PluginPass.ClassBody (/home/abc/dev/sample-ui/node_modules/@babel/plugin-proposal-class-static-block/lib/index.js:56:21)
    at newFn (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/visitors.js:177:21)
    at NodePath._call (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:53:20)
    at NodePath.call (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:40:17)
    at NodePath.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:100:31)
    at TraversalContext.visitQueue (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:103:16)
    at TraversalContext.visitSingle (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:77:19)
    at TraversalContext.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/context.js:131:19)
    at Function.traverse.node (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/index.js:82:17)
    at NodePath.visit (/home/abc/dev/sample-ui/node_modules/@babel/traverse/lib/path/context.js:108:18)



How to add swipe event in ember JS 3.27

I want some actions to be done when the screen is swiped down and I'm using ember version 3.27. Is this possible?




mardi 23 novembre 2021

How to do polling in Ember js component?

In ember js 3.24 LTS, I can create a component that receive data from an API call inside a route. The data from the API is an activity logs. The complexity arrives when I try to keep updating the logs with the latest logs, I need to keep polling the API every few seconds and I need to keep updating the data that being displayed inside the component.

  • How do I keep reloading the API call every few seconds and then update the display of the component?
  • I can use the ember later to keep looping/requery the API ever 2 seconds or 2000 ms, but then how do I tell my component to update the display?

This component gets data from an API call which is in the routes.

// addon/routes/single-scan/index.js 
import { later } from '@ember/runloop';
...
  async model() {
    let phaseActivityLog = await this.pollTestActivity(testId);
    return { phaseActivityLog };
  }

  async pollTestActivity(testId) {
    later(
      this,
      function () {
        this.pollTestActivity(testId);
      },
      2000
    );
    let phaseActivityLog = await this.store.query('phase-activity-log', testId, { reload: true }); // poll this
    return phaseActivityLog;
  }

And my component hbs

// components/single-scan/phase-activity-log.hbs


   -  - 




lundi 22 novembre 2021

Open one component instance at a time in Ember Octane

Let's say we have component answer that has isOpen property. By default isOpen is false and when the user is clicking on the answer we are changing the isOpen to true.

We are showing the list of answers. How can we close the first answer when the user clicks on second answer?

I was thinking about creating a service answersSync with globalIsOpen = false.




samedi 20 novembre 2021

DEPRECATION: Versions of modifier manager capabilities prior to 3.22 have been deprecated. You must update to the 3.22 capabilities

I got this warning on my Ember App :

DEPRECATION: Versions of modifier manager capabilities prior to 3.22 have been deprecated. You must update to the 3.22 capabilities. [deprecation id: manager-capabilities.modifiers-3-13] See https://deprecations.emberjs.com/v3.x#toc_manager-capabilities-modifiers-3-13 for more details. at logDeprecationStackTrace (http://localhost:4200/assets/vendor.js:36552:21) at HANDLERS. (http://localhost:4200/assets/vendor.js:36685:9) at raiseOnDeprecation (http://localhost:4200/assets/vendor.js:36579:9) at HANDLERS. (http://localhost:4200/assets/vendor.js:36685:9) at invoke (http://localhost:4200/assets/vendor.js:36697:9) at deprecate (http://localhost:4200/assets/vendor.js:36653:28) at modifierCapabilities$1 (http://localhost:4200/assets/vendor.js:11678:62) at http://localhost:4200/assets/vendor.js:99939:46 at CustomModifierManager.getDelegateFor (http://localhost:4200/assets/vendor.js:44817:20)

I visited the link https://deprecations.emberjs.com/ recommended for updating, I didn't really understand how to make this update, any help please .




mercredi 17 novembre 2021

Dynamically determine existence of template only Ember glimmer component?

I know that to dynamically determine the existence of a component on Ember we can use the solutions explained here or here.

We have a helper that uses .hasRegistration('component:${component}')

This also works for Glimmer components as long as there is a .js file defined, but it doesn't work for template-only Glimmer components. The component doesn't seem to be registered in that case.

Does anyone know a solution that would work for template-only glimmer components too?




mardi 16 novembre 2021

Where is this "Redirecting to //www....." page coming from?

I have an Ember app (with service worker) that is being served by Fastboot on an AWS Beanstalk server (Nodejs+NGINX).

My Beanstalk Nginx setup has a 301 http-to-https redirect rule, which works just fine as you can see in the screenshot.

The Ember app has the route path "/" mapped to "events/map" in the router.js file.

When I navigate to https://www.gigshq.com, it is supposed to redirect to https://www.gigshq.com/events/map. Sometimes it does it automatically, but sometimes it shows the following basic HTML page:

Screenshot of unknown "Redirecting to"

I'm trying to prevent this from showing and redirecting automatically, however I don't even know where to start because I'm not quite sure where this basic HTML page is coming from, whether it is Nginx, Fastboot, or Ember. Any help would be appreciated!




Ember.j - How to update chat when a message is created in database? (firebase as database)

I'm new to ember.js and firebase. At the moment I can post messages and see them displayed in a list like this:

//templates/show-messages.hbs



<div class="container">
    <div class="chat-container">
        
        <div class="bubble">
            <h3></h3>
            <p></p>
        </div>
        
    </div>
    <ChatInput class="Input" @username="" @text=""></ChatInput>
</div>


//routes/show-messages.js

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

export default class ShowMessagesRoute extends Route {
  model() {
    return this.store.findAll('chat-message');
  }
}

The problem is that when viewing chat in another browser, the chat window doesnt update when I post a message. Hence, the chat doesnt really update like it should.

How do I solve this? Thanks.




lundi 15 novembre 2021

How to put void link like Html in Ember using

I would like to know if it's possible to make a temporary void link in Ember <LinkTo @route=""> like HTML <a href="#">, thanks for helping.




mercredi 10 novembre 2021

Making a API Request in ember js

I am trying to learn ember JS, and I want to make a API request watched and read soo many videos and blogs also not clear enough how to call a API and store that data in the official docs.

const response = await fetch('/api/users.json');
const {data} = await response.json();
console.log(data)

This is what I tried ,but there is nothing in console I have created a folder in public directory and created a folder called API in it and saved my user.json file in it. My directory path

Hope, someone can explain how to make a API request in ember, if u can refer some blog or tutorial also will help me. Thanks in advance




mardi 9 novembre 2021

Ember JS FindAll returns undefined data

iam currently developing a contact management system web app using ember js for the front end .Iam using ember store for fetching the data from the api , while fetching json data using store.findAll() , iam getting the json array with the length of data as expected but when i try to access the data at a specific position in the json array it gives undefined value , it is not giving the model value.I have checked everything like json format , naming conventions with respect to my serializer but cant able to find what is going wrong , can anyone help me with solving this ?

Application adapter :

import RESTAdapter from '@ember-data/adapter/rest';

export default class ApplicationAdapter extends RESTAdapter {
    buildURL(...args) {
      return "http://localhost:8082/ContactManagementSystem1/api/contact/5";
    }
    headers = {
        'Accept': '*/*',
      };
}

Json response from api :

[
    {
        "firstName": "Example",
        "lastName": "K",
        "deletedAt": "",
        "mobileNumberHome": "7827382738",
        "companyName": "Example",
        "dateOfBirth": "2000-04-12",
        "id": 21,
        "userId": 4,
        "mobileNumberWork": "2738273788",
        "email": "rath@gmail.com"
    },
    {
        "firstName": "nameexample2",
        "lastName": "p",
        "deletedAt": "",
        "mobileNumberHome": "8989898996",
        "companyName": "Business ",
        "imageURL": "actress1.jfif",
        "dateOfBirth": "2021-10-05",
        "id": 51,
        "userId": 4,
        "mobileNumberWork": "8667889896",
        "email": "nameexample2h@gmail.com"
    }
]

Serializer :

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    normalizeResponse(store, primaryModelClass,payload,id,requestType){
        arguments[2] = {
            "contacts" : payload
        }
        return this._super(...arguments);
    }
});

Since my json response is different from the RestSerializer format i have written some code in the serializer for normalising the response.

Route where i fetch data using store.findAll()

import Route from '@ember/routing/route';
import {inject as Service } from '@ember/service';
export default class UserContactRoute extends Route {
  @Service store;
  async model() {
    return this.store.findAll('contact');
  }
}

These are codes which i have used , i have also checked in the inspect's console no error is been thrown , the problem is model array object were undefined.




jeudi 4 novembre 2021

How to resolve "Unable to download node 14.18.0" when deploying an Ember.js app to Heroku?

I encountered the error mentioned in the Title.

I have referred to a few relevant Heroku articles and tried their suggested changes including specifying the exact version of Node.js, Yarn, or npm that I'm using locally , but that still didn't work.

Here's the relevant sections extracted from my package.json:

  "engines": {
    "node": "14.18.0",
    "npm": "6.14.15",
    "yarn": "1.19.1"
  },
  "ember": {
    "edition": "octane"
  }

Here's the deployment log:

Enumerating objects: 1134, done.
Counting objects: 100% (1134/1134), done.
Delta compression using up to 4 threads
Compressing objects: 100% (1027/1027), done.
Writing objects: 100% (1134/1134), 309.32 KiB | 2.64 MiB/s, done.
Total 1134 (delta 581), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/emberjs.tgz
remote: -----> emberjs app detected
remote: -----> Setting NPM_CONFIG_PRODUCTION to false to install ember-cli toolchain
remote: -----> Fetching buildpack heroku/nodejs-v98
remote: -----> Node.js detected
remote:
remote: -----> Creating runtime environment
remote:
remote:        NPM_CONFIG_PRODUCTION=false
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NODE_VERBOSE=false
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote:
remote: -----> Installing binaries
remote:        engines.node (package.json):  14.18.0
remote:        engines.npm (package.json):   6.14.15
remote:
remote:        Downloading and installing node 14.18.0...
remote:        Unable to download node 14.18.0; does it exist?
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        If you're stuck, please submit a ticket so we can help:
remote:        https://help.heroku.com/
remote:
remote:        Love,
remote:        Heroku
remote:
remote: -----> Failed trying to compile heroku/nodejs-v98
remote:  !     Push rejected, failed to compile emberjs app.
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: d70a7009920574c3b615eb11c570a054b8348453
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version d70a7009920574c3b615eb11c570a054b8348453
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  !
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !   Push rejected to rarweo.
remote:
To https://git.heroku.com/rarweo.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/rarweo.git'



samedi 30 octobre 2021

How to convert array of object(hasMany relationship data) to array of id?

I'm getting data back from hasura like this:

{
  "data": {
    "movies": [
      {
        "id": "584db434-5caa-475e-b3ec-e98e742f0030",
        "movieid": "abc123",
        "description": "Penquins dancing in antactica",
        "photos": [
          {
            "id": "c4d2833a-4896-42b0-ae8b-0ab9fe71d1d4"
          },
          {
            "id": "e04697e3-21fe-4f0e-8012-443f26293340"
          }
        ]
      }
    ]
  }
} 

But Ember.js can't read and render the relationship data (photos). Is it the "photos" data should be like this?

"photos": [c4d2833a-4896-42b0-ae8b-0ab9fe71d1d4, e04697e3-21fe-4f0e-8012-443f26293340]

How can I convert it in Ember? or in Hasura?




malihu jquery custom scrollbar plugin error in crossdomain loading

Iam using malihu jquery custom scrollbar plugin version 3.1.5 in my tomcat application, build using ember js runing in xxx.com. While loading that xxx.com application in the iframe of another application running at yyy.com, Iam getting object.defineProperty called on non-object in the yyy.com web console. Kindly, help me as quick as possible.

error from console




jeudi 28 octobre 2021

How do I pass an object to a component?

This question was asked in the Ember Discord.

Is there a way to pass an object into a component

<SomeComponent object={color: green} />



Trying to Customize the ApolloService to enable Authorization in Ember 3.28. Any special configuration I need to plugin the apollo.js to be my config

Ember-Octane 3.28 Configured the enviroment.js file with the graphql endpoint, My apollo.js file in the service folder looks like

import ApolloService from 'ember-apollo-client/services/apollo';
import { inject as service } from '@ember/service';
import { setContext } from '@apollo/client/link/context';

export default class OverridenApollo extends ApolloService {
  @service session;

  link() {
    let httpLink = super.link();

    let authLink = setContext((request, context) => {
      return this._runAuthorize(request, context);
    });
    return authLink.concat(httpLink);
  }

  _runAuthorize() {
    if (!this.session.isAuthenticated) {
      return {};
    }
    return new Promise((success) => {
      let headers = {};
      let token = this.session.data.authenticated.token;
      headers['Authorization'] = `Bearer ${token}`;

      success({ headers });
    });
  }

  clientOptions() {
    return {
      link: this.link(),
      cache: this.cache,
    };
  }

 //...
}

Using ember-apollo-client pkg




Ember mismatch names in index.js and package.json

i have two different names in my package.json and index.js which i cannot change on both places. I am getting this error.

ember-cli: Your names in package.json and index.js should match. The addon in /Users/nrehman/Projects/copilot-seo-score currently have '@copilot/copilot-seo-score' in package.json and 'copilot-seo-score' in index.js. Until ember-cli v3.9, this error can be disabled by setting env variable EMBER_CLI_IGNORE_ADDON_NAME_MISMATCH to "true". For more information about this workaround, see: https://github.com/ember-cli/ember-cli/pull/7950.

My ember-cli version is "ember-cli": "~3.28.3"




mardi 26 octobre 2021

Connecting ember js application with react host : microfrontend

I was trying to connect different frontend tech together in a React host using microfrontend.

I managed to connect react, vue, VanillaJS application to the React host, but i am not able to wrap my head around Ember JS, since vue, Vanilla were not framekwork, it was easy to connect them using webpack ModuleFederationPlugin.

I tried searching it over internet couldn't find any help, Is it possible to connect Ember JS application to a react based host environment(using module federation) ??

If yes would like to see an example if it's available online. (github or sandbox links)




dimanche 24 octobre 2021

Building Ember app gives me error, Cannot read property 'pkg' of null

I was trying to compile a website frontend from 2015 that utilizes an old version of ember.js and node.js. The instructions state to run make build, which in turn would run ember build dist. Though when the command is ran, it gives me this error.

Cannot read property 'pkg' of null
TypeError: Cannot read property 'pkg' of null
    at Function.Addon.resolvePath (/home/pyah/pyah/client/node_modules/ember-cli/lib/models/addon.js:347:18)
    at Function.Addon.lookup (/home/pyah/pyah/client/node_modules/ember-cli/lib/models/addon.js:362:22)
    at /home/pyah/pyah/client/node_modules/ember-cli/lib/models/project.js:222:34
    at visit (/home/pyah/pyah/client/node_modules/ember-cli/lib/utilities/DAG.js:23:3)
    at DAG.topsort (/home/pyah/pyah/client/node_modules/ember-cli/lib/utilities/DAG.js:82:7)
    at Project.initializeAddons (/home/pyah/pyah/client/node_modules/ember-cli/lib/models/project.js:220:9)
    at Project.eachAddonCommand (/home/pyah/pyah/client/node_modules/ember-cli/lib/models/project.js:249:10)
    at module.exports (/home/pyah/pyah/client/node_modules/ember-cli/lib/cli/lookup-command.js:53:13)
    at CLI.<anonymous> (/home/pyah/pyah/client/node_modules/ember-cli/lib/cli/cli.js:36:26)
    at $$$internal$$tryCatch (/home/pyah/pyah/client/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:490:16)

This error is shown even if just ember is ran in terminal.

Node.js version: v6.12.0

npm version: 6.14.15




solution for selecting frameworks and tools for managing photo with zoom and selection

I want to develop a software in which I need to maneuver on the photos, Features such as Drag and zoom and ..., for example photos related to the rocks of a mine (like the image below) where the depth of each rock is known and users can see rocks related to any depth of see this mine There is an example of this website: https://portal.imago.live/

enter image description here

A general guide from this website: https://support.imago.live/hc/en-us/articles/360032890432-Explore-the-Imago-Web-Portal-Overview

The question is, do you have the tools to do this? This site has used the Ember.js framework. Does this framework help to implement this software?




vendredi 22 octobre 2021

Ember test launch in CI/dev environment

I have this in my testem.js

launch_in_ci: ['Chromium'],
launch_in_dev: ['Chrome'],

Is there any way to run ember test and specify CI/dev environment?

I know I can use this solution but this looks like not the right way since I have configuration file.




jeudi 21 octobre 2021

Ember: Selecting the object form array using index in #each loop

Trying to use the index value in a loop in EmberJs

Consider the following scenario,


<Component1 @prop= @prop2= />

I wish to send the object from the second array using the index value from first array. I cannot find any references to this. Any References i found use the first array alone and and didn't use the index in another variable. Thanks in advance for your time and effort.




Ember not population model even after successful API call

My route.js

export default Route.extend(ResetScrollMixin, {

  model(params, { queryParams }) {
    return hash({
      ruleSetVersions: this.store.queryRecord('rule-set-versions', {
        rule_set_id: params.rule_set_id,
        is_archived: false,
        page: queryParams.page || 1
      }),
      ruleSet: this.store.findRecord('rule-set', params.rule_set_id)
    })
  },

  actions: {
    reload() {
      location.reload()
    }
  }
});

Models

rule-set-versions.js

export default DS.Model.extend({
    rule_set_versions: DS.belongsTo('paginated-versions')
})

paginated-versions.js

export default DS.Model.extend({
    rule_set_versions: DS.hasMany('rule-set-version'),
    pagination: DS.belongsTo('pagination'),
})

pagination.js

export default DS.Model.extend({
    page_number: DS.attr('number'),
    page_size: DS.attr('number'),
    total_pages: DS.attr('number'),
    total_rows: DS.attr('number')
})

rule-set-versions.js this is a serializer for rule-set-versions model

var underscore = Ember.String.underscore;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
      rule_set_versions: {
        serialize: "id",
      },
      pagination: {
        serialize: "id",
      },
    },
    keyForRelationship: function (rawKey) {
      console.log("here")
      return underscore(rawKey) + "_id";
    }
})

My API Response which truncated.

{
    "rule_set_versions": {
        "id": 100,
        "pagination": {
            "id": 100,
            "page_number": 1,
            "page_size": 5,
            "total_pages": 1,
            "total_rows": 3
        },
        "rule_set_versions": [{
            "id": 934,
          ....
        }]
    }
}

I am getting null when I do this.get("model.ruleSetVersions"). I tried and followed the documentation as well but I couldn't come up with the solution.




mercredi 20 octobre 2021

Ember 1.13.x and newer version relation with jquery

  1. Does Ember require jquery to be imported in older or newer versions ?

  2. if yes, will older ember support if newer version of jquery.js file is included ? any docs to refer ?

  3. what does Ember.$ mean ? does ember have inbuilt jquery ?




lundi 18 octobre 2021

Frontend framework change

We are a small company, using emberjs as the main frontend framework for our projects. The frontend architect sticks to it like liquid glue sticks to paper, because he doesn't know any other frameworks. The main reason that is forced is the slogan: 'convention over configuration'. And there are reasons like emberjs is faster in larger scale applications. Anyone can reason pro-contra for emberjs, angular, react etc.. (hopefully someone who knows all of them, at least emberjs, and another)? We are having meeting sessions about this, where junior frontend devs try to convince the architect about the other frameworks. In my opinion this should not be a technical issue, all of the frameworks are capable of developing 'larger scale' applications. The real reason should be the recruiting, we would find react/angular devs more easily. Thanks




jeudi 14 octobre 2021

Ember Octane - Display contents of a Tracked Array from Controller in Template?

I am trying to render access the contents of an array stored in the controller from within the template. The array starts empty but objects are added to it using a method in the controller:

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

export default class ControllerName extends Controller {

  @tracked
  displayedArray = new Array();

  @action
  async setUpArray(){
    let object1 = {Key1:[1,2], Key2: [3,4]};
    let object2 = {Key1:[5,6], Key2: [7,8]};
    this.displayedArray.push(object1);
    this.displayedArray.push(object2);
  }
}

I am able to call setUpArray() from the template and have confirmed it is running as expected and producing setting the tracked variable to an array of the two objects.

However I do not seem to be able to display anything relating to displayedArray in the template. I have tried the following:

//Returns blank - I expected [object,object]


//Returns blank


//Returns 0 before and after the *setUpArray()* function is called

As far as I can tell the issue only happens with arrays or at least arrays containing objects. I am able to display strings or other tracked variables set up in the controller just fine.

Does anyone know why Ember is failing to display this?




lundi 11 octobre 2021

How do I customize the ember-bootstrap form.element so that the input uses a specific column size?

I'm using ember-bootstrap and the following element:

<form.element @controlType="text" @label="First Name:" @property="firstName" />

which produces the following HTML

<div class="form-group row">
  <label class="col-sm-4 col-form-label" for="ember198-field">First Name</label>

  <div class="col-sm-10">
    <input id="ember198-field" class="form-control" type="text">
  </div>
</div>

How do I go about customizing the col-sm-10 in the enclosing <div> for the input element?




Slick Slider Not Work When Array Update In Ember js

When first render component slick slider work well but when i update array data by action then break slick slider view.Please Help me.I am using Ember Cli version 3.12.Here Is My Component Code:

slickCarousel(){
$(`.${this.className}`).slick({
  slidesToShow: this.slideShow,
  responsive: [
    { breakpoint: 992, settings: { slidesToShow: 4 } },
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2,
        arrows: false,
        dots: true,
      },
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2,
        arrows: false,
        dots: true,
      },
    },
  ],
  arrows: true,
  prevArrow:
    "<button type='button' class='slick-prev'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
  nextArrow:
    "<button type='button' class='slick-next'><i class='fa fa-angle-right' aria-hidden='true'></i></button>",
});
},

destroyCarousel() {
if ($(`.${this.className}`).hasClass('slick-initialized')) {
  this.$(`.${this.className}`).slick('destroy');
}       
},

didInsertElement() {
this._super(...arguments);
this.destroyCarousel();
this.slickCarousel();
},



caniuse-lite is outdated will not go away after updating browserlist

I'm working on fixing build warnings in my Ember.js application currently, and one I get is this

[Babel: @ember/test-helpers > applyPatches]Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

However running that command provides this output:

npx: installed 6 in 2.566s
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

Why you should do it regularly:
https://github.com/browserslist/browserslist#browsers-data-updating
Latest version:     1.0.30001265
Installed version:  none
Removing old caniuse-lite from lock file
Installing new caniuse-lite version
$ yarn add -W caniuse-lite
Cleaning package.json dependencies from caniuse-lite
$ yarn remove -W caniuse-lite
caniuse-lite has been successfully updated
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

Why you should do it regularly:
https://github.com/browserslist/browserslist#browsers-data-updating

And the warning never goes away. I have tried about every applicable solution in this thread. This seemed to be the main one to help, but has not for me

npm --depth 20 update --save caniuse-lite browserslist 

I am not using Visual Studio and have tried blowing away all node modules and still nothing. Is there any known issue around this or way to fix it?




vendredi 8 octobre 2021

How to install ember-cli version 1.13.11 without global?

I just install nvm software and I will run nvm install 4.0.0 . Node will download and npm also download and install it automatically.next i will run nvm use 4.0.0 set-up will set it.now I see my node version using node - v it show v4.0.0 all are correct all comments under admin only and I will create one folder and change to that path and I will run npm install ember-cli@4.0.0 it will install it successfully but after that I use ember -v it show ember is not recognised?




How can I use ember-concurrency with a callback function?

I'd like to use ember-concurrency to handle batch validation of a collection of addresses. The address validation is done by a third party API that calls a server-side function that then 'calls back' to the client when the server has completed its work.

It seems like this would be a place to use the ember-concurrency add-on, but i can't figure out how to use it correctly. I think the challenge is that the api call to server returns immediately after the server side process is kicked off. How do i make ember-concurrency aware of the connection between the call to the server and the callback function so that the 'task' waits for the callback to be completed as a sign that the task has been completed? The way i have the code working now, 'results' is (understandably) always null.

import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';

export default class BatchAddressInputComponent extends Component {
    @service api;
    addressList = "";

    //addressList populated from a TextArea
    @task *DoAddressValidation ()
    {
        let results = yield this.api.BatchQueryAddresses(this.addressList);
        alert(results); //not surprisingly, 'results' is always null
    }
}
    
    
import Service from '@ember/service';

export default class ApiService extends Service {
  _api;

  //API *should* be available as a global object, imported as a <script> on
  // application start-up.
  constructor() {
    super(...arguments);
    this._api = API;
  }

  BatchQueryAddresses(addressList) {
    this._api.BatchQueryAddress(addressList, 2, this._queryAddressCallback, null, 2000);
  }

  _queryAddressCallback(result, error) {
    if (error) {
        alert("Error: " + result);
        return;
    }
    var j = JSON.stringify(result, null, ' ');
    return(j);
  }
}



How to install ember-cli version 1.13.11 in windows 10

I am trying to install ember-cli version 1.13.11 using node version is 4.0.0 and npm version is 2.14.2 . i will run all comments in admin. first i will install npm install -g ember-cli@1.13.11 and ember version is created next i will run ember new demoproject .but my laptop has 4 gb ram and windows 10 so it will take almost 1 hour to run after it will not create project it showing error it shown in that picture but i will clean all npm cache and computer temp also but problem is not solved and npm install -g ember-cli-windows comments also installed but it will not work please share me solution install ember-cli@1.13.11




How to use tabulator with ember?

I want to use http://tabulator.info/ with ember. I don't understand the documentation nor can I find any guides on configuration for ember. How can I start by creating a simple table?




How do I access ENV from config/environment in an addon?

This is a question that was asked by @dbendaou over on the Ember Discord


What is the best way to access ENV from config/envirnoment in an addon?

I was thinking about getOwner(this).lookup('config:environment') but it doesn't work neither does import ENV from '../config/environment'; 😅




jeudi 30 septembre 2021

EmberJS Octane Avoid two way binding for @tracked variable and normal variable

In EmberJS if I assign a @tracked variable as the value of a second variable, updating the second variable also updates the tracked variable.

For example:

  @tracked
  baseProperty = this.args.baseProperty;

  @action
  updateDescription(event){
    let newProperty = this.baseProperty;
    let text = event.target.innerText;

    this.newProperty = Object.assign(this.newProperty , { property: htmlSafe(event.target.innerText) });
  }

If updateDescription() runs property for the newProperty object is updated, but property for the tracked baseProperty is updated as well. Is there a way to make it so that only newProperty updates?




mardi 28 septembre 2021

Emberjs Model from route returning undefined in controller

I have a strange behavior with my Ember app. I can't make any sense out of it. Basically I'm using Ember octane and I wanted to access my model from my route to my controller .

This is my route

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

export default class ChatIndexRoute extends Route {
  model() {
    return {
      chatMessages: [
        {
          username: '1',
          message: 'Hi',
          read: true,
        },
        {
          username: '1',
          message: 'how are you?',
          read: false,
        },
        {
          username: '1',
          message: 'its been a long time :)',
          read: false,
        },
      ],
    };
  }

  setupController(controller, model) {
    controller.set('model', model.chatMessages);
  }
}

and this is my controller

import Controller from '@ember/controller';


export default class ChatIndexController extends Controller {
  init() {
    super.init(...arguments);
    console.log('test', this.model);
  }
}

When I console.log(this.model) I got undefined.

But when I simply do a console.log(this) I got a whole object with a model property filled with chatmessages

See this image

This is crazy




dimanche 26 septembre 2021

Ember Octane, Tracked property not rerendering template

Coming from a React background, I'm having issues understanding EmberJs "Tracked" concept. On paper it shouldn't be different from "React state".

So what I have understood is that when we anotate a property with @tracked it should cause a re render when there is a change in this property.

Please take a look at the code below:

ProductItemComponent

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class ProductItemIndexComponent extends Component {
  @service('cart') cartService;

  @tracked addedToCart = false;

  @action
  checkItemInCart(id) {
    if (this.cartService.items.findBy('id', id)) {
      this.addedToCart = true;
    } else {
      this.addedToCart = false;
    }
  }
}

Template,

<div class="card-container">
  <div class="card product-item" >
    <img src= class="product-image card-img-top" alt="...">
    <div class="card-body">
      <h5></h5>
    </div>
    <div class="footer">
      <p class="card-text"><span class="badge badge-secondary"><strong>Price: </strong></span></p>
      <button type="button" class="btn btn-warning" 
        disabled=>Add
        to cart</button>
    </div>
  </div>
</div>

When I first render the component I'm checking if the current item is present in the cart using and if its present I'm switch the tracked property @tracked addedToCart = false; to true else false.

In theory, this should disable my button in my productItem template as soon as it finds the Item in the cartService. It only works when I go to another page and then come back.

But there is no rerender of the page. Can someone help me understand what I might be doing wrong?

Thank you in advance




mercredi 22 septembre 2021

Ember - How to break the build if test coverage fails minimum threshold?

I want to break the build if coverage drops below certain percentage. Currently test runs and coverage is generated if I run below command.

COVERAGE=true ember test

enter image description here

but I don't see a way to break the build based on coverage percentage. Request to help me on this.




lundi 20 septembre 2021

EmberJS Data Assert in setRecordDataFor "Illegal set of identifier"

Using 3.28 I am hitting an assert deep inside Ember Data when retrieving a relationship on one of my models. I can run the following query just fine:

return this.store.findRecord('project', project_id)

However when I run a subsequent

const monitors = await model.monitors;

in my afterModel() of the route, this assert is triggered.

My Models look pretty standard:

export default class ProjectModel extends Model {
  @attr('string') name;
  @belongsTo('user') creator;
  @attr('date') created;
  @attr('date') changed;
  @hasMany('domain-monitor') monitors;
}

export default class DomainMonitorModel extends Model {
  @belongsTo('project') project;
  @hasMany('page-monitor') pages;
  @attr('string') protocol;
  @attr('string') domain;
  @attr('date') created;
  @attr('date') changed;
}

If someone can point to what is going wrong, I am happy to submit an MR to improve this assert message to hopefully unstuck someone in the future. Thanks!




jeudi 16 septembre 2021

Ember-cli-build do not inject app.css into the compiled app

I just migrated my app from ember 2.18 to 3.4. I have a css file at app/styles/app.css

Here is my ember-cli-build.js

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    // Add options here
    adminLTE: {
      plugins: ['morris','datepicker',
        'bootstrap-wysihtml5', 'daterangepicker',
        'select2', 'input-mask'
      ]
    },

    flatpickr: {
      locales: ['fr']
    },

    minifyCSS: {
        enabled: true,
        options:
        {rebaseTo: 'assets'}
      },

    'ember-bootstrap': {
      bootstrapVersion: 3,
      importBootstrapCSS: false,
      importBootstrapFont: true
    }
  });
  return app.toTree();
};

And the relevant part of index.html :

    <link integrity="" rel="stylesheet" href="assets/vendor.css">
    <link integrity="" rel="stylesheet" href="assets/marketadmin.css">
    <link integrity="" rel="stylesheet" href="css/AdminLTE.min.css">
    <link integrity="" rel="stylesheet" href="css/skins/skin-blue.min.css">

There is no CSS rules of my app.css in vendor.css or in marketadmin.css. Why?




Eslint disable for a specific line pattern

Example, //test is a pattern used in one of my code processing to ignore some testing. And we matched exactly //test to exclude the processing. But when we apply Esline auto fix, //test automatically changes in // test (space added as formatting)

So, Extra processing is happening due to it.

Hence I had googled to fix this. possible solutions are,

  1. matching both patterns(//test & // test - this is out of my context, had to raise and wait for the fix)
  2. Or else, had to add eslint disable comment to disable eslint processing around that comments.

Is there any way to configure a line pattern to ignore commonly in .eslintrc.js? Curious to know about it. So far checked, there is a pattern to exclude file folder paths only.

Please let me know here if anyone knows about this(line pattern ignoring commonly)




lundi 13 septembre 2021

ember-cli-eslint - Unexpected top level property overrides[0].extends

I am having an issue with eslint (using ember-cli-eslint ver 5.1.0) and an extends property in my override in my .eslintrc file. My .eslintrc looks like this:

module.exports = {
    root: true,
    parser: 'babel-eslint',
    parserOptions: {
        ecmaVersion: 2018,
        sourceType: 'module',
        ecmaFeatures: {
            legacyDecorators: true
        }
    },
    plugins: [ 'ember' ],
    extends: [
        'eslint:recommended'
    ],
    env: {
        browser: true
    },
    overrides: [
        {
            files: [
                '.eslintrc.js',
                'ember-cli-build.js',
                'testem.js',
                'blueprints/*/index.js',
                'config/**/*.js',
                'lib/*/index.js'
            ],
            extends: [
                'plugin:my-plugin
            ]
        }
    ]
};

However when I build I get the following error:

ESLint configuration in path-to\my-app\.eslintrc.js is invalid:
        - Unexpected top-level property "overrides[0].extends".

I have another ember project with the same version of ember-cli-eslint and a very similar eslintrc file that uses the same extends property in overrides without issue. I have compared configurations between the two projects over and over and cannot figure out what is causing this. Doing research the most I could find is an issue that caused this error incorrectly on older versions of ember-cli-eslint, but that should be fixed in my version.

Am I missing a different configuration to allow extends properties in overrides?




jeudi 9 septembre 2021

How to send post request from form that sends the name, email and folder of the CV by using a method post in framework Ember?

How to send post request from form that sends the name, email and folder of the CV by using a method post in framework Ember




mercredi 8 septembre 2021

unable to import Braintree Javascript SDK in Ember "ember-cli": "^3.25.2",

I have installed the braintree package via npm, outlined here,

using

const braintree = require("braintree");

results in

loader.js:247 Uncaught Error: Could not find module braintree imported from (require)

attempting a manual install suggested here

app.import('node_modules/braintree/lib/braintree/braintree_gateway.js');

with

const braintree = require("braintree");

results

loader.js:247 Uncaught Error: Could not find module braintree imported from (require)

this

app.import('node_modules/braintree/lib/braintree.js');

results

card-payment.js:343 Uncaught TypeError: braintree.BraintreeGateway is not a constructor

grep -r BraintreeGateway node_modules/braintree/
node_modules/braintree/lib/braintree/braintree_gateway.js:class BraintreeGateway {
node_modules/braintree/lib/braintree/braintree_gateway.js:module.exports = {BraintreeGateway: BraintreeGateway};
node_modules/braintree/lib/braintree.js:let BraintreeGateway = require('./braintree/braintree_gateway').BraintreeGateway;
node_modules/braintree/lib/braintree.js:  BraintreeGateway: BraintreeGateway,
node_modules/braintree/CHANGELOG.md:* Add `GraphQLClient` to `BraintreeGateway` class
node_modules/braintree/README.md:var gateway = new braintree.BraintreeGateway({
node_modules/braintree/README.md:var gateway = new braintree.BraintreeGateway({

a grep of the node modules appears to show the last manual import as in the ballpark of correct.

component-class

  @action
  saveNonce() {
    // const braintree = require("braintree");

    var gateway = new braintree.BraintreeGateway({
      environment: String(ENV.BRAINTREE_ENVIRONMENT),
      merchantId: String(ENV.BRAINTREE_MERCHANT_ID),
      publicKey: String(ENV.BRAINTREE_PUBLIC_KEY),
      privateKey: String(ENV.BRAINTREE_PRIVATE_KEY)
    });

    let clientNonce = document.getElementById('save-nonce').value;

    gateway.transaction.sale({
      amount: String(this.amount/100),
      paymentMethodNonce: clientNonce,
      // deviceData: deviceDataFromTheClient,
      options: {
        submitForSettlement: true
      }
    }, (err, result) => {
    });

  }

package.json

...
"ember-cli": "^3.25.2",
"braintree": "^3.7.0",
...



How do you render and filter over a collection of data from an @argument?

This question comes from our Ember Discord


I have something like this


  <ItemList @categories=/>


I am calling action somewhere else, then filtering the @data and I would like to reset this each @data.

I want to assign the filtered result to @data data passed from parent component to this

At the same component I have button

<li 
  class="inline hover:underline cursor-pointer ml-4" 
  
>
  
</li>

and changeProject action filters the @data that I would like to re-assign to #each for example - this.data = filteredModel; does not work.




mardi 7 septembre 2021

Could not find module ember-routing/system/route

error while upgrading from 2.18 to 3.4

error while upgrading ember-CLI version from 2.18 to 3.4




Ember not displaying objects in views

I've started working on Discourse plugin and learning about Ember. I have 'keynote' model, which has 3 attributes: id, key, link. My problem is that when I create new keynote - it displays on keynotes page but if I reload page - results disappear. I'm sure that the problem in my fetch method. Here is my views page:

<button onclick="createKeynote">Create</button>
<form >
 <input type="text" id= key_area>
 <input type="text" id= link_area>

  <button type='submit' class='btn btn-primary'>
    
  </button>
</form>



<ul>
  
    <li>
       -->  ==> 
    </li>
  
</ul>

Here is the page for my keynotes controller:

 export default Ember.Controller.extend({
  init() {
    this._super();
    this.set('keynotes', []);
    this.fetchKeynotes();
  },

  fetchKeynotes() {
    this.store.findAll('keynote')
      .then(result => {
        for (const keynote of [result.link] && [result.key]) {
          this.keynotes.pushObject(keynote);
        }
      })
      .catch(console.error);
  },

  actions: {
    createKeynote(key, link)
    {
      key = document.getElementById("key_area").value
      link = document.getElementById("link_area").value
      const keynote_full = {};
      keynote_full[key] = link


      const keynoteRecord = this.store.createRecord('keynote', {
        id: Date.now(),
        key: key,
        link: link
      });
      console.log(keynoteRecord)

      keynoteRecord.save()
        .then(result => {
          this.keynotes.pushObject(result.target);
        })
        .catch(console.error);
    }
  }
});

Pay attention to 'fetchKeynotes' method - if I would try to console.log(findAll('keynote')) - it would give me out all attributes and also arrangedContent in which one contains all of the keynotes with all attributes (id, key, link), so as I said - I'm sure, that something is wrong with 'fetchKeynotes' method but I am not sure why.




lundi 6 septembre 2021

Check if value is false in handlebar helper

I have created a handlebar helper which gives true or false values. How can I check if the value is false and render HTML. I tried using unless but it's not working. I don't want to give any else condition.

ifTrue = false


   <p> Print when not true.</p>




samedi 4 septembre 2021

Ember.js Creating a new route in ember.js always lead to default index.html file

I am new at learning ember.js I have followed some tutorials but I don't know why It doesn't work for me. What I would like is to create a new route with games: http://localhost:4200/jeux so I have done :

ember g route jeux

To create a new route "/jeux" I have completed this new page with jeux.hbs:


<p>La page des jeux-vidéos</p>

Now I don't know why http://localhost:4200/jeux is still leading to the default index.html page [image of http://localhost:4200][1] [image of http://localhost:4200/jeux][2] Thanks for the Help! Here are some images that can help to understand my project (it is a simple project that I have generated with "ember new the project name")

[image of file "router.js"][3]
[basic default "index.html"][4]
[the evironment.js file][5]
[1]: https://i.stack.imgur.com/JAzuf.png
[2]: https://i.stack.imgur.com/LBrFB.png
[3]: https://i.stack.imgur.com/gQunM.png
[4]: https://i.stack.imgur.com/FEa93.png
[5]: https://i.stack.imgur.com/UaXfp.png



Ember.set not working on some specific property

I am not a beginner in Ember.js but I don't understand why the following bug occurs:

console.log('--> before set document', JSON.stringify(model.echographies));
model.echographies.pushObject(EmberObject.create({test: '1'}));
model.echographies.forEach(echography => {
  if (!echography.documents) {
    set(echography, 'documents', []); // <== bug is here
    set(echography, 'documentsX', []);
    set(echography, 'documentsY', 'test');
  }
});
console.log('--> after set document', JSON.stringify(model.echographies));

The output in the console is:

    --> before set document 
    [
        {"id":92,"echography_date":"2020-02","echography_freetext":"echography_freetext"}
    ]
    --> after set document 
    [
        {"id":92,"echography_date":"2020-02","echography_freetext":"echography_freetext","documentsX":[],"documentsY":"test"},
        {"test":"1","documents":[],"documentsX":[],"documentsY":"test"}
    ]

What I don't understand is why the documents property is not set on the real object while documentsX or documentsY work on it and why the three properties work on the fake object. I could not make a JSFiddle to reproduce the bug.

Ember 3.16 Objects are created with EmberObject.create. The array is displayed in the view with a and some computed watching the array.

Do you have any idea on why this bug could append? What should I try to debug this code and find why the set not working for this specific property?




braintree hosted payment fields client undefined Ember 3.25

Ember and Braintree Hosted Fields are not a good mix so far, Braintree Support are out of ideas on this one. When the form renders on the page it calls the action to create the client. The client is undefined. The live page is up here.

picture-this-44ac48bef9f8df633632a4d202da2379.js:57 Uncaught TypeError: Cannot read property 'client' of undefined

enter image description here

component hbs

<script src="https://js.braintreegateway.com/web/3.81.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.81.0/js/hosted-fields.min.js"></script>
<div class="demo-frame" >
  <form action="/" method="post" id="cardForm" >
    <label class="hosted-fields--label" for="card-number">Card Number</label>
    <div id="card-number" class="hosted-field"></div>

    <label class="hosted-fields--label" for="expiration-date">Expiration Date</label>
    <div id="expiration-date" class="hosted-field"></div>

    <label class="hosted-fields--label" for="cvv">CVV</label>
    <div id="cvv" class="hosted-field"></div>

    <label class="hosted-fields--label" for="postal-code">Postal Code</label>
    <div id="postal-code" class="hosted-field"></div>

    <div class="button-container">
    <input type="submit" class="button button--small button--green" value="Purchase" id="submit"/>
    </div>
  </form>
</div>

component class

import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { braintree } from 'braintree-web';

export default class CardPaymentComponent extends Component {

  @action
  setupBraintreeHostedFields() {

    alert('booh');
    var form = document.querySelector('#cardForm');
    var authorization = 'sandbox_24nzd6x7_gyvpsk2myght4c2p';

    braintree.client.create({
      authorization: authorization
    }, function(err, clientInstance) {
      if (err) {
        console.error(err);
        return;
      }
      createHostedFields(clientInstance);
    });

    function createHostedFields(clientInstance) {
      braintree.hostedFields.create({
        client: clientInstance,
        styles: {
          'input': {
            'font-size': '16px',
            'font-family': 'courier, monospace',
            'font-weight': 'lighter',
            'color': '#ccc'
          },
          ':focus': {
            'color': 'black'
          },
          '.valid': {
            'color': '#8bdda8'
          }
        },
        fields: {
          number: {
            selector: '#card-number',
            placeholder: '4111 1111 1111 1111'
          },
          cvv: {
            selector: '#cvv',
            placeholder: '123'
          },
          expirationDate: {
            selector: '#expiration-date',
            placeholder: 'MM/YYYY'
          },
          postalCode: {
            selector: '#postal-code',
            placeholder: '11111'
          }
        }
      }, function (err, hostedFieldsInstance) {
        var tokenize = function (event) {
          event.preventDefault();

          hostedFieldsInstance.tokenize(function (err, payload) {
            if (err) {
              alert('Something went wrong. Check your card details and try again.');
              return;
            }

            alert('Submit your nonce (' + payload.nonce + ') to your server here!');
          });
        };

        form.addEventListener('submit', tokenize, false);
      });
    }

  }

}

package.json

...
"ember-cli": "^3.25.2",
"braintree-web": "^3.81.0",
...



mercredi 1 septembre 2021

Add Extra Actions to LinkTo in Octane

I have a dropdown menu with links, when the links are clicked I'd like the menu to close.

Something like (a11y/i18n truncated):

<ul class="menu">
    <li>
        <LinkTo @route="myprofile">
            Profile
        </LinkTo>
    </li>
    <li>
        <LinkTo @route="logout">
            Logout
        </LinkTo>
    </li>
</ul>

I'd like to add an additional click handler to the link to, something like:

<ul class="menu">
    <li>
        <LinkTo @route="myprofile" >
            Profile
        </LinkTo>
    </li>
    <li>
        <LinkTo @route="logout" >
            Logout
        </LinkTo>
    </li>
</ul>

However this makes the LinkTo useless as it reloads the page as if following a link instead of transitioning to a new route. We're currently doing this using hember-link-action, but I'd love to find a more idiomatic way to approach this problem.




Data loading issues in Ember 2.17

In ember 2.17 I have the following model :

import DS from 'ember-data';

export default DS.Model.extend({
  sharing_start:DS.attr('date'),
  owner: DS.belongsTo('shop'),
  deleted:DS.attr('boolean'),
  shared:DS.attr('boolean'),
  free_price:DS.attr('boolean'),
  product:DS.belongsTo('product'),
  from_share_products:DS.hasMany('product',{inverse:"shared_from"})
});

I use it in the following model :

import Route from '@ember/routing/route';
import { assign } from '@ember/polyfills';

export default Route.extend({
  model(params){
    return this.get('store').query('shared-product',assign(params,{include:'owner,product'}))
  },
  queryParams: {
    page: {refreshModel: true},
    size: {refreshModel: true},
    scope: {refreshModel: true}
  }
});

The data is rendered in a table, here is the line component used in a each loop :

<td> SP ID :  PRODUCT ID : </td>
<td></td>
<td></td>

If I reload the page on this route It render one line with the product name and ID and the following error :

 "Assertion Failed: You modified \"sp.product\" twice on <marketadmin@model:shared-porduct::ember988:11> in a single render. It was rendered in \"component:shared-products/catalog-line\" and modified in \"component:shared-products/catalog-line\". This was unreliable and slow in Ember 1.x and is no longer supported. See https://github.com/emberjs/ember.js/issues/13948 for more details."

If I go to this route from another route in the app, the array is displayed without console error except that, the first line has no product name or ID, as well as the 8th line (both in FF and chrome), and the following ones have a product name and ID.

The weird part is that in both the refresh or naviguating case, the data is retrieved in one API call that return the data with products as relationship.

I am not sure where to go to diagnose or solve that problem.




Emberjs, inside Controller call this.transitionToRoute('index');

    error: function (jqXHR, exception) {
      console.log('Error occured!');
      this.transitionToRoute('main');
    },

Error: Uncaught TypeError: this.transitionToRoute is not a function




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!