Denormalize with normalizr - redux

I am trying to denormalize some data from the redux state, but I can't get it to work. I have tried putting together the denormalize function in all ways I can think. It is a guessing game and nothing have worked so far.
First I normalize the product data and put it into the state.
The entities are being put in state.data.products, including the products.
state.data: {
products: {
products: {
9: {
id: 9
attributes: [ 10, 45, 23 ],
things: [23, 55, 77]
},
11 //etc
}
attributes: {
10: {
id: 10
},
45: //etc
},
things: { //etc
}
}
So there is one property "products" that includes all entities, and there is another "products" for the "products" entity.
The normalizing works without problem:
normalize(data, [productSchema]);
The "productSchema" is defined like this:
productSchema = new schema.Entity('products', {
attributes: [attributeSchema],
things: [thingsSchema],
//+ other stuff
});
Now I want to denormalize a product, for example 9.
I use "connect" in a view component to call this function to retrieve the data from state and denormalize it:
export const denormalizeProduct = (state, productId) => {
const entities = state.data.products;
return denormalize(
productId,
[productSchema],
entities
);
}
If I call denormalizeProductById(state, 9) , I only get 9 back.
(similar to this question , but I couldn't find a solution from it, and it mixes together two examples)
If I put the "productSchema" without the array:
return denormalize(
productId,
productSchema,
entities
);
I get the error: TypeError: entities[schemaKey] is undefined.
Everything I have tried results in either "9" or the above error.
Edit:
found the error - added it below

I found the error - one of my schemas was wrong: I had created new schema.Entity('shippingZones') but in the reducer I added it to the state with a different name:
shipping_zones: action.payload.shippingZones
So it was looking for "shippingZones" while there was only "shipping_zones" I guess. So I changed it to new schema.Entity('shipping_zones') and shipping_zones: action.payload.shipping_zones
It's a pity that the message TypeError: entities[schemaKey] is undefined couldn't have specified "shippingZones" , then I could have saved a few days time.
So this code worked in the end:
const entities = state.data.products;
return denormalize(
productId,
productSchema,
entities
);

Related

Can we use NgRx Data with pagination style REST API response?

I am currently using NgRx Data to perform CRUD operation on couple of entities on my project. Now, I've to develop pagination. Hence, REST API response is going to be like:
{
"page": 1,
"per_page": 10,
"total": 100,
"total_page": 10,
"data": [
{ ... },
{ ... },
{ ... }
]
}
AFAIK, NgRx Data works well with entities, I've no clue how to deal with this. Could you please redirect me to some light? Thank you.
Even I was facing a similar issue. So for people who are new to NgRx data, I have created an EntityDataListInterface which was similar to:
{
page: number,
per_page: number,
total: number,
total_page: number,
data: EntityDataItem[]
}
For each section I am working on I create a different service. Lets call it ComponentService. Inside this ComponentService I access the EntityService(which implements EntityCollectionServiceBase<EntityDataItem>) and entity's DataService (which implements DefaultDataService<EntityDataListInterface>).
Once the API returns EntityDataListInterface data, you can use addManyToCache to add them into the entity cache.
Inside the module, register the EntityDataItem by passing the filterFn. Now you can call setFilter to filter the entities based on indexes(or any pagination logic like shown below) and the result would be accessible via filteredEntities$.
//eds: EntityDefinitionService in the constructor
const entityMetadata: EntityMetadataMap = {
EntityDataItem: {
filterFn:(entities: EntityDataItem[], pattern:{startIndex: number, endIndex: number}) => {
return entities.filter((entity, index) => {
return ((index >= pattern.startIndex) && (index <= pattern.endIndex));
})
}
}
};
eds.registerMetadataMap(entityMetadata);
Subscribe to filteredEntities$ in your component and it will solve the pagination issue.

NGRX: Composing state when we have to represent data from two lists

Practical example: Consider an expand/collapse list. Each item expands another list.
export interface MainDomainList {
id: number
name: string;
}
export interface SubDomainList {
id: number
name: string;
}
export interface AppState {
mainDomainList: MainDomainList[];
subDomainList: SubDomainList[];
}
On the UI the list should be represented like this:
MainDomainList[1]
SubDomainList[] (entire list)
MainDomainList[2]
Another SubDomainList[] (entire list)
etc..
When the user clicks on the MainDomain[n] there is a call to the backend which returns a list of SubDomain[]. There are no connections between the two of them.
It seems that the most complicated part is that the SubDomains are being loaded one by one on click not all at once, and multiple MainDomains can be open at the same time like in the example above. Also, it should be possible to easily perform CRUD operations on the subDomainList entities.
I tried using a selector which selects an item from the state by id but every time the state is overridden.
My initial idea was to create a separate state in which after the SubDomainList[] is loaded successfully, then I could add the loaded SubDomainList[] by dispatching an 'ADD' action thus adding the entities and the id of the clicked MainDomainList in the newList state as the user clicks on through the list obtaining something like this:
exportt interface AppState {
mainDomainList: MainDomainList[];
subDomainList: SubDomainList[];
newList: NewList[];
}
{
mainDomainList : {
entities: {
md1: {
id: 'md1',
name: '1'
},
md2: {
id: 'md2',
name: '2'
}
}
},
subDomainList : {
entities : {
sd1 : {
id : 'sd1',
name: 'name1'
},
sd2 : {
id : 'sd2',
name: 'name2'
}
},
newList : {
entities : {
md1 : {
id : 'md1',
subDomainList: [{}, {}]
},
md2 : {
id : 'md2',
subDomainList: [{}, {}]
}
}
}
}
Then somehow i would get all the newList entities and match them in the UI with the id of the MainDomainList[n].id
Is my approach correct or is there any other better or less complicated solution for this issue?
I'm fairly new to the subject but I had a lot of headaches trying to figure out how to implement this with ngrx/Entity and failed so far, although it should be a pretty common case. Any help would be much appreciated.
You can write selectors with argument by passing of main domain list
ref: ngrx parameter to select function
and https://blog.angularindepth.com/ngrx-parameterized-selector-e3f610529f8

Meteor Framework Subscribe/Publish according to document variables

I have a game built on Meteor framework. One game document is something like this:
{
...
participants : [
{
"name":"a",
"character":"fighter",
"weapon" : "sword"
},
{
"name":"b",
"character":"wizard",
"weapon" : "book"
},
...
],
...
}
I want Fighter character not to see the character of the "b" user. (and b character not to see the a's) There are about 10 fields like character and weapon and their value can change during the game so as the restrictions.
Right now I am using Session variables not to display that information. However, it is not a very safe idea. How can I subscribe/publish documents according to the values based on characters?
There are 2 possible solutions that come to mind:
1. Publishing all combinations for different field values and subscribing according to the current state of the user. However, I am using Iron Router's waitOn feature to load subscriptions before rendering the page. So I am not very confident that I can change subscriptions during the game. Also because it is a time-sensitive game, I guess changing subscriptions would take time during the game and corrupt the game pleasure.
My problem right now is the user typing
Collection.find({})
to the console and see fields of other users. If I change my collection name into something difficult to find, can somebody discover the collection name? I could not find a command to find collections on the client side.
The way this is usually solved in Meteor is by using two publications. If your game state is represented by a single document you may have problem implementing this easily, so for the sake of an example I will temporarily assume that you have a Participants collection in which you're storing the corresponding data.
So anyway, you should have one subscription with data available to all the players, e.g.
Meteor.publish('players', function (gameId) {
return Participants.find({ gameId: gameId }, { fields: {
// exclude the "character" field from the result
character: 0
}});
});
and another subscription for private player data:
Meteor.publish('myPrivateData', function (gameId) {
// NOTE: not excluding anything, because we are only
// publishing a single document here, whose owner
// is the current user ...
return Participants.find({
userId: this.userId,
gameId: gameId,
});
});
Now, on the client side, the only thing you need to do is subscribe to both datasets, so:
Meteor.subscribe('players', myGameId);
Meteor.subscribe('myPrivateData', myGameId);
Meteor will be clever enough to merge the incoming data into a single Participants collection, in which other players' documents will not contain the character field.
EDIT
If your fields visibility is going to change dynamically I suggest the following approach:
put all the restricted properties in a separated collection that tracks exactly who can view which field
on client side use observe to integrate that collection into your local player representation for easier access to the data
Data model
For example, the collection may look like this:
PlayerProperties = new Mongo.Collection('playerProperties');
/* schema:
userId : String
gameId : String
key : String
value : *
whoCanSee : [String]
*/
Publishing data
First you will need to expose own properties to each player
Meteor.publish('myProperties', function (gameId) {
return PlayerProperties.find({
userId: this.userId,
gameId: gameId
});
});
then the other players properties:
Meteor.publish('otherPlayersProperties', function (gameId) {
if (!this.userId) return [];
return PlayerProperties.find({
gameId: gameId,
whoCanSee: this.userId,
});
});
Now the only thing you need to do during the game is to make sure you add corresponding userId to the whoCanSee array as soon as the user gets ability to see that property.
Improvements
In order to keep your data in order I suggest having a client-side-only collection, e.g. IntegratedPlayerData, which you can use to arrange the player properties into some manageable structure:
var IntegratedPlayerData = new Mongo.Collection(null);
var cache = {};
PlayerProperties.find().observe({
added: function (doc) {
IntegratedPlayerData.upsert({ _id : doc.userId }, {
$set: _.object([ doc.key ], [ doc.value ])
});
},
changed: function (doc) {
IntegratedPlayerData.update({ _id : doc.userId }, {
$set: _.object([ doc.key ], [ doc.value ])
});
},
removed: function (doc) {
IntegratedPlayerData.update({ _id : doc.userId }, {
$unset: _.object([ doc.key ], [ true ])
});
}
});
This data "integration" is only a draft and can be refined in many different ways. It could potentially be done on server-side with a custom publish method.

Sails js 2:n relation

I recently started working with SailsJS, and I found the process of defining attributes and associations very elegant. However, there is one thing I cannot find out:
I have a model Couple(person1, person2). I'd like to create an association in Person, that lists every couple they are a member of. Something along the lines of:
attributes{
//other attributes,
couples:{
collection: 'couple',
via: 'person1, person2'
}
}
My current method is:
attributes{
//other attributes,
couples1:{
collection: 'couple',
via: 'person1'
},
couples2:{
collection: 'couple',
via: 'person2'
},
getCouples: function() {
return this.couples1 + this.couples2;
}
}
But this doesn't seem very pretty, is there a way to do it more elegantly?
If i get your question correctly, you want a person and its couple, i'm assuming you have a monogamous relationship in your couples (meaning one person belongs to the other and vice-versa) you can make an association with the same model, like this.
var Person = {
attributes: {
name: {type:'string'},
couple: {model: 'Person', via: 'couple'}
}
};
module.exports = Person
Then you can create and associate them like this. (Assuming sails console)
Person.create({name: 'John Doe', couple: {name: 'Jane Doe'} }).exec(console.log)
Person.update(2, {couple:1}).exec(console.log)
And retrieving them is as easy as
Person.find({name:'John Doe'}).populate('couple').exec(console.log)
You can try to associate them with .add and .save but i'm not sure if it works when the association points to the same model, so check that out.
Another option is to have it like this:
var Person = {
attributes: {
name: {type:'string'},
couple: {model: 'Couple', via: 'persons'}
}
};
module.exports = Person;
Couple model holds a collection of persons, so you can add persons to the
couple model, and associate them later with the person.couple attribute.
var Couple = {
attributes: {
persons: {collection: 'Person', via: 'couple'}
}
};
module.exports = Couple;
Or you could use what you have, which is not ideal in this case, but it works.

Meteor 1.0: Upsert with Mongo Selector

I am trying to do an upsert on the server side with a custom field as the unique identifier instead of a mongo id (data is being pulled from a 3rd party api).
A simplified version of what I am trying to achieve:
var myItem = {
myUniqueID : 'abc123',
name: 'foo'
};
MyCollection.upsert(
{
"myUniqueID ": myItem.myUniqueID
},
{
"$set": myItem
}
);
I receive the following error:
Error: Meteor does not currently support objects other than ObjectID as ids
It appears that this was caused by me adding:
MyCollection._ensureIndex({myUniqueID : 1}, {unique: 1});
right after declaring the Mongo Collection... even when I commented this line out the damage had been done.. I had to rename the collection (essentially create a new collection) to get past it.

Resources