Debugging Ember-cli-mirage when routes are not being called - ember-cli

I have successfully created one route in ember-cli-mirage, but am having trouble loading the related data.
The API should be returning JSON API compliant data.
I'm not really sure if there are any good methods or not for debugging mirage's request interception. Here is my config.js
export default function() {
this.urlPrefix = 'https://myserver/';
this.namespace = 'api/v1';
this.get('/machines', function(db, request) {
return {
data: db.machines.map(attrs => (
{
type: 'machines',
id: attrs.id,
attributes: attrs
}
))
};
});
this.get('/machines/:id', function(db, request){
let id = request.params.id;
debugger;
return {
data: {
type: 'machines',
id: id,
attributes: db.machines.find(id),
relationships:{
"service-orders": db["service-orders"].where({machineId: id})
}
}
};
});
this.get('/machines/:machine_id/service-orders', function(db, request){
debugger; // this never gets caught
});
}
Most of this is working fine (I think). I can create machines and service orders in the factory and see the db object being updated. However, where my application would normally make a call to the api for service-orders: //myserver/machines/:machine_id/service-orders, the request is not caught and nothing goes out to the API
EDIT:
This is the route that my Ember app is using for /machines/:machine_id/service-orders:
export default Ember.Route.extend(MachineFunctionalRouteMixin, {
model: function() {
var machine = this.modelFor('machines.show');
var serviceOrders = machine.get('serviceOrders');
return serviceOrders;
},
setupController: function(controller, model) {
this._super(controller, model);
}
});
And the model for machines/show:
export default Ember.Route.extend({
model: function(params) {
var machine = this.store.find('machine', params.machine_id);
return machine;
},
setupController: function(controller, model) {
this._super(controller, model);
var machinesController = this.controllerFor('machines');
machinesController.set('attrs.currentMachine', model);
}
});
Intuitively, I would think that machine.get('serviceOrders'); would make a call to the API that would be intercepted and handled by Mirage. Which does not seem to be the case

Related

Wuxt.js (Nuxt.js) getting out data from axios response

I want to fetch out menu items from the Wordpress json response with Wuxt framework (Nuxt + Wordpress), but I can't access the data object outside the fetch (error message is that data is not defined)
This is my code
<script>
import axios from 'axios'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
async fetch ({ params, error }) {
try {
let { data } = await axios.get('http://localhost:3080/wp-json/wuxt/v1/menu')
return data
} catch (e) {
error({ message: 'Not found', statusCode: 404 })
}
}
}
</script>
How can the data object be accessed, for inserting into the template?
If you are using fetch than all your data should be commiting into store, and accessed from it. If you want to return data, use asyncData method.
I had to change the code a bit, that it returns a data function with variable, so it looks like this.
export default {
components: {
Logo
},
data() {
return { menus: [] }
},
mounted() {
fetch('http://localhost:3080/wp-json/wuxt/v1/menu')
.then(response => {
response.json().then(menus => {
this.menus = menus;
})
})
}
}

Issue Connecting to MongoDB collections

I am using axios and express.js API to connect to my mongo DB. I have a .get() request that works for one collection and doesn't work for any other collection. This currently will connect to the database and can access one of the collections called users. I have another collection setup under the same database called tasks, I have both users and tasks setup the same way and being used the same way in the code. The users can connect to the DB (get, post) and the tasks fails to connect to the collection when calling the get or the post functions. When viewing the .get() API request in the browser it just hangs and never returns anything or finishes the request.
any help would be greatly appreciated!
The project is on GitHub under SCRUM-150.
API connection
MONGO_URI=mongodb://localhost:27017/mydb
Working
methods: {
//load all users from DB, we call this often to make sure the data is up to date
load() {
http
.get("users")
.then(response => {
this.users = response.data.users;
})
.catch(e => {
this.errors.push(e);
});
},
//opens delete dialog
setupDelete(user) {
this.userToDelete = user;
this.deleteDialog = true;
},
//opens edit dialog
setupEdit(user) {
Object.keys(user).forEach(key => {
this.userToEdit[key] = user[key];
});
this.editName = user.name;
this.editDialog = true;
},
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource) {
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
}
},
//get those users
mounted() {
this.load();
}
};
Broken
methods: {
//load all tasks from DB, we call this often to make sure the data is up to date
load() {
http
.get("tasks")
.then(response => {
this.tasks = response.data.tasks
})
.catch(e => {
this.errors.push(e);
});
},
//opens delete dialog
setupDelete(tasks) {
this.taskToDelete = tasks;
this.deleteDialog = true;
},
//opens edit dialog
setupEdit(tasks) {
Object.keys(tasks).forEach(key => {
this.taskToEdit[key] = tasks[key];
});
this.editName = tasks.name;
this.editDialog = true;
},
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource) {
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
}
},
//get those tasks
mounted() {
this.load();
}
};
Are you setting any access controls in the code?
Also refer to mongoDB's documentation here:
https://docs.mongodb.com/manual/core/collection-level-access-control/
Here is my solution:
In your app.js, have this:
let mongoose = require('mongoose');
mongoose.connect('Your/Database/Url', {
keepAlive : true,
reconnectTries: 2,
useMongoClient: true
});
In your route have this:
let mongoose = require('mongoose');
let db = mongoose.connection;
fetchAndSendDatabase('yourCollectionName', db);
function fetchAndSendDatabase(dbName, db) {
db.collection(dbName).find({}).toArray(function(err, result) {
if( err ) {
console.log("couldn't get database items. " + err);
}
else {
console.log('Database received successfully');
}
});
}

FirstOrDefaultAsync() Hangs MVC5

Someone please help me not kill my Server.. Here's my MVC controller action:
(Don't worry about names, I'm mid-refactoring)
public async Task<ActionResult> AllByLead(int leadId)
{
try
{
var lead = await _researchService.GetLeadWithContacts(leadId);
var contactViewModels = Mapper.Map<Lead, List<ContactViewModel>>(lead);
contactViewModels.Each(contact => PopulateContactOptions(contact));
var listViewModel = new ContactListViewModel {Results = contactViewModels};
return PartialView(listViewModel);
}
catch
{
return Json(string.Format(Resources.BasicErrorMessageFormat, "Error retrieving Lead Contacts"),
JsonRequestBehavior.AllowGet);
}
}
Service:
public async Task<Lead> GetLeadWithContacts(int leadId)
{
return await _repository.GetLeadWithContacts(leadId).ConfigureAwait(false);
}
Repo:
public async Task<Lead> GetLeadWithContacts(int leadId)
{
var leadEntity = await _context.Leads
.Where(lead => lead.LeadID == leadId)
//.Include(lead => lead.LeadContactMaps.Select(map => map.Contact.Addresses))
//.Include(lead => lead.LeadContactMaps.Select(map => map.Contact.PhoneNumbers))
//.Include(lead => lead.Organizations.Select(business => business.Addresses))
//.Include(lead => lead.Organizations.Select(business => business.PhoneNumbers))
.FirstOrDefaultAsync();
return leadEntity;
}
EDIT
DbContext Module
internal class DbContextModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(ctx => new CRTechEntities()).InstancePerLifetimeScope();
}
}
JS Ajax Call:
function populateContactList() {
var leadId = $("#LeadId").val();
$.ajax({
url: url + "/Contact/AllByLead/",
type: "GET",
data: { 'leadId': leadId },
success: function(data) {
$("#contactContainer").html(data);
},
error: function(data) {
}
});
}
Bonus points on if you can school me on my includes, they may very well be terrible.. It's pretty slow just grabbing the lead right now. Hence the async change. I'd like to see if it will be easier on the system with more users. (I can do my own profiling/tests on whether explicit loading will be better here, just saying..)
Anyway, I hit this, the server is completely borked when the await FirstOrDefaultAsync() gets hit.
EDIT 2: I've updated the controller action to show exactly what I'm doing here. I only included the code that was being hit originally.
Um, are you returning anything in your controller? That would cause it to hang.
Try
public async Task<JsonResult> AllByLead(int leadId)
{
var lead = await _researchService.GetLeadWithContacts(leadId);
return Json(lead);
}

Call controller on afterCreate

I have the following code for my Sessions model:
module.exports = {
attributes: {
},
afterCreate: function(value,next) {
next();
}
};
And the following Sessions Controller:
module.exports = {
saveSession: function(res,req) {
console.log('in save');
}
};
I want to save a value to a user's session afterCreate
How can I call the saveSession function from my model? I tried Sessions.saveSession() but it doesn't work.
I don't think you need a session model and it's not a good idea to call a controller method directly.
I'd recommend just set req.session when you're trying to save the session and it'll be auto-saved when you respond from that controller action.
afterCreate will never have access to req unless you pass it down which I wouldn't recommend.
The pattern is something like:
{
// …
login: function (req,res) {
User.findOne({
username: req.param('username'),
password: req.param('password')
}).exec(function (err, user) {
if (err) return res.serverError(err);
if (!user) return res.view('/login');
req.session.user = user.toJSON();
return res.redirect('/dashboard');
});
}
// ...
I think that you want to save a value to a cookie or create another database record am i correct?
If so, you dont need to call a controller action from the model (not recommended), you just need to create a new record or save the value to the cookie, here are some alternatives that i see possible in your scenario.
creating another record:
// on models/YourModel
module.exports = {
attributes: {
},
afterCreate: function(newlyInsertedRecord,next) {
ModelOrResource.create({
param1: newlyInsertedRecord.attributeYouWant,
param2: value2
// and so on
}).exec(function(err, recordCreated){
if(err) return next(err);
// do somethign with recordCreated if you need to
// ...
next();
})
}
};
Saving a value to a cookie:
module.exports = {
attributes: {
},
afterCreate: function(newlyInsertedRecord, next) {
// do some other stuff not related to calling a controller action ;)
next();
}
};
This code was retrived from snippets from my own projects, so it should work on sails 0.9.x
Hope it helps!

Angular.js - cascaded selects with AJAX loading

I have two selects: one for country, other for regions. Country select is filled statically, but region select has to be filled dependent on current country through POST request.
I already made a server method which responds to country parameter with corresponding JSON, made a code for loading data into the select, but when I put this code into a watch it does not work properly:
.....................
]).factory('helperService', [
'$http', '$log', function($http, console) {
var checkDiscount, getRegions;
getRegions = function(countryCode) {
return $http({
method: 'POST',
url: '/api/regions/',
data: {
country_code: countryCode
}
});
};
.....................
]).controller('orderController', [
.....................
$scope.$watch('billing_country', function(value) {
helperService.getRegions($scope.country).success(function(result) {
$scope.regions = result;
return $scope.order.billing_state = $scope.regions[0];
});
return $scope.country = value;
});
Your call to factory must return an object, currently it isn't returning anything at all.
Change it to the following:
.factory('helperService', ['$http', '$log', function($http, console) {
var checkDiscount;
var service = {
getRegions: function(countryCode) {
return $http({ method: 'POST',
url: '/api/regions/',
data: { country_code: countryCode }
});
}
};
return service;
}])/****/
And then your call to helperService.getRegions will work.