mercredi 7 août 2019

Best way to utilize a serializer in Ember.js to support a different payload key?

When running the following line of code:

this.get('store').query('domain-message', 
{
    domainId: user.defaultDomain.id
});

>>/api/domain-messages?domainId=1

this error is returned:

The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use store.queryRecord to query for a single record. Error: Assertion Failed: The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use store.queryRecord to query for a single record.

I have a model in app/pods/domain-message/model.js that looks like so:

import DS from 'ember-data';
import attr from 'ember-data/attr';

export default DS.Model.extend({
    campaignId: attr('number'),
    orgId: attr('number'),
    orgName: attr('string'),
    userId: attr('number'),
    memberId: attr('number'),
    messageSubject: attr('string'),
    messageBody: attr('string'),
    attachmentLink: attr('string'),
    //sentTimestamp: attr('date'),
    //receivedTimestamp: attr('date'),
    //archivedTimestamp: attr('date'),
    messageSeen: attr('boolean'),
    messageRead: attr('boolean'),
    parentMessageId: attr('number'),
    actionCount: attr('number'),
    completedActionCount: attr('number'),
    //actionStatusUpdatedTimestamp: attr('date'),
});

When inspecting the network for this query, the payload data is as follows:

{"messages":[{"id":1,"campaignId":1,"orgId":1,"orgName":"TestOrg","userId":120,"memberId":"12345","messageSubject":"Test Message","messageBody":"test test test","attachmentLink":"https://google.com","sentTimestamp":null,"receivedTimestamp":"2019-08-07T17:01:39Z","archivedTimestamp":null,"messageSeen":false,"messageRead":false,"parentMessageId":0,"actionCount":0,"completedActionCount":0,"actionStatusUpdatedTimestamp":"2019-08-07T17:01:39Z"},{"id":2,"campaignId":1,"orgId":1,"orgName":"TestOrg2","userId":120,"memberId":"12349","messageSubject":"Hello","messageBody":"How are you?","attachmentLink":"https://google.com","sentTimestamp":null,"receivedTimestamp":"2019-08-07T17:07:39Z","archivedTimestamp":null,"messageSeen":false,"messageRead":false,"parentMessageId":0,"actionCount":0,"completedActionCount":0,"actionStatusUpdatedTimestamp":"2019-08-07T17:07:39Z"}],"meta":{"count":2,"total":2,"offset":null,"limit":null}}

Notice how the payloadKey is "members", this may be causing the issue since it may have to be the same as the models name. Is there anyway to modify this payloadKey and change it so that the model above supports it?

I am not using a serializer, but I do know that it may be required to do so to make this work. Can anyone suggest the best route to suppress this error? When generating a serializer, it will be located in app/pods/domain-message/serializer.js.

Thanks in advanced.




if id is invalid, go to another ember route

I have an ember project, the main concep is there is a list of books on the route /books, but you can pass in a book id in /books/1 and it would view that book only. Here is the router i made...

Router.map(function()
{
    this.route('books', {path: '/'});
    this.route('books', {path: '/*path'});
    this.route('books', {path: 'books/:book_id'});
});

So my default path will always be /books except if the user passes in an id

On my books route, I have the following functions

setupController(controller, model)
{
    this._super(controller);
    controller.loadBook(model.book_id);
},

model(params)
{
    return params;
}

So the model function returns the id and the setupController function will run on init and call the loadBook function in the controller passing in the id

In my controller I have my loadBook function

routerService: service('router'),

loadBook(book)
{
    const validBook = (book === 1);
    if (!validBook)
    {
        console.log('transitioning');
        this.get('routerService').transitionTo('books');
    }
}

So this works, if I go to /books/1, Its a valid book. But if I go to books/2, It will go in that function and transition to /books but the url is still books/2.

Is there any way to actually transition to /books so the url says that, thanks




Unexpected token error when migrating to native classes for components

I upgraded to Ember 3.11 and I want to start using native classes for my components. When I change a component class to something similar like:

    export default class MyClassName extends BaseComponent {

        myFieldName;

I get a build error "Parsing error: Unexpected token ;" because of the class field.

Ideas how to make sure ember-cli doesn't complain about the new syntax are more than welcome.

Thanks




mardi 6 août 2019

Disabled on buttons does not seem to take effect

I just started learning ember today. (Trying to do yoember.com) tutorial. Please excuse my newbie questions.

I'm experiencing some issues and I am not sure what I am doing wrong.

Issue:

  • Disabled does not work (it always enables the button)

What I am doing:

  • I have a contact page which has email, message and submit button.
  • I want to disable the button initially (When there is no email, message)

This is what I've done so far:

contact.hbs:

<h1>Contact Page</h1>
<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="text">Text</label>
    <textarea type="textarea" class="form-control" id="text" placeholder="Text" rows="4" cols="50" value=></textarea>
  </div>
  <button disabled=  type="submit" class="btn btn-primary">Submit</button>
</form>

Contact.js

import Route from '@ember/routing/route';
import { match, not } from '@ember/object/computed';

export default Route.extend({
    emailAddress: '',
    message: '',
    isValid: match('emailAddress', /^.+@.+\..+$/),
    isDisabled: not('isValid'),

    actions: {
        submitButton () {
            alert(`Saving of the following email address is in progress:`);
        }
      }
});

Questions:

1) What am I doing wrong? Why is the button always enabled?

2) What is the difference when I do value=emailAddress vs value=




Is it possible to run ember fastboot only for search crowlers

Ember fastboot works fine. But is it possible to have both static files for browser-clients and fastboot server for search engines crawlers?




Adding Ember.js frontend app to Node.js backend app

I have a running ember.js frontend app. Also have a node.js backend app which can do basic CRUD operations from MongoDB. Using Postman I can see that my node.js app is returning JSON data properly.

I want my frontend to use the backend to do CRUD operations on MongoDB. I am new to ember.js so I want a guideline where I can understand to use the JSON data from the node.js app and use with ember.js frontend.

My ember.js app already is using a mock server. It has a "dist" folder inside.

My adapter/application.js file in ember.js frontend:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'api' 
});

I want to use my localhost:3000 node server here. Do not know where to add it.




lundi 5 août 2019

My Application is not responding to the request given by front end and throwing a CORS exception

I have created a web service using dropwizard application.

  1. Through this I am able to create resources package wherein I have created entity for indexing the document, search request, getting doc by id.

  2. By hitting the api in postman I get the desired result.

  3. For developing the web application I built the front end using ember.js.

  4. But when I send request to my application I am getting CORS policy exception.

    • When I am sending request through postman to http://localhost:9090 (9090 is the port number of my ApplicationConnector) then it is respnding to the request.
    • Now when I send request from origin http://localhost:4200 (4200is the default port number for ember.js) to http://localhost:9090 it is giving error :

Access to XMLHttpRequest at http://localhost:9090/{indexName}/{id} >from origin http://localhost:4200 has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access->Control-Allow-Origin' header is present on the requested resource.

So can someone please explain how to resolve this issue and if there is any other way apart from enabling CORS in Dropwizard ?