OData is returning Upper-case properties when filtering - reactjs

I'm working on a project which has a front-end made in Reactjs + axios, and a backend with .NET Core 3.1 Web API which is configured to allow OData filtering.
Everything is working fine, but I only have one small problem.
If I consume, e.g: GET /api/questions without any OData filtering, I receive:
[
{
"id": "005b46c6-1811-42f2-b917-00178e916d2e",
"value": "List the requirements for Schedule III, IV, & V Prescriptions.",
"required": true,
"sequence": 0,
"questionType": {
"id": "4227e559-3b14-4e07-b90e-73151f723698",
"name": "Rating",
"value": "rating-question",
"description": "a question in where the user rates the answer"
},
"ratingSetting": {
"id": "5e6a883a-084d-4400-bdf2-78b97e2eba18",
"name": "Poor to Excellent",
"minValueText": "Poor",
"maxValueText": "Excellent",
"optionCount": 5
},
"answers": []
},
...
]
But if I perform some filtering, for example: GET /api/admin/questions?$select=id, value&$expand=questionType($select=name)&$expand=ratingSetting($select=name) the result contains an array where every property has changed to Upper-case:
[
{
"QuestionType": {
"Name": "Rating"
},
"RatingSetting": {
"Name": "Poor to Excellent"
},
"Id": "005b46c6-1811-42f2-b917-00178e916d2e",
"Value": "List the requirements for Schedule III, IV, & V Prescriptions."
},
...
]
As you can see, every property is upper case. This is causing me trouble when I try to bind the result object, because it's not the same question.id against question.Id, so I'm having an undefined exception in the front-end.
Is there any configuration that I have to perform in my backend to solve this?

Make sure you are using a contract resolver by specifying the appropriate NewtonSoftJsonOptions:
services.AddControllers(options =>
options.EnableEndpointRouting = false)
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

Install these libraries:
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OData.NewtonsoftJson" Version="8.0.4" />
Then add this in startup.cs or program.cs:
services.AddControllers().AddOData(options =>
{
options.EnableQueryFeatures(maxTopValue: 500);
})
.AddODataNewtonsoftJson()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});

Related

How to add child entities without id to parent in state normalized with normalizr

I've recently started using normalizr with zustand in a new React app. It's been a very good experience so far, having solved most of the painful problems I've had in the past.
I've just bumped into an issue I can't think of a clean way of solving for the past few days.
Imagine I have a normalizr-normalized state looking like:
{
"entities": {
"triggers": {
"1": {
"id": 1,
"condition": "WHEN_CURRENCY_EXCHANGED",
"enabled": true,
"value": "TRY"
},
"2": {
"id": 2,
"condition": "WHEN_CURRENCY_EXCHANGED",
"enabled": true,
"value": "GBP"
},
"3": {
"id": 3,
"condition": "WHEN_TRANSACTION_CREATED",
"enabled": true,
"value": true
}
},
"campaigns": {
"19": {
"id": 19,
"name": "Some campaign name",
"triggers": [
1,
2,
3
]
}
}
},
"result": 19
}
And we have a page that allows a user to add one or more triggers to the campaign and then save them. The problem is that at the time of adding these triggers, they do not have an id until the user clicks the Save button (ids are generated by the database). When the Save button is clicked, the state is being denormalized (via normalizr's denormalize function) and sent as payload to the backend looking like the following:
{
"id": 19,
"name": "Some campaign name",
"triggers": [
{
"id": 1,
"condition": "WHEN_CURRENCY_EXCHANGED",
"enabled": true,
"value": "TRY"
},
{
"id": 2,
"condition": "WHEN_CURRENCY_EXCHANGED",
"enabled": true,
"value": "GBP"
},
{
"id": 3,
"condition": "WHEN_TRANSACTION_CREATED",
"enabled": true,
"value": true
}
]
}
The problem is that if the user adds an entity to the triggers, it does not have an id as ids are generated by the database and I cannot find a proper way to add it to the state (due to the id-based nature of normalized states).
The only workaround I can think of is generating some temporary IDs (e.g. uuid) when a trigger is added on the front-end but is not yet saved and then going over each entity upon denormalization, doing something like if (isUuid(trigger.id)) delete trigger.id, which seems too tedious and workaroundish.
Appreciate your help.
P.S. There is something similar explained here. The problem is that in our case the generateId('comment') logic is happening on the backend.
A simple solution is to split.
The create trigger API call and the add trigger to campaign API call.
Do the first, then save the trigger into the normalized store with the id generated by the backend.
Then add it to the campaign.

Antd Table render properties inside and array of objects

I have an Antd Table, with data coming from axios API
"data": [
{
"id": 1,
"name": "Package 1",
"services": [
{
"id": 1,
"name": "Evaluation Core",
}
]
},
{
"id": 2,
"name": "Package 2",
"services": [
{
"id": 1,
"name": "Evaluation BizCore",
},
{
"id": 2,
"name": "Certification Fizz"
}
]
}
],
"meta": {
"current_page": 1,
"last_page": 1,
"per_page": 20,
"total": 2,
"total_results": 2
}
}
In this Table I'm rendering one column with the name of the Package, and the second column I need to render any name property inside the Services array. That columns has this dataindex:
dataIndex: ['services', 'name'],
If there is more then one property name, should be render separated with ",". I tried differents approaches,but nothing seems to work.
Thanks!!
If I understand correctly you want to render a Services column where each package may have a different amount of services. Each service has a name and you want to display the name property of all services for package aggregated. e.g. Package has Service 1 and Service 2 and it should be displayed Service 1,Service 2.
The simple answer is to use render. The column for Services can look like.
{
title: "Services",
dataIndex: "services",
render: (services) => services.map(service => service.name).join(),
key: "services"
}
https://codesandbox.io/s/basic-antd-4-16-3-forked-q6ffo?file=/index.js
Please comment if this was not the intended result.

I have a datastudio error - basic json config

I've returned to try and make some datastudio custom javascript.
So I started off with a template type settings and basic js. Manifest is listing correctly - datastudio sees the custom item.
I took a long time for it to be authorised.
However, on adding the custome js, the console is reporting a load of erros.
first : data.0.type is not a valid config
second : data.0.elements.data.0.type is not a valid config.
Json:
{
"data": [
{
"id": "idtestviz",
"label": "Dimension Element Heading",
"type":"DIMENSION"
}
]
,
"style": [
{
"id": "idtestvizstyles",
"label": "Test Styles",
"elements":[
{
"id":"idtestvizfontcolor",
"label":"Font Colour",
"defaultValue":"#FFFF00"
}
]
}
]
}
It did have options in before, same error.
And appears to be the same as in https://developers.google.com/datastudio/visualization/define-config
Also it also is erroring on 'is already used in the config'
and that data.0.elements.style.0.elements.0.type required field that cannot be found
Seems like there are more checks that need to be done.
Is there a validator for json etc. before running, or has something updated on google side that their documentation hasn't been updated yet?
Or the more likely aspect, I'm missing some critical stuff...
Regards
Vince
Re checked my json config with a previous one that works, noted some errors in the objects. Corrected those and the json errors in the console have gone away.
JS errors remain - working on those... closing this question.
{
"data": [
{
"id":"test_viz_data",
"label":"Test Viz Data",
"elements":[
{
"id": "text_viz_dimensions",
"label": "Dimension Element Heading",
"type": "DIMENSION",
"options": {
"min": 1,
"max": 1
}
}
,
{
"id": "test_metrics",
"label": "Metric fields",
"type": "METRIC",
"options": {
"min": 1,
"max": 1
}
}
]
}
]
,
"style": [
{
"id": "idstyles",
"label": "Test Styles",
"elements":[
{
"id":"idfontcolor",
"label":"Font Colour",
"type":"FONT_COLOR",
"defaultValue":"#FFFF00"
}
]
}
]
,
"interactions": [
]
}

Loopback, AngularJS and validation

I followed this tutorial to create a project with Loopback and AngularJs. https://github.com/strongloop/loopback-example-angular
Now, I have an application with:
HTML files (with Bootstrap)
AngularJS controllers
AngularJS service (generated with syntax lb-ng server/server.js client/js/services/lb-services.js)
Model (located in ./common folder)
MongoDB backend
The model "Device" is defined in ./common/models/device.js
module.exports = function(Device) {
};
And in ./common/models/device.json
{
"name": "Device",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"name": {
"type": "string",
"required": true
},
"description": {
"type": "string",
"required": true
},
"category": {
"type": "string",
"required": true
},
"initialDate": {
"type": "date"
},
"initialPrice": {
"type": "number",
"required": true
},
"memory": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
In the "AddDeviceController", I have an initialization part with:
$scope.device = new DeviceToBuy({
name: '',
description: '',
category: '',
initialPrice: 0,
memory: 8
initialDate: Date.now()
});
And I am able to save the $scope.device when executing the following method:
$scope.save = function() {
Device.create($scope.device)
.$promise
.then(function() {
console.log("saved");
$scope.back(); // goto previous page
}, function (error) {
console.log(JSON.stringify(error));
});
}
When everything is valid, the model is saved in the backend. If something is not valid in the $scope.device, I receive an error from my backend. So everything is working fine.
Now, I would like to use the model to perform client-side validation before sending my model to the backend and put some "error-class" on the bootstrap controls.
I tried something in the $scope.save function before sending to the backend:
if ($scope.device.isValid()) {
console.log("IsValid");
} else {
console.log("Not Valid");
}
But I get an exception "undefined is not a function" --> isValid() doesn't exist.
And I cannot find any example on how to execute this client-side validation.
LoopBack models are unopinionated and therefore do not provide client side validation out-of-box. You should use Angular validation mechanisms before calling $save.

Why is angularjs code slow?

Is it normal, that angularjs ng-repeat takes 1.5 Seconds to render data from an rest api? The result consists of only 10 rows with in total 1KB of data. How can I improve the speed or where to look for the problem?
ADDED INFOS:
The rest request itself only takes 128ms if I run it directly on the browser.
This is a set of sample data you get from the rest api:
{
"result": [
{
"id": 1224,
"name": "Schokolade-Vanille",
"kcal": 35500,
"displayName": "Schokolade-Vanille"
},
{
"id": 23423,
"name": "Naturreis Uncle Bens",
"kcal": 34400,
"displayName": "Naturreis Uncle Bens"
},
{
"id": 123231,
"name": "Paprikahendl",
"kcal": 4100,
"displayName": "Paprikahendl"
},
{
"id": 434,
"name": "Vanille Kugeln",
"kcal": 53700,
"displayName": "Vanille Kugeln"
},
{
"id": 323423,
"name": "Weihnachtstraum, Lindor-Kugeln",
"kcal": 60800,
"displayName": "Lindor-Kugeln"
},
{
"id": 5435,
"name": "Schokolade",
"kcal": 4300,
"displayName": "Schokolade"
},
{
"id": 23213,
"name": "Hühner-Nuggets",
"kcal": 23400,
"displayName": "Hühner-Nuggets"
},
{
"id": 5534,
"name": "Knödel, Kartoffel",
"kcal": 1230,
"displayName": "Knödel, Kartoffel"
},
{
"id": 23233,
"name": "Curvers",
"kcal": 15400,
"displayName": "Curvers"
},
{
"id": 53434,
"name": "Frites Original",
"kcal": 14100,
"displayName": "Frites Original"
}
],
"count": 12854
}
NEW ADDED INFOS
I have had a closer look now and found out, that not te repeat funktion is the problem.
I used the following code:
$scope.updateResultset = function() {
$scope.result = Food.query({
offset: $scope.offset,
order_by: $scope.orderby,
name: $scope.textfilter,
},function(){
console.log( "response " + (new Date().getTime() - start) );
});
$scope.offset = undefined;
console.log( "updateResultset " + (new Date().getTime() - start) );start = new Date().getTime();
And get the following response:
response 435
But the request itself only takes 131ms. In my opinion, >300ms is a lot of time to waste in a single method?
Compared to my former version, where I showed a plan html list, which was replaced by jquery ajax response html, its much slower?
As others indicated in the comments, the cause in the code is likely something else aside from ng-repeat. However, here are other options to consider, if speed still seems like an issue for ng-repeat:
quick-ng-repeat directive on github: https://github.com/allaud/quick-ng-repeat
ng-scroll, as part of angular-ui: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md
Ok, I found out the problem. Not the repeatition of the 10 list items was the problem! As you can see in my question, I return not only the 10 results, but also the total amount of results. In my case it was '"count": 12854'.
On the same page, I have a pagination which was the part which slows down the whole page, since it had to render 1286 pager buttons (~12854/10). Now I only show 10 pager-buttons.

Resources