access another model within ng-repeat - json

This seems to me like it should be painfully obvious but I've not found an example anywhere.
I have two models, sessions and users:
$scope.sessions =
[{
"sessionId":"1",
"userId":"12345",
"date": "17/07/2014",
"test_name":"2014beta",
"status": "new",
"assigned_to":""
}]
$scope.users =
[{
"userId":"12345",
"name":"Frank Tester",
"dob": "17/07/1967",
"eyes":"blue"
}]
A session belongs to a user, so in the database, the user ID is saved within the session model (over-simplified models above).
In a listing of sessions, I'd like to include the user name and other user detail, both of which are accessed via the user model.
I have both users and sessions available within the scope. I use an ng-repeat to list all sessions (and show things like session.name, session.time etc), how do I access the user name from the other model by it's ID? ie. I'd would think I should be able to access session.user.name
I'll need to do this in a couple of different places and will need to access different bits of cross-referenced data - Is there a simple way to do this within the template or do I need to build a service for this? A directive? A filter?

You can put another ng-repeat inside session ng-repeat and filter it by session.userId
please see that demo: http://plnkr.co/edit/BOITOEEYDM9tFH3zbMIW
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ul>
<li ng-repeat="session in sessions">
{{session.date}}
<ul>
<li ng-repeat="user in users | filter: session.userId ">
{{user.name}}
</li>
</ul>
</li>
</ul>
</body>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.sessions =
[{
"sessionId":"1",
"userId":"12345",
"date": "17/07/2014",
"test_name":"2014beta",
"status": "new",
"assigned_to":""
}]
$scope.users =
[{
"userId":"12345",
"name":"Frank Tester",
"dob": "17/07/1967",
"eyes":"blue"
}]
});

Related

Django: Send current logged in user as JSON

I would like to create a GET endpoint that returns the JSONResponse of the current logged-in user. Ideally, it would look like:
{
"username": "joe",
"email": "joe#plainviewhcp.com",
"first_name": "",
"last_name": "",
"last_login": "2021-09-17T17:11:00.039Z",
"is_superuser": true,
"is_active": true
}
(Note that I'm using Django 3.2, not Django REST API)
This requires serializing the current user object, but serializing a single object is... opaque in the documentation, and many similar questions have responses from 6 or more years/two major versions ago.
I've solved this problem by re-querying the user from the request.user object and singling out the first field. This has the added benefit of controlling the fields. Note that I've already tested to make sure the user is logged in at this point.
def api_current_user(request: HttpRequest):
user = (
User.objects.filter(pk=request.user.pk)
.values(
"username",
"email",
"first_name",
"last_name",
"last_login",
"is_superuser",
"is_active",
)
.first()
)
return JsonResponse(user)

Error when including a contact to group using People API

I need to add a single contact to all the below groups. I tried to add the contact to groups one by one, however when I tested with the first group the API gave an error
GoogleJsonResponseException: API call to people.contactGroups.members.modify failed with error: Cannot add contacts to deprecated system contact group resource name "contactGroups/chatBuddies".
I want to add the created contact to all these groups
contactGroups/chatBuddies
contactGroups/all
contactGroups/friends
contactGroups/coworkers
contactGroups/family
contactGroups/blocked
I dont see anywhere that these groups are depreciated
I have tried with
var b = {
"phoneNumbers": [{
"type": "mobile",
"value": "09876543210"
}],
"names": [{
"unstructuredName": "Test account"
}],
"urls": [],
"addresses": [{
"type": "work",
"formattedValue": "0"
}],
"organizations": [{
"name": "Organisation"
}],
"emailAddresses": [{
"type": "home",
"value": "abcd#gmail.com"
}]
}
function doGet(e) {
var resource = People.People.createContact(b);
var id = resource.metadata.sources[0].id;
var contactResourceName = resource["resourceName"];
var group = People.ContactGroups.get("contactGroups/friends");
var groupResourceName = group["resourceName"];
var membersResource = {
"resourceNamesToAdd": [
contactResourceName
]
}
People.ContactGroups.Members.modify(membersResource, groupResourceName);
return ContentService.createTextOutput(JSON.stringify(group));
}
Where was the deprecation notice?
It was on display in the bottom of a locked filing cabinet stuck in a disused lavatory with a sign on the door saying "Beware of the Leopard."
In all seriousness, advanced services are thin layers wrapping the corresponding REST APIs, in this case, People API, therefore each method of the service has a corresponding method exposed by the API, specifically contactGroups.members.modify.
The description of the method reads as follows, clearly outlining that system contact groups are, in fact, deprecated:
The only system contact groups that can have members added are contactGroups/myContacts and contactGroups/starred. Other system contact groups are deprecated and can only have contacts removed.
Can I update system groups via the API directly?
It does not seem to be possible, as adding system groups to contact when updating memberships field via the people.updateContact method is explicitly forbidden (you have to examine the ContactGroupMembership resource docs to find the info):
Any contact group membership can be removed, but only user group or "myContacts" or "starred" system group memberships can be added.

Sailsjs MVC map params from external API to multiple models

I need to create a database of shopify orders so I can run advanced queries and sales reports that you can't do in the shopify admin area. I'm building in Sails .12 and mysql. Shopify lets you register a webhook so that every time an order is placed, it creates a POST to the specified URL with the order data in the body as JSON. The products ordered are an array of JSON objects as one of the values in the POST:
{
"id": 123456,
"email": "jon#doe.ca",
"created_at": "2017-01-10T14:26:25-05:00",
...//many more entires
"line_items": [
{
"id": 24361829895,
"variant_id": 12345,
"title": "T-Shirt",
"quantity": 1,
"price": "140.00",
},
{
"id": 44361829895,
"variant_id": 42345,
"title": "Hat",
"quantity": 1,
"price": "40.00",
},
]
}
I need to save the order into an Orders table, and the products ordered into a line_items table that is a one to many relation; one order can have many line_items (products ordered). There are over 100 key-value pairs sent by the webhook, and I'm saving all of it. I've created my two models where I define the data type, so now i have very long Order.js and Line_item.js files, and I'm using the
line_items: {
collection: 'line_item',
via: 'order_id'
},
in my Order.js, and
order_id: {
model: 'order'
},
in my Line_item.js models to relate them. Is this the correct way to denfine my two tables? Also, where would I put the code that maps the JSON to the model parameters? If I put that code in the controllers, would I have to type another 100+ lines of code to map each json value to its correct parameter. The how would I save to the two different models/tables? Eg:
var newOrder = {};
newOrder.id =req.param('id');
newOrder.email = req.param('email');
newOrder.name = req.param('name');
...//over 100 lines more, then Order.create(newOrder, ...)
var newLine_items = req.params('line_items'); //an array
_.forEach(newLine_items, function(line_item){
var newLine_item = {};
newLine_item.id = line_item.id;
newLine_item.order_id = newOrder.id;
newLine_item.title = line_item.title;
//etc for over 20 more lines, then Line_item.create(newLine_item, ...)
});
I need to save the order into an Orders table, and the products ordered into a line_items table that is a one to many relation; one order can have many line_items (products ordered).
That sounds completely reasonable, well, besides the use of the Oxford comma :)
There are over 100 key-value pairs sent by the webhook
I'm not sure that I understand exactly what this is or what it is used for within this process.
That being said, it might help to have a single attribute in your model for this which has a JSON value, then retrieve and work with it as JSON instead of trying to manually account for each attribute if that is what you're doing over there?
It really depends on your use case and how you'll use the data though but I figure if the format changes you might have a problem, not so if it's just being stored and parsed as a JSON object?
Also, where would I put the code that maps the JSON to the model parameters
In v0.12.x take a look at Services.
In v1, Services will still work but moving this logic into Helpers might be a good option but then, it seems that a custom model method would be a better one.
Here is a shorter version of your code:
var newOrder = req.allParams();
newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
newLine_items.push(line_item);
});
Here is what your logic might look like:
var newOrder = req.allParams();
// Store the order
Order
.create(newOrders)
.exec(function (err, result) {
if (err) // handle the error
var newLine_items = {};
_.forEach(newOrder.line_items, function(line_item) {
// Add the order id for association
line_item.order_id = result.id;
// Add the new line item with the orders id
newLine_items.push(line_item);
});
// Store the orders line items
LineItems
.create(newLine_items)
.exec(function (err, result) {
if (err) // handle the error
// Handle success
});
});
And the lifecycle callback in the Order model:
beforeCreate: function (values, cb) {
delete(values.line_items);
cb();
}
But you really should look into bluebird promises as the model methods in version one of sails have opt in support for them and it helps to negate the pyramid of doom that is starting in my example and is also something that you want to avoid :P

Pulling Sequelize Info from multiple tables

I'm pretty new to new sequelize but I'm trying to figure out how I can pull sequelize information from multiple tables (Place and Review tables) and render them on the same page. The Review table has a User Id and a Place Id. I've tried raw queries and different variations of the code below to no avail. What sort of syntax should I use in this case?
User.hasMany(Review);
Review.belongsTo(User);
User.hasMany(Place);
Place.belongsTo(User);
Place.hasMany(Review);
Review.belongsTo(Place);
app.get('/place/:category/:id', function(req, res){
var id = req.params.id;
Place.findAll({
where : {id : id},
include: [{
model: [Review]
}]
}).then(function(reviews){
res.render('singular', {reviews});
});
});
From your API route definition, I assume you're trying to display reviews for a place based on place ID.
So, to achieve this, you could model your table associations as
Places.hasMany(Reviews);
Users.hasMany(Reviews);
Review.belongsTo(Places);
Review.belongsTo(Users);
Now, based on this association, you could perform the query like this:
Places.findById(req.params.id, {
include: [{
model: Reviews,
required: false,
include: [{
model: Users,
required: false
}]
}]
}).then(function(place) {
// The rest of your logic here...
});

Ember Data findAll() not populating models?

new to ember js, and working on an app using ember-data. If I test with same data using FixtureAdapter, everything populates in the html template ok. When I switch to RESTAdapter, the data looks like it's coming back ok, but the models are not being populated in the template? Any ideas? Here's the code:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
})
});
App.Brand = DS.Model.extend({
name: DS.attr('string'),
numStyles: DS.attr('string'),
vendorId: DS.attr('string')
});
App.BrandsRoute = Ember.Route.extend({
setupController:function(controller){
},
model:function(){
return App.Brand.find();
}
});
And here is the data coming back, but not being inserted into the template!
returnValue: [{numStyles:1, name:Easton, vendorId:6043}, {numStyles:1, name:Louisville Slugger, vendorId:6075},…]
0: {numStyles:1, name:Easton, vendorId:6043}
1: {numStyles:1, name:Louisville Slugger, vendorId:6075}
2: {numStyles:1, name:Rawlings, vendorId:6109}
3: {numStyles:7, name:BWP Bats , vendorId:6496}
4: {numStyles:1, name:DeMarini, vendorId:W002}
status: "ok"
And here is the template:
{{#each brand in model.returnValue }}
<div class="brand-node"{{action select brand}}>
<h2>{{brand.name}}</h2>
<p>{{brand.numStyles}} Styles</p>
</div>
{{/each}}
Any help would be greatly appreciated! I'm not getting any errors, and the data seems to be coming back ok, just not getting into the template. Not sure if the returned dataset needs "id" param?
I am also using the Store congfig to alter the find() from plural to singular:
DS.RESTAdapter.configure("plurals", {
brand: "brand"
});
The way the API was written, its expecting "brand" and not "brands"... maybe its something to do with this??
Thanks in advance.
You have stated:
Not sure if the returned dataset needs "id" param?
Yes you are guessing right, you data coming back from the backend need's an id field set. And if the id field name is different then id you should also define this in ember like so:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
}),
serializer: DS.RESTSerializer.extend({
primaryKey: function (type) {
return '_my_super_custom_ID'; // Only needed if your id field name is different than 'id'
}
})
});
I suppose your Fixtures have an id defined thus it works, right?
Note: you don't need to define the id field at all explicitly, ember add's automatically the id field to a model, so your model is correct.
Here a website that is still a WIP but can be good reference for this conventions
and as stated there:
The document MUST contain an id key.
And this is how your JSON should look like for a collection of records:
{
"brands": [{
"id": "1",
"numStyles": "1",
"name": "Easton",
"vendorId" :"6043"
}, {
"id": "2",
"numStyles": "4",
"name": "Siemens",
"vendorId": "6123"
}/** and so on**/]
}
Note: as you have shown you JSON root is called returnValue this should be called brand or brands if you are not adapting the plurals. See here for reference for the JSON root I'm talking about.
Hope it helps