Get single record from collection in ember-cli-mirage - ember.js

How can I return a record that matches some custom id (not the regular id) from my collection?
// record schema
{
id: 123, // assigned id from mirage
dId: 'DEVICE0001', // device id I want to use to pick
value: 'some content'
}
To select with something like this:
// app/mirage/config.js
this.get("/something/:device_did", function(db, request){
var did = request.params.device_did;
// select using my device id
return db.devices.firstWhere( { 'dId': did });
});
The API docs only reference a 'find()' function that acts on the id, and a 'where()' that gets an array of records.

select the first element from the models array!
var device = db.devices.where({'dId' : did });
return device.models[0];

Related

SuiteScript - Map/Reduce summarize

I am writing a map/reduce script to search for a custom record and create a CSV file from its results.
Firstly, in the getInputData() creating a search and returning its results.
After that comes the map function where I am using JSON.parse to parse the result values.
I have an array declared globally as var data = '' in which I am pushing the values I get in map function.
But when all the looping ends in map() and it enters summarize(), the data array becomes empty again.
I want that data array to be called in summarize() where I can use file.create() function to create the csv file.
I used return data; in map() but it is showing as empty when in summarize().
You have to use context.write at the end of map to send data to the next stage.
context.write({
key: key,
value: value
});
Adding a simple script to show how to access values in the summarize stage:
/**
*#NApiVersion 2.x
*#NScriptType MapReduceScript
*/
define([],
function () {
function getInputData() {
return [{
id: 1,
value: 'abc'
}, {
id: 2,
value: 'def'
}];
}
function map(context) {
var value = JSON.parse(context.value);
context.write({
key: value.id,
value: value.value
});
}
function summarize(context) {
var values = [];
context.output.iterator().each(function (key, value) {
log.debug({
title: 'Output for key ' + key,
details: value
});
values.push(value);
return true;
});
log.debug({
title: 'Summary',
details: JSON.stringify(values)
});
}
return {
getInputData: getInputData,
map: map,
summarize: summarize
}
});

How to access data of another persisted model of loopback from remote method of one persisted model?

'use strict';
module.exports = function (City) {
City.GetCurrentPopulation = function (req) {
var population;
City.app.models.Pupulation.find({where{id:req.id}}, //This line //gives me an error that cannot read property 'find' of undefined
function(req.res){
population=res.population;
});
response='Population for ' +req.cname ' is' +population;
req(null, response);
};
City.remoteMethod(
'GetCurrentPopulation', {
http: {
path: '/GetCurrentPopulation',
verb: 'GetCurrentPopulation'
},
returns: {
arg: 'startdate',
type: 'string'
}
}
);
There is a model city and i want to access another model like "population.find(some filters)" How to do this?
I have a remote method written in city model. Where i am trying to access population record as
var countryp=population.find(where{id:4});
var currentpopulation=countryp.Totalpopulation;
It gives an error population.find is not a function.
Please suggest way to do this.
City.app.models.Population can only work if you defined some relation between City & Population models. Otherwise it wont work that way. If there is no relation to the other model. You need to get a reference to the app object using
Try like this:
var app = require('../../server/server');
module.exports = function (City) {
var Population = app.models.Population;
City.GetCurrentPopulation = function(req) {
Population.find({where{id:req.id}}, function (err) {
if (err) {
return console.log(err);
} else {
// do something here
});
}
You can refer to the documentation here https://loopback.io/doc/en/lb3/Working-with-LoopBack-objects.html#using-model-objects

How to get list of items from DynamoDB with HashKey while using HashKey+RangeKey combination?

I have my table with UserId(hashkey)+id(Rangekey). they are only together unique as expected.
[DynamoDBTable("Item")]
public class Item
{
[DynamoDBHashKey]
public string UserId { get; set; }
[DynamoDBRangeKey]
public string id { get; set; }
}
now I want to get all the table items for a UserId. I tried as below using xamarin sdk loadasync function with parameter of an existing UserId.
var client = new
Amazon.DynamoDBv2.AmazonDynamoDBClient(AWS.DynamoDBhelper.Credentials,
Amazon.RegionEndpoint.USEast1);
Amazon.DynamoDBv2.DataModel.DynamoDBContext context = new
Amazon.DynamoDBv2.DataModel.DynamoDBContext(client);
Items= await context.LoadAsync<List<Item>>("14354365");
But i get exception as below, it looks like It expects not list because it assumes there should be table with table with list.
How can I achieve this?
There is also QueryAsync function but I am not sure what is the difference between LoadAsync.
ex = {System.InvalidOperationException: Must have one hash key defined
for the table List`1
at Amazon.DynamoDBv2.DataModel.DynamoDBContext.MakeKey (System.Object
hashKey, System.Object rangeKey,
Amazon.DynamoDBv2.DataModel.ItemStorageConfig storageConfig, Amaz...
Your code:
var client = new Amazon.DynamoDBv2.AmazonDynamoDBClient(
AWS.DynamoDBhelper.Credentials,
Amazon.RegionEndpoint.USEast1
);
Amazon.DynamoDBv2.DataModel.DynamoDBContext context = new
Amazon.DynamoDBv2.DataModel.DynamoDBContext(client);
Items= await context.LoadAsync<List<Item>>("14354365");`
Should read:
var client = new Amazon.DynamoDBv2.AmazonDynamoDBClient(
AWS.DynamoDBhelper.Credentials,
Amazon.RegionEndpoint.USEast1
);
Amazon.DynamoDBv2.DataModel.DynamoDBContext context = new
Amazon.DynamoDBv2.DataModel.DynamoDBContext(client);
items= await context.QueryAsync<Item>("14354365").GetRemainingAsync();
You should be able to use LoadAsync to get an object by both its hash + range key.
The .NET library has this:
public Task<T> LoadAsync<T>(
object hashKey,
object rangeKey,
DynamoDBOperationConfig operationConfig,
CancellationToken cancellationToken = default(CancellationToken))
Use Load when the method requires only the primary key of the item you want to retrieve.

How to get the changed object of an array when using ember oberver

I am using following code to get the details of the object whose property is changed.
getChangedObject:function(){
console.log('changed name is' , can i get the object here );
}.observes('model.#each.rollNo')
Thanks in advance.
Inside observer you cant get the exact object which caused observer to trigger, but you can try the below approach, like iterating array of model and watch for changed attributes alone.
getChangedObject: function() {
let model = this.get('model');
model.forEach(function(item, index) {
var changedAttributes = item.changedAttributes();
item.eachAttribute(function(item, meta) {
var temp = changedAttributes[item];
if(temp){
console.log(' old value ',temp[0],' new value ',temp[1]);
}
});
})
}.observes('model.#each.rollNo')

Add payload in Ember deleteRecord

I have a requirement to include remarks from user in the payload whenever he tries to delete an item. So far, I have this:
let remarks = this.get('remarks');
let id = this.get('itemID');
this.store.findRecord('item', id).then(function (selectedItem) {
// TODO - DELETE doesn't accept payload in body?
selectedItem.destroyRecord({remarks:remarks}).then(function(response){
Ember.debug('delete successful:'+JSON.stringify(response));
Ember.$('#confirmDelete').modal('hide');
Ember.$('#remarks').val('');
context.set('successful', true);
context.set('message', context.get('i18n').t('success.role.delete'));
}).catch(function(error){
Ember.debug('delete failed:'+JSON.stringify(error));
Ember.$('#confirmDelete').modal('hide');
Ember.$('#remarks').val('');
context.send('showErrors', error);
});
});
It doesn't work. So does setting the remarks value in the model like:
...
this.store.findRecord('item', id).then(function (selectedItem) {
selectedItem.set('remarks', remarks);
selectedItem.destroyRecord().then(function(response){
...
I am trying to override the deleteRecord but I don't know where to start or how to do it.
Anyone have ideas? Thanks!
You can easily achieve this kind of behaviour by extending your application adapter with the following mixin:
/* app/mixins/delete-with-playload.js */
import Ember from 'ember';
export default Ember.Mixin.create({
deleteRecord(store, type, snapshot) {
var id = snapshot.id;
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot);
return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE", {
data
});
}
});
Then just add it to your application adapter
/* app/adapters/application.js */
import RestAdapter from 'ember-data/adapters/rest';
import DeleteWithPayloadMixin from '../mixins/delete-with-payload';
export default RestAdapter.extend(DeleteWithPayloadMixin);
This will result a payload identical to the payload of PUT method, meaning a payload of the form:
{
"<model-name>": {
// model's serialized attributes
}
}
Now all you have to do is to set the desired attributes on the record before deleting, and destroy the record.
model.setProperties({
deleteReason: 'whatever'
});
model.destroyRecord();
/*
results a DELETE request when requestBody is "{
"<model-name>": {
...
"deleteReason": "whatever"
...
}
}"
*/