lundi 3 juillet 2017

Ember not calling setupController of router

So, I have two paths in my route. I created the two routes as the doc recommends.

My router is the following:

// router.js
Router.map(function() {
  this.route('photos');
  this.route('photo', { path: '/photo/:photo_id' });
});

If I visit firstly the route /photo/ID and then go to /photos, it will only show one object on the latter. (wrong)

If I visit /photos first it shows all the objects and I can go to /photo/ID later on and it will be fine. (right)

I want to make it work both ways. How to do this? You can see my code for each route down below:

// photo.js
export default Ember.Route.extend({
  model(params) {
    return this.get('store').findRecord('photo', params.photo_id);
  }
});

// photos.js
export default Ember.Route.extend({
  setupController(controller, model) {
    let photos = this.get('store').findAll('photo');
    console.log('add all...');
    // convert to an array so I can modify it later
    photos.then(()=> {
      controller.set('photos', photos.toArray());
    });
  },
});

I can always call the findAll() function regardless where the user goes, but I don't think this is smart.




how to add personalized name while excel export in kendo?

i have created a kendo grid but while downloading excel template i want to give some suitable name to the excel file . how to deal with it. here is my code.

resizable: true,
                            sortable: true,
                            pageable: Instance.pageable,
                            groupable: Ember.isPresent(Instance.groupable) ?Instance.groupable : false,
                            filterable: true,
                            reorderable: true,
                            toolbar: Instance.toolbar,
                            excel:  Instance.excel,
                            columns: Instance.columns,

how to give my file suitable name??




How to append an pre-filled textarea content using fillIn

I have a textarea which is already filled in with value using fillIn function. But now I want to append the same textarea with another character '@'. But when I tried using fillIn again; it rewrites the textarea. How can I append the text. I need it to be in two step process.

HTML:

<textarea data-test-id='descriptor'></textarea>

Test:

test('testing-fillIn', async function(assert){
await fillIn(testSelector('descriptor'), 'First text ');
await fillIn(testSelector('descriptor'), '@');
});

The output should be : First text @




dimanche 2 juillet 2017

Set value session authorizer ember simple-auth

I use ember simple-auth with devise_token in rails, in my adapter my function handleResponse is not invoqued, Why?

My authentication works but authorized not work and my session i can't get the atributes is null


  <br>
  HI
   


this is my adapter code

    // `adapters/application.js`

import Ember from 'ember';
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

const { service } = Ember.inject;
import config from '../config/environment';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
  authorizer: 'authorizer:authorizer-devise',
  host: `${config.apiHost}`,
  namespace: `${config.apiNamespace}`,
  session: service('session'),

  handleResponse(status, headers) {

    if(headers['client']) {
      let newSession = this.get('session.data');
      newSession['authenticated']['accessToken'][0] = headers['access-token'];
      newSession['authenticated']['expiry'][0] = headers['expiry'];
      newSession['authenticated']['tokenType'][0] = headers['token-type'];
      newSession['authenticated']['uid'][0] = headers['uid'];
      newSession['authenticated']['client'][0] = headers['client'];
      this.get('session.store').persist(newSession);
    } else if (status == 401) {
      this.get('session').invalidate();
    }
    return this._super(...arguments);
  }
});

And this is my authenticator code

// `/authenticators/authenticator_devise.js`
import DeviseAuthenticator from 'ember-simple-auth/authenticators/devise';
import Ember from 'ember';
import config from '../config/environment';
const { RSVP, isEmpty, run } = Ember;

export default DeviseAuthenticator.extend({
  session: Ember.inject.service('session'),
  serverTokenEndpoint: `${config.apiHost}/auth/sign_in`,


  restore(data){
    return new RSVP.Promise((resolve, reject) => {
      if (!isEmpty(data.accessToken) && !isEmpty(data.expiry) &&
          !isEmpty(data.tokenType) && !isEmpty(data.uid) && !isEmpty(data.client)) {
        console(data);
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate(identification, password) {
  //console(`${config.apiHost}/${config.apiNamespace}/auth/sign_in`);
   return new RSVP.Promise((resolve, reject) => {
      const { identificationAttributeName } = this.getProperties('identificationAttributeName');
      const data = { password };
      data[identificationAttributeName] = identification;
      this.makeRequest(data).then(function(response) {
        if(response.status != 401) {
          var result = {
            accessToken: response.headers.map['access-token'],
            expiry: response.headers.map['expiry'],
            tokenType: response.headers.map['token-type'],
            uid: response.headers.map['uid'],
            client: response.headers.map['client']
          };
          run(null, resolve, result);
        }else {
          alert("Usuario o password incorrecto");
        }

      }, function(xhr) {
        run(null, reject, xhr.responseJSON || xhr.responseText);
      });
    });
  },

  invalidate() {
    return new RSVP.Promise((resolve, reject)=> {
      Ember.$.ajax({
        type: "DELETE",
        url: `${config.apiHost}/auth/sign_out`,
        headers: {
          'uid': 'prueba@prueba.com',
        }
      }).then(function(response) {
        Ember.run(function() {
          resolve(response);
        });
      }, function(xhr, status, error) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });

  }

});

and my authorized

// `/authorizers/authorizer_devise.js`

import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';

const { service } = Ember.inject;

export default Base.extend({
  session: service('session'),
  authorize(data, block) {
    console("entro a authorize");
    const accessToken = data.accessToken[0];
    const expiry = data.expiry[0];
    const tokenType = data.tokenType[0];
    const uid = data.uid[0];
    const client = data.client[0];
    if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
      block('Authorization', `Bearer ${accessToken}`);
      block('access-token', accessToken);
      block('expiry', expiry);
      block('token-type', tokenType);
      block('uid', uid);
      block('client', client);
    }
  }
});

And in my logi-component i invoque the authenticator

import Ember from 'ember';

export default Ember.Component.extend({
    session: Ember.inject.service('session'),
    actions:{
        authenticate(){

            this.get('session').authenticate('authenticator:authenticator-devise', this.get('email'), this.get('password'));


        }
    }
});




Fetching records and nested relations

I have a route in my app (repo) where i fetch bookings belonging to a user, I also include rentals and rentals.rental-ratings in the request. Now, a rental (which belongsTo a Booking) hasMany rentalRatings, and rentalRatings belongsTo Users. In the template I have a component that accepts booking and a rentalRating as arguements. How can I get a rating that belongsTo the booking and the currentUser?

Bookings route:

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  sessionAccount: Ember.inject.service(),

  model() {
    const currentUser = this.get('sessionAccount.currentUser');

    return this.get('store').query('booking', {
      filter: {
        'user_id': currentUser.id
      },
      include: 'rental,rental.rental-ratings'
    });
  }
});

Bookings template:

<h1>Your bookings</h1>

  





Ember + Firebare: Getting property generated by Could Function when saving record completes

I use a Cloud Function to generate a short unique URL on a record on the 'onWrite' event, and save it. This works well, but when I save a record from my Ember app using EmberFire, I do get a model back as an argument to a callback, but the URL of this model is undefined. Is there a way to return this back to the client? Or do I need to query the record to get the generated URL?

This is how my Clound Function code looks:

exports.generateUrl = functions.database.ref('/tournaments/{tid}')
  .onWrite(event => {
    if (event.data.previous.exists()) {
      return;
    }
    if (!event.data.exists()) {
      return;
    }

    const url = shortid.generate();

    return event.data.ref.update({ url });
  });

Here is my component that saves data through form submission. I'm using an add-on called ember-changeset to handle some validations, but this shouldn't be related to the issue.

export default Ember.Component.extend({

  submit(e) {
    e.preventDefault();

    let snapshot = this.changeset.snapshot();

    return this.changeset
      .cast(Object.keys(this.get('schema')))
      .validate()
      .then(() => {
        if (this.changeset.get('isValid')) {
          return this.changeset
            .save()
            .then((result) => {
                // Here, result.get('url') is undefined.
            })
        }
      })
  }
});




Ember-simple-auth cant get currentUser after reload

I have a simple Ember app (repo) with authentication using ember-simple-auth (i followed this article http://ift.tt/2sB6w2m). After logging in I have access to currentUser in my routes, controllers and templates. However, if I navigate to any route besides my ApplicationRoute and reload the browser, I can no longer access currentUser in that route, but it's available in the template. If I navigate back to application route and navigate to different one again, then I can access the currentUser. How can I fix this, i.e. I want to be able to access currentUser in any route even after reload?

ApplicationRoute:

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  sessionAccount: Ember.inject.service(),
  beforeModel() {
    this.get('sessionAccount').loadCurrentUser();
  }
});

SessionAccount service:

import Ember from 'ember';

const { inject: { service }, RSVP } = Ember;

export default Ember.Service.extend({
  session: service('session'),
  store: service(),


  loadCurrentUser() {
    if (this.get('session.isAuthenticated')) {
      this.get('store')
      .queryRecord('user', { me: true })
      .then((user) => {
        this.set('currentUser', user);
      });
    } else {
      return RSVP.resolve();
    }
  }
});

Bookings route - the 'other' route:

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  sessionAccount: Ember.inject.service(),

  model() {
    const currentUser = this.get('sessionAccount.currentUser');

    return this.get('store').query('booking', {
      filter: {
        'user_id': currentUser.id
      },
      include: 'rental,rental.rental-ratings'
    });
  }
});