Looping and updating data in React - json

So quite new to React here (mostly backend and devops engineer). I need to fix a bug as the person usually responsible is not available currently.
One of the REST endpoint is formatting dates incorrectly while sending the data to the backend. The data expected from the endpoint for a PUT is
"items": [
{
"uuid": "abc7aba1-47ad-46d1-a3a5-d26ff55e4cf8",
"item_id": "21626227",
"item_description": "Test",
"item_schedule": {
"uuid": "37f8ca4c-6469-4bfb-822e-acfbc02e502e",
"start_date": "2018-12-04",
"end_date": "2018-12-06",
"interval": 3,
"unit": "days",
"occurrence": 1
"schedule_dates": [
{
"uuid": "d5b73ac5-be77-40c5-b11b-45034f70f81f",
"planned_date": "2018-12-04",
"custom": true
}
]
}
},
{
"uuid": "7abca4f4-1717-4136-aec6-3a37b4971c81",
"item_id": "21626229",
"item_description": "Test 2",
"maintenance_plan": "31001827",
"item_schedule": {
"uuid": "5de45d6e-81e8-4c86-9eb2-31c71089c876",
"start_date": null,
"end_date": null,
"interval": null,
"unit": "",
"occurrence": null,
"schedule_dates": [
{
"uuid": "da7ed2e4-053e-4f1d-80ca-2d6d258e8a08",
"planned_date": "2018-12-13",
"custom": true
}
]
}
}
]
Instead what we get for all the dates, i.e. start_date, end_date and planned_dates is (skipping all the right stuff here..)
"end_date": "2018-12-05T13:00:00.000Z",
"start_date": "2018-12-03T13:00:00.000Z"
"planned_date" : "2018-12-03T13:00:00.000Z"
When creating a new schedule for a new item, the old schedule data is incorrectly formatted.
I have tried to loop over all the items and the relevant schedule and dates and correctly format them , but doesn't seem to work.
Do I need to use map here instead of foreach?
const mapDispatchToProps = (dispatch, props) => ({
save: (value, notes) => dispatch(ItemDetailAction.saveLocal(
props.value.merge(
Map(Object.assign(
{
notes: notes.setIn([0, 'created'], undefined),
uuid: props.value.get('uuid'),
},
props.value.getIn(['item', 'type']) === 'P' && {
items: props.value
.get('items').forEach((item) => {
console.log(item.get('item_schedule'));
const start_date = item.get('item_schedule').get('start_date');
if (start_date !== '') {
const formatted_date = moment(start_date).format('YYYY-MM-DD');
//not updating the date-format below in the same array.
item.get('item_schedule').set('start_date',formatted_date);
item.setIn(['item_schedule', 'start_date'],formatted_date);
// this still prints the wrong date-format
console.log(item.get('item_schedule').get('start_date'));
}
}),
},
)),
),
true,
{
then: () => {
props.onCancel();
dispatch(actions.getItemListTable(FilterMaintenance.asParams(props.filters)));
},
}, )), });

Related

How to configure everything into one or multiple configure files

I haven't used this since 2 years ago. I'm trying to figure out how to put everything into one json or it has to be mulitple jsons.
Using v11.9.46. The documentation is not clear as it references things that are for one version or another.
I'm moving items from ADOorg1 to ADOorg2. In this order I was going to setup the json
Areas and Iterations
Team setup
Shared Queries
Work Items (using a query to find select area)
This is what I had so far as I tried to figure out how to put it into one:
{
"ChangeSetMappingFile": null,
// "Endpoints": {
// "TfsTeamSettingsEndpoints": [
// {
// "Name": "TeamSettingsSource",
// "AccessToken": "",
// "Query": {
// "Query": "SELECT [System.Id], [System.Tags] FROM WorkItems WHERE [System.TeamProject] = #TeamProject AND [System.WorkItemType] NOT IN ('Test Suite', 'Test Plan') ORDER BY [System.ChangedDate] desc"
// },
// "Organisation": "https://dev.azure.com/test1/",
// "Project": "test1",
// "ReflectedWorkItemIdField": "ReflectedWorkItemId",
// "AuthenticationMode": "AccessToken",
// "AllowCrossProjectLinking": false,
// "LanguageMaps": {
// "AreaPath": "Area",
// "IterationPath": "Iteration"
// }
// },
// {
// "Name": "TeamSettingsTarget",
// "AccessToken": "",
// "Query": {
// "Query": "SELECT [System.Id], [System.Tags] FROM WorkItems WHERE [System.TeamProject] = #TeamProject AND [System.WorkItemType] NOT IN ('Test Suite', 'Test Plan') ORDER BY [System.ChangedDate] desc"
// },
// "Organisation": "https://dev.azure.com/test2/",
// "Project": "test2",
// "ReflectedWorkItemIdField": "ReflectedWorkItemId",
// "AuthenticationMode": "AccessToken",
// "AllowCrossProjectLinking": false,
// "LanguageMaps": {
// "AreaPath": "Area",
// "IterationPath": "Iteration"
// }
// }
// ]
// },
"Source": {
"$type": "TfsTeamProjectConfig",
"Collection": "https://dev.azure.com/test1/",
"Project": "test1",
"ReflectedWorkItemIDFieldName": "ReflectedWorkItemId",
"AllowCrossProjectLinking": false,
"AuthenticationMode": "Prompt",
"PersonalAccessToken": "",
"LanguageMaps": {
"AreaPath": "Area",
"IterationPath": "Iteration"
}
},
"Target": {
"$type": "TfsTeamProjectConfig",
"Collection": "https://dev.azure.com/test2/",
"Project": "Test2",
"ReflectedWorkItemIDFieldName": "ReflectedWorkItemId",
"AllowCrossProjectLinking": false,
"AuthenticationMode": "Prompt",
"PersonalAccessToken": "",
"LanguageMaps": {
"AreaPath": "Area",
"IterationPath": "Iteration"
}
},
"Endpoints": {
"InMemoryWorkItemEndpoints": [
{
"Name": "Source",
"EndpointEnrichers": null
},
{
"Name": "Target",
"EndpointEnrichers": null
}
]
},
"GitRepoMapping": null,
"LogLevel": "Information",
"Processors": [
{
"$type": "TfsAreaAndIterationProcessorOptions",
"Enabled": true,
"PrefixProjectToNodes": false,
"NodeBasePaths": null,
"ProcessorEnrichers": null,
"SourceName": "Source",
"TargetName": "Target"
},
{
"$type": "TfsTeamSettingsProcessorOptions",
"Enabled": false,
"MigrateTeamSettings": true,
"UpdateTeamSettings": true,
"PrefixProjectToNodes": false,
"Teams": null,
"ProcessorEnrichers": null,
"SourceName": "Source",
"TargetName": "Target"
},
{
"$type": "WorkItemMigrationConfig",
"Enabled": false,
"ReplayRevisions": true,
"PrefixProjectToNodes": false,
"UpdateCreatedDate": true,
"UpdateCreatedBy": true,
"BuildFieldTable": false,
"AppendMigrationToolSignatureFooter": false,
"WIQLQueryBit": "AND [Microsoft.VSTS.Common.ClosedDate] = '' AND [System.WorkItemType] NOT IN ('Test Suite', 'Test Plan')",
"WIQLOrderBit": "[System.ChangedDate] desc",
"LinkMigration": true,
"AttachmentMigration": true,
"AttachmentWorkingPath": "E:\\temp\\WorkItemAttachmentWorkingFolder\\",
"FixHtmlAttachmentLinks": false,
"SkipToFinalRevisedWorkItemType": true,
"WorkItemCreateRetryLimit": 5,
"FilterWorkItemsThatAlreadyExistInTarget": true,
"PauseAfterEachWorkItem": false,
"AttachmentMaxSize": 480000000,
"CollapseRevisions": false,
"LinkMigrationSaveEachAsAdded": false,
"GenerateMigrationComment": true,
"NodeBasePaths": [
"Product\\Area\\Path1",
"Product\\Area\\Path2"
],
"WorkItemIDs": null
}
],
"Version": "0.0",
"workaroundForQuerySOAPBugEnabled": false,
"WorkItemTypeDefinition": {
"sourceWorkItemTypeName": "targetWorkItemTypeName"
}
// "Endpoints": {
// "InMemoryWorkItemEndpoints": [
// {
// "Name": "Source",
// "EndpointEnrichers": null
// },
// {
// "Name": "Target",
// "EndpointEnrichers": null
// }
// ]
// }
}
If you use this Azure DevOps Migration Tools, it can migrate Work Items, TestPlans & Suits, Teams, Shared Queries, & Pipelines from one Organization to another. You could refer to Processors: TfsAreaAndIterationProcessor, TfsTeamSettingsProcessor, TfsSharedQueryProcessor and Work Item Tracking Processor to create corresponding configuration Json files one by one.

Access nested JSON in React table

I want to display nested JSON data in a react-table.
I tried it like this:
render() {
const columns = [{
//Not Displaying
Header: 'Owner ID',
id: 'ownerid',
accessor: '_links.customer.href.ownerid', // <- i think this is wrong
Cell: this.renderEditable
},
{
//Displaying
Header: 'Price',
accessor: 'price',
Cell: this.renderEditable
}, {
The data i am getting back and have bound to the table is structured as follows:
[
{
"id": 1,
"date": "20.07.2019",
"price": 3.2,
"customer": {
"ownerid": 1,
"firstname": "John",
"lastname": "Johnson"
}
}
]
Here i am using the columns array:
import ReactTable from "react-table";
<ReactTable data={this.state.offers} columns={columns}
filterable={true} pageSize={10}/>
Binding the data:
fetchOffers = () => {
const token = sessionStorage.getItem("jwt");
fetch(SERVER_URL + 'api/offers',
{
headers : {'Authorization':token}
})
.then((response) => response.json())
.then((responsteData) => {
this.setState({
offers: responsteData._embedded.offers,
});
console.log(this.state);
})
.catch(err=> console.error(err));
}
The data i am using after binding:
Check the Accessors documentation. It has several examples for complex data structure.
I don't see _links or href in your sample data. So I think that you need just:
accessor: 'customer.ownerid'
The data structure from the console screenshot doesn't match your sample data. And it doesn't seem to contain ownerid. Try accessor: '_links.customer.href' to check whether it outputs anything to the table.
I figured it out.
I called the endpoint "localhost:8080/api/offers" and saved the following response:
"offers": [
{
"date": "20.07.2019",
"price": 3.2,
"_links": {
"self": {
"href": "http://localhost:8080/api/offers/1"
},
"offer": {
"href": "http://localhost:8080/api/offers/1"
},
"customer": {
"href": "http://localhost:8080/api/offers/1/customer"
}
}
}
]
there is no customer object
But when i call "localhost:8080/offers" i get:
[
{
"id": 1,
"date": "20.07.2019",
"price": 3.2,
"customer": {
"ownerid": 1,
"firstname": "John",
"lastname": "Johnson"
}
}
]
i changed the URI in my project and now the number is displaying.
I still don't know why i get data from "../api/offers" but i will research.
I had to access a nested object and display it with some styling, and this ended up working for me:
(Note: I was using typescript, so some of the typing might not be necessary)
{
Header: 'Thing To Display',
accessor: 'nested.thing.to.display',
Cell: ({ row }: { row: Row }) => (
<p>{row.values['nested.thing.to.display']}</p>
),
}

Angular http get data and put the json object to a variable

I want to get the nested data in officeid id , code ,name ,shortname, accroym . and put it into individual variable.
How to I do that ???
My code:
{
"id": 1,
"code": "1000-001-1-01-001-001",
"name": "PEACE AND ORDER PROGRAM",
"isActive": true,
"majorFinalOutput": null,
"officeId": 1,
"office": {
"id": 1,
"code": "1-01-001",
"name": "Office of the Governor",
"shortName": "PGO",
"accronym": "PGO",
"website": null,
"email": null,
"telephone": null,
"fax": null,
"type": "1"
},
"sectorId": 1,
"sector": {
"id": 1,
"name": "General Public Services Sector",
"code": "1000",
"parentId": null,
"parent": null
},
"dateCreated": "2018-10-02T14:23:04.913",
"dateModified": null,
"createdBy": null,
"modifiedBy": null
}
getProgram() {
return this.httpClient.get('api/programs/' + idhold).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
});
return this.programService.editProgram().finally( () => {
}).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
console.log(holdprogram.office.id);
console.log(holdprogram.office.name);
console.log(holdprogram.office.shortname);
}, error => {
console.error(error);
},
() => {
});
}
The usual simplest way to keep a reference to a variable obtained via a request is to use a component variable :
in the component :
public export class MyComponent {
...
public office: any; // instead of using 'any', you could create an interface corresponding to the structure
...
}
in the subscribe :
.subscribe((holdprogram: any[]) => {
this.office = holdprogram.office;
console.log(this.office);
// now this.office keeps a reference of your nested variable 'office'.
},
If you need to keep a reference for it across components, it's a bit more comlicated : you could do something similar at the service level (using tap and a local variable), and you'll need to add some more "cache handling" mechanism.

Remove proxies from Json Response Symfony2

I'm working in Symfony2 application and what I'm trying to do is to remove unwanted fields from response and show only fields that I want.
My JSON looks like this:
[
{
"id": 1,
"title": "Granit",
"typeId": {
"id": 1,
"name": "X or Y",
"acroname": "xory",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"pushDate": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460584800
},
"addedAt": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460548644
},
"deviceToShow": {
"id": 2,
"name": "Mobile",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"statusSurvey": false,
"slides": [
{
"id": 1,
"title": "First Question",
"picture1": "160413015724bazinga2.jpg",
"picture2": "160413015724th.jpg",
"idSurvey": 1,
"absolutePathpic1": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724bazinga2.jpg",
"webPathpic1": "uploads/slideSurvey/160413015724bazinga2.jpg",
"absolutePathpic2": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724th.jpg",
"webPathpic2": "uploads/slideSurvey/160413015724th.jpg",
"file": null,
"file1": null
}
],
"categories": []
}
]
I want to remove fields like "initializer": null,"cloner": null, "isInitialized": true and hide timezone object and show only "timestamp".
Here is my controller where I'm doing serializing and creating Json Response.
public function getAction()
{
$em = $this->getDoctrine ()->getManager ();
$survey = $em->getRepository ( 'AppBundle:Survey' )->findAll ();
if ( !$survey ) {
throw $this->createNotFoundException ( 'Data not found.' );
}
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler ( function ( $survey ) {
return $survey->getid ();
} );
$serializer = new Serializer( array ( $normalizer ), array ( $encoder ) );
$jsonContent = $serializer->serialize ( $survey, 'json' );
return new Response( $jsonContent );
}
Thank you.
Try to exclude this fields:
$normalilzer->setIgnoredAttributes(
[
"__initializer__",
"__cloner__",
"__isInitialized__"
]);
Detach entity to remove doctrine2 links to the object
$em->detach($survey);

MongoDB, NodeJS: updating an embedded document with new members

Using: MongoDB and native nodeJS mongoDB driver.
I'm trying to parse all the data from fb graph api, send it to my API and then save it to my DB.
PUT handling in my server:
//Update user's data
app.put('/api/users/:fbuser_id/:category', function(req, res) {
var body = JSON.stringify(req.body);
var rep = /"data":/;
body = body.replace(rep, '"' + req.params.category + '"' + ':');
req.body = JSON.parse(body);
db.fbusers.update({
id: req.params.fbuser_id
}, {
$set: req.body
}, {
safe: true,
multi: false
},
function(e, result) {
if (e) return next(e)
res.send((result === 1) ? {
msg: 'success'
} : {
msg: 'error'
})
});
});
I'm sending 25 elements at a time, and this code just overrides instead of updating the document.
Data I'm sending to the API:
{
"data": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Basically my API changes "data" key from sent json to the category name, f.e.:
PUT to /api/users/000/likes will change the "data" key to "likes":
{
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Then this JSON is put to the db.
Hierarchy in mongodb:
{
"_id": ObjectID("556584c8e908f0042836edce"),
"id": "0000000000000",
"email": "XXXX#gmail.com",
"first_name": "XXXXXXXX",
"gender": "male",
"last_name": "XXXXXXXXXX",
"link": "https://www.facebook.com/app_scoped_user_id/0000000000000/",
"locale": "en_US",
"name": "XXXXXXXXXX XXXXXXXXXX",
"timezone": 3,
"updated_time": "2015-05-26T18:11:59+0000",
"verified": true,
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
....and so on
}
]
}
So the problem is that my api overrides the field (in this case "likes") with newly sent data, instead of appending it to already existing data document.
I am pretty sure that I should be using other parameter than "$put" in the update, however, I have no idea which one and how to pass parameters to it programatically.
Use $push with the $each modifier to append multiple values to the array field.
var newLikes = [
{/* new item here */},
{/* new item here */},
{/* new item here */},
];
db.fbusers.update(
{ _id: req.params.fbuser_id },
{ $push: { likes: { $each: newLikes } } }
);
See also the $addToSet operator, it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.