Edit RESTAdapter url for API end point - javascript

I have an api endpoint that requires a / at the end of it, but Ember does not add the /. Is there a way to edit the URL that the RESTAdapter creates so that it adds this slash?
Currently the URL ember sends is http://www.myapi.com/v1/roles
I need the URL to look like this: http://www.myapi.com/v1/roles/
Here is my current ApplicationAdapter:
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function() {
console.log('error');
},
host: 'http://www.myapi.com',
namespace: 'v1'
});
Here is my router:
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
return this.store.find('role');
}
});

You'll want to override the buildURL function on your ApplicationAdapter to append the trailing slash. You can just call the default buildURL that DS.RESTAdapter provides and then append the slash.
Here's what the code will look like:
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function() {
console.log('error');
},
host: 'http://www.myapi.com',
namespace: 'v1',
buildURL: function(type, id, record) {
//call the default buildURL and then append a slash
return this._super(type, id, record) + '/';
}
});
Here's the documentation for buildURL.

Related

Ember data fetch json file

I'm trying to get data from json file from server. My code:
adapters/application.js:
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
host: 'http://exampleweb.com',
namespace: 'file.json'
});
models/item.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string')
});
routes/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.get('store').findAll('item');
}
});
templates/application.hbs
{{#each model as |item|}}
{{item.name}}<br>
{{/each}}
JSON file on server look like this:
{
"Products": [
{
"name": "Aviator"
},
{
"name": "Dark"
}]
}
Now ember requst http://exampleweb.com/file.json/items. How can I get this Products correctly and display them in template?
Depending on your need, you have two options.
If you need to substitute backend for app development, the best choice is using ember-cli-mirage
If you need to get and display file's contents, you may not use ember data and do smth like
return new Promise((resolve, reject) => {
Ember.$.get('/path/to/file.json').then(resolve, reject);
});
in model hook

Dynamic segments in ember js

I'm new to ember js. I was trying to use dynamic segments in my ember project and it give me an error.I tried localhost/4200/profile/john in my browser to get the info of "john".I think it is complaining about api end point in server.js.. Please help me to find what i have done wrong.
error display in console:
GET localhost:4500/api/users/john 404 (Not Found)
These are my files;
router.js
Router.map(function() {
this.resource('profile', { path: '/profile/:username' });
});
model/user.js
import DS from 'ember-data';
export default DS.Model.extend({
docType:DS.attr('string'),
firstName:DS.attr('string'),
userName:DS.attr('string'),
password:DS.attr('string'),
lastName:DS.attr('string'),
mobileNo:DS.attr('string'),
landNo:DS.attr('string'),
address:DS.attr(
{
no:'string',
street:'string',
city:'string'
}
),
nicNo:DS.attr('string'),
created_at:DS.attr('date'),
updated_at:DS.attr('date')
});
route/profile.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params, transition) {
return this.get('store').find('user', params.username);
}
});
server.js
app.get('/api/users', function(req,res) {
UserModel.find({},function(err,docs) {
if(err) {
res.send({error:err});
}
else {
res.send({user:docs});
}
});
});
template/profile.hbs
<h2>Welcome user</h2>
{{#each item in model}}
{{item.userName}}
{{/each}}
You need to add an adapter to your application and tell it where your API is.
//app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
namespace: 'api' //All requests will be made to api/*
});
Beware that the example I gave you is using the JSONAPI Adapter (Ember 2.0) but there's also a RESTAdapter, you have to choose the right one for you.

Promise in Ember route model not resolving/updating

I'm using Ember Simple Auth and a service that gets injected into application controller to keep track of currently logged in user. I can use {{accountName}} for the currently logged in user in my application template by doing the following:
//controllers/applications.js
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service(),
userFromSession: Ember.inject.service('session-user'),
accountName: Ember.computed('session.data.authenticated.userId', function(){
this.get('userFromSession.user').then((user)=>{
if (Ember.isEmpty(user.get('company'))) {
this.set('accountName', user.get('firstName') + ' ' + user.get('firstName'));
} else {
this.set('accountName', user.get('company.name'));
}
});
})
});
My session-user service looks like the following:
//services/session-user.js
import Ember from 'ember';
import DS from 'ember-data';
const { service } = Ember.inject;
export default Ember.Service.extend({
session: service('session'),
store: service(),
user: Ember.computed('session.data.authenticated.userId', function() {
const userId = this.get('session.data.authenticated.userId');
if (!Ember.isEmpty(userId)) {
return DS.PromiseObject.create({
promise: this.get('store').find('user', userId)
});
}
})
});
Now, a user has a company, and a company has opportunities. I would like to retrieve the company opportunities, based on the currently logged in user. How do I do this? In my opportunities route I have tried the following:
//routes/opportunities/index.js
import Ember from 'ember';
export default Ember.Route.extend({
sessionUser: Ember.inject.service('session-user'),
model: function(){
this.get('sessionUser.user').then((user)=>{
let companySlug = user.get('company.slug');
console.log(companySlug);
return this.store.findRecord('company', companySlug);
});
}
});
When using {{model.opportunities}} in my template, it just stays blank and looks like the promise never resolves. However, I can see the data populating in the Ember Inspector, as well as the expected output of my console logs. Further, when I do the following, it works fine:
//routes/opportunities/index.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function(){
let companySlug = 'known-company-slug';
return this.store.findRecord('company', companySlug);
}
});
Which means that the problem lies with model not resolving/updating for some reason. What am I doing wrong here?
Okay so I was trying to get the company model when I already had access to it through the sessionUser service.
//routes/opportunities/index.js
import Ember from 'ember';
export default Ember.Route.extend({
sessionUser: Ember.inject.service('session-user'),
model: function(){
return this.get('sessionUser.user').then(user => user.get('company'));
}
});

Error Nothing handled the action 'sessionInvalidationSucceeded' using Simple Auth Ember JS

So I have been setting up a auth manager through my ember for the past week a and finally got it working. However, I'm still getting a error when invalidating the user.
Nothing handled the action 'sessionInvalidationSucceeded'
Can't figure out what the best way to handle the error?
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.Object.extend({
authenticate: function(controller, user) {
var app = this.container.lookup('controller:application');
var session = app.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', user);
session.then(function() {
console.log('Session Started');
controller.transitionToRoute('brands');
});
},
endSession: function() {
var app = this.container.lookup('controller:application');
var session = app.get('session').invalidate();
session.then(function() {
app.store = DS.Store.create();
console.log('Session Ended');
app.transitionToRoute('index');
app.store.destroy();
});
}
});
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
sessionEnded: function() {
this.authManagerService.endSession();
}
},
currentUser: function() {
return this.store.find('user', this.session.get('user_id');
}.property('#each.user')
});
You need to include the Simple Auth Route mixin on the route you are authenticating
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
or handle the action in your initializer
Ember.Application.initializer({
name: 'authentication',
after: 'simple-auth',
initialize: function(container, application) {
var applicationRoute = container.lookup('route:application');
var session = container.lookup('simple-auth-session:main');
// handle the session events
session.on('sessionInvalidationSucceeded', function() {
applicationRoute.transitionTo('index');
});
}
});
Take a look at the api, it's really helpful
http://ember-simple-auth.com/ember-simple-auth-api-docs.html#SimpleAuth-ApplicationRouteMixin-sessionInvalidationSucceeded

How to get the type of route path in Ember

If I have in the router map:
this.resource('detail', { path: '/detail/:type' }, function() {
...
});
And I retrive the currentPanth in my Ember Application code:
currentPath: '',
ApplicationController : Ember.Controller.extend({
updateCurrentPath: function() {
App.set('currentPath', this.get('currentPath'));
console.log('currentPath',App.currentPath);
}.observes('currentPath')
}),
When I navigate in my app, I get the route names by console, but when It is "detail" I get "detail.index". How can I get the type?
you only have access to the params in the route, ie. when you are defining your model:
App.Router.map(function() {
this.resource('photo', { path: '/photos/:photo_id' });
});
App.PhotoRoute = Ember.Route.extend({
model: function(params) {
return Ember.$.getJSON('/photos/'+params.photo_id);
}
});
Or you can also use paramsFor, also in the route only.
Depending on what you are trying to acomplish maybe query params suit better

Categories

Resources