vendredi 30 avril 2021

Ember Data not properly serializing property names of objects in an array

I have a simple (made up for this question) model with an attribute called electricGuitars that has a few defaults predefined.

 export default class guitarCollectionModel extends Model {
  @attr('string') firstName;
  @attr('string') lastName;
  @attr({
    defaultValue() {
      return [
        {
          serialNumber: "sdfdsfadf",
          colorCode: "dsfsadfdfa"
        },
        {
          serialNumber: "234234234",
          colorCode: "234234234323"
        },
        {
          serialNumber: "oorprpprprpororprp",
          colorCode: "rproproroprporp"
        }
      ];
    }
  }) electricGuitars;
}

When I save the model (this.model.save()) Ember Data POSTs to my API and almost everything is serialized correctly by default (no custom serializer or adpaters). API expects all property names to be dasherized.

{
  "data": {
    "attributes": {
      "first-name": null,
      "last-name": null,
      "electric-guitars": [
        {
          "serialNumber": "sdfdsfadf",
          "colorCode": "dsfsadfdfa"
        },
        {
          "serialNumber": "234234234",
          "colorCode": "234234234323"
        },
        {
          "serialNumber": "oorprpprprpororprp",
          "colorCode": "rproproroprporp"
        }
      ]
    },
    "type": "guitar-collection"
  }
}

The problem is that the serialNumber and colorCode properties inside of the electricGuitars property/array have not been dasherized.

Is there an easy way to achieve this?




Replace browser confirm() with other library like bootbox

Browser native confirm dialog doesn't look good.
I have ember route wherein taking user confirmation to proceed if there are any unsaved changes. I wanted to change the dialog with bootbox confirm dialog but that doesn't stop the execution as bootbox.confirm() method is async.

        willTransition: function(transition){
            // model dirty checking logic to set flag value
            if(flag){
                if(!confirm("Do you want to leave this page without save?")){
                    transition.abort();
                }
            }
          }

Note: ES6 is not used in project




mercredi 28 avril 2021

How to call js function from a hbs file in ember.js

this is the main app in ember.js

app/templates/application.hbs


<ul>
  <LinkTo @route="print-user" >Print User</LinkTo>
</ul>

This is the code to get the json-array response from servlet

app/components/print-user.js

import Component from '@glimmer/component';
import {action} from "@ember/object";
import {tracked} from "@glimmer/tracking";
export default class PrintUserComponent extends Component {
    @tracked search="";
    @tracked print="";
    @tracked gotresponse=false;
    @action 
    async searchuser (searchtext){
        let response=await fetch("/UserManagement/SearchServlet",
        {   method: "POST",
            body: JSON.stringify({
                "type": "search",
                "searchtext": searchtext
            })
        });
        let parsed=await response.json();
        this.gotresponse=true;
        this.search=parsed;
    }
    async deleteuser (id,firstname,lastname,mailid){
        let response=await fetch("/UserManagement/UserManagementServlet",
        {   method: "POST",
            body: JSON.stringify({
                "type": "delete",
                "id": id,
                "firstname":firstname,
                "lastname":lastname,
                "mailid":mailid
            })
        });
        let parsed=await response.json();
        alert(parsed.status);
    }
}

This is the hbs code to print the user table in webpage

app/components/print-user.hbs


<input5></input5>
<searchbutton >Search</searchbutton>
<printbutton >Print User</printbutton>

<table class="styled-table">
    <thead>
        <tr><th>User Id</th>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Mailid</th>
            <th>Delete</th>
        </tr>
    </thead>
    
        <tbody>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td><button >Delete</button></td>
            </tr>
        </tbody>
    
</table>

I need to print the user data while clicking the print user in application.hbs It is working properly when I click search button. I Don't know how to print the user details without clicking button....




vendredi 23 avril 2021

using ember ember-drag-sort with emblem templates

Error parsing code while looking for "npm:" imports in file: /{path}/tmp/stub_generator-input_base_path-8FTPYOxJ.tmp/dash/tests/pages/components/_component.js SyntaxError: Unexpected token (35:13)

this when i try to run my project or build

i am using ember 3.12 emblem 0.12.0 ember-drag-sort 3.0




How do I run Ember tests using local Mongo DB?

I have set up a local Mongo Database which I initialise as follows:

(shell 1)
> mongo
mongo> use prod-db

I then start my local server:

(shell 2)
> yarn start:server

and I then start my ember app:

(shell 3)
> yarn start:my-ember-app

I now want to write some ember tests and for this I do not want to use ember-cli-mirage. I want to use the actual local server I mention above and I also want to use my local Mondo DB, just not the prod-db database but a test-db one.

In other words I want to do:

(shell 1)
> mongo
mongo > use test-db

(shell 2)
> yarn start:server

(shell 3)
> yarn run:ember-tests

However, I do not want to do all of the above every time I want to run my ember tests. I only want to do

yarn run:ember-tests

And I want the rest (1. starting the local MongoDB using the test-db database 2. starting the local server) to happen "internally" without me having to open up separate shells manually etc..)

Is this possible and how ?




In Ember.js how do you extend a component and trigger an action on did-insert?

Our project is currently using Ember 3.12 and we are trying to upgrade to using Ember 3.20, but we are having an issue with extending an ember-power-select component (which now uses Glimmer components). In our extended component we need to call a method when the component is inserted and have access to component element, which we did using didInsertElement in Ember 3.12, but we now need to use a did-insert modifier. However, when we create a template file of our own which contains an element which triggers the did-insert modifier the power-select element is not displayed (because our template file has replaced it). I would rather not copy the entire contents of the power-select.hbs file into our own file and wrap it in a div that contains the did-insert modifier so that we can get access the component element in the action. Is there a pattern for this situation? Like templates can now be extended or there is another way to trigger an action when the component is inserted (and still get access to the component's element)?




mardi 20 avril 2021

Showing error while using response.json() in ember js to fetch response from API

I have to create a web app to add a user in mySQL Database and implement UI using ember js.

app/components/user.hbs

   <h1>User Management!</h1>
<div>   
    <label1>User Id </label1>   <colon1>:</colon1>
    <input1></input1>
    <label2>Firstname</label2>  <colon2>:</colon2>
    <input2></input2>
    <label3>Lastname</label3>   <colon3>:</colon3>
    <input3></input3>
    <label4>Mail Id</label4>    <colon4>:</colon4>
    <input4></input4>
</div>
    <button1 >Add User</button1>
    <button2 >Delete User</button2>

app/components/user.js

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

export default class UserComponent extends Component {
    @action 
    async user (type,id,firstname,lastname,mailid){
        let response=await fetch("http://localhost:8080/UserManagement/UserManagementServlet",
        {   method: "POST",
            mode:"no-cors",
            headers: { 'Content-Type': 'application/json'},
            body: JSON.stringify({
                "type": type,
                "id": id,
                "firstname":firstname,
                "lastname":lastname,
                "mailid":mailid
            })
        });
        let parsed=await response.json();
        alert(parsed.status);
    }
}

Servlet API code

//Required Header files
@WebServlet("/UserManagementServlet")
public class UserManagementServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException 
    {   res.setContentType("application/json");  
        res.setCharacterEncoding("UTF-8");
        Gson gson=new Gson();
        BufferedReader br=new BufferedReader(new InputStreamReader(req.getInputStream()));
        String param=br.readLine();
        User user = gson.fromJson(param, User.class);
        HashMap<String,String> jsonfile=new HashMap<String,String>();
        PrintWriter out=res.getWriter();
        String url="jdbc:mysql://localhost:3306/employee",username="root";
        String password="root";
        Connection con=null;
        PreparedStatement pst;
        String query="select*from user";
        ResultSet rs;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url,username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Entered");
        if (user.getType().equals("add")) {
            try {
                String insertquery="INSERT INTO user" +"  (id,firstname,lastname,  mailid) VALUES " +" (?,?, ?, ?);";
                pst = con.prepareStatement(insertquery);
                pst.setString(1, String.valueOf(user.getId()));
                pst.setString(2, user.getFirstName());
                pst.setString(3, user.getLastName());
                pst.setString(4, user.getMailid());
                
                jsonfile.put("id", String.valueOf(user.getId()));
                jsonfile.put("firstname", user.getFirstName());
                jsonfile.put("lastname", user.getLastName());
                jsonfile.put("mailid", user.getMailid());
                jsonfile.put("status","User Added Successfully");
                
                String final1=gson.toJson(jsonfile);
                System.out.println(final1);
                out.println(final1);
                
                pst.executeUpdate();   
            } catch (Exception e) {
                out.println("error"+e);
            }
        }
        out.flush();
    }
}

It showed Cors error so I added "mode":"no-cors" in user.js but after that cors error got disappeared but this error didn't.

While Clicking Add User Button, it shows an error in this line " let parsed=await response.json();"

user.js:54 Uncaught (in promise) SyntaxError: Unexpected end of input
    at UserComponent.user (user.js:54)"



How do I obfuscate Javascript in Ember?

Does anyone know how to use the javascript-obfuscator (or similar) in Ember ?

I guess it needs to be called inside ember-cli-build.js but I don't know where and how.

Thank you in advance for any help :)




File management in a webapp

I'm working on a CRUD-webapp where certain entities (tasks, orders,...) have multiple linked files. These files can be uploaded, updated and deleted. Many views use the same logic but with differences in the entities linked, capabilities or view. The files are stored on a different server as the metadata and linked entities.

I'm not sure how to manage this. The main goal is this webapp to function well. It should also have clearly readable code. To be sure my question is understood well, I'll give some more concrete questions:

  • I don't know to which degree it is required to handle errors. e.g. a network connection failed while uploading. How to handle this, keep the metadata in sync,... Is it possible to handle every possible error without out of sync data? Is there a degree of incorrectness that is acceptable in general standards. e.g. The upload of the metadata fails. Should I delete the file from the file server again?

  • How do I structure this code? Is it written in a component or a service? Is duplication allowed, because some details are different for each entity and view to avoid to much parameterization.

The application is using the Ember.js framework. Previously I worked on an Angular project where I struggled to get this right as well. I'm more looking for general applicable advice.

I hope this question is clear enough so I don't get downvoted again. If not, just ask questions.




samedi 17 avril 2021

Can't load module that imports css via ember-auto-import

I am trying to build an ember 3.25 application that imports the CkEditor via ember-auto-import

I was able to get the editor working fine by adding the following to my package.json:

"@ckeditor/ckeditor5-build-classic": "^27.0.0",

and adding the following to my ember component:

import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

...

didInsertElement() {
  var editor = ClassicEditor
    .create( document.querySelector( '#editor' ), {
      ...
    });
}

But when I tried to add the ImageResize module via:

"@ckeditor/ckeditor5-image": "^27.0.0",

and in my component (as instructed here):

import Image from '@ckeditor/ckeditor5-image/src/image';
import ImageResize from '@ckeditor/ckeditor5-image/src/image-resize';

I was initially seeing errors that read: 'UnhandledPromiseRejectionWarning: Error: webpack returned errors to ember-auto-import so I ran AUTO_IMPORT_VERBOSE=true ember serve

I now am seeing errors that ckeditor can't @import nested .css:

ERROR in ./node_modules/@ckeditor/ckeditor5-ui/theme/components/toolbar/toolbar.css 6:0
Module parse failed: Unexpected character '@' (6:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|  */
|
> @import "../../mixins/_unselectable.css";

Or use ES6 syntax:

ERROR in ./node_modules/@ckeditor/ckeditor5-ui/theme/components/dropdown/toolbardropdown.css 6:0
Module parse failed: Unexpected token (6:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|  */
|
> :root {

and errors where it tries to include svg files:

ERROR in ./node_modules/@ckeditor/ckeditor5-widget/theme/icons/drag-handle.svg 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M4 0v1H1v3H0V.5A.5.5 0 0 1 .5 0H4zm8 0h3.5a.5.5 0 0 1 .5.5V4h-1V1h-3V0zM4 16H.5a.5.5 0 0 1-.5-.5V12h1v3h3v1zm8 0v-1h3v-3h1v3.5a.5.5 0
 0 1-.5.5H12z"/><path fill-opacity=".256" d="M1 1h14v14H1z"/><g class="ck-icon__selected-indicator"><path d="M7 0h2v1H7V0zM0 7h1v2H0V7zm15 0h1v2h-1V7zm-8 8h2v1H7v-1z"/><path fill-opacity=".254" d="M1 1h14
v14H1z"/></g></svg>

Based on this message:

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

It seems like I need to add some webpack loaders to ember, but I'm really not sure how to do that. Can anyone help?




vendredi 16 avril 2021

Nested each with table not rendering properly handlebars template

I am facing same issue as in the below links. Can someone help me on this. Please use code link in the github issue. https://github.com/handlebars-lang/handlebars.js/issues/1478




lundi 12 avril 2021

What ID do I use to create user in the backend when using Google Oauth2 's implicit grant login?

I am a Front End Developer with limited experience setting up backends.

I'm building a simple Ember application (with one single route) and I want to use Google's Login button.

When someone logs in the first time I want to create a record of them in the backend. From there on, every time they log back in (same gmail address), I want to be able to query/update their record in the backend.

  1. When the user clicks to log in with Google, Google returns me an id_token which is the one I'm supposed to use in the Backend.
  2. I then create/authenticate the session for that user by using ember-simple-auth:
this.session.authenticate('authenticator:oauth2-implicit-grant', {
  access_token: id_token // the one received by Google
})
  1. Then I get the access_token generated by ember-simple-auth to find that user in the backend (or create them if this is a new user):
let { access_token }  = this.session.data.authenticated // ember-simple-auth
let user = await this.store.findRecord('user', access_token)
  1. And then in the backend I'm doing:
this.get('/users/:access_token', ({ users }, { params }) => {
  let user = users.find(*params.access_token or something else?*)
  
  // is the user doesn't exist yet I create them
  if (!user) {
    // I realised that if I use params.access_token
    // this will change in the future for the same Gmail account
    // so what identifier do I need to use to create the user the 1st time so that it's permanent ? 
    user = users.create({ id: *params.access_token or something else?* })
  }

  return new Response(200, {}, { user })
})

My question is about which identifier to use in the backend route handler you see above, in order to create the user and then query/update their record during future visits.

Thank you in advance for your help!

EDIT (thinking it about it a bit more): is the access_token only supposed to be used by ember-simple-auth and not by my backend/database at all? In which case is it google's id_token that I should use in the backend ? Is the id_token I received bound to that email address permanently?




jeudi 8 avril 2021

How to detect the client's country from the server side in an Ember site?

I have been trying to use https:ip2c.org/self, yet it is rather giving me not precise info. Somebody suggested https://www.npmjs.com/package/@maxmind/geoip2-node, yet some help is needed.




dimanche 4 avril 2021

Wanted to call action of the linking controller in ember js?

<span >Login
the above code is in my ember signup template , i have linked to login template. I wanted to call my 'loginfunc' in my login controller, but the complier is checking 'loginfunc' inside the sign up controller, can you please tell me why, i'm a beginner. someone guide me with this.




Ember pod style component SCSS: variable undefined

I am working on a pod-style ember app that uses ember-cli-sass, and ember-component-css.

I defined a variable in app/styles/app.scss that looks like this:

$yellow: #f2d173;

But when I try to use that variable in the scss file of a component located at: app/components/login-form/styles.scss, I get an error that reads:

Error: Undefined variable.

I would have expected the app.scss file to get loaded first, and for my variable to be accessible within my components - but something is not working perfectly.

Does any one know how to get application-wide scss/sass variables to be accessible in my components?