I want to save all the searches from the user as a key of objects (search field):
beforeState = fromJS({
showFilter: false,
loading: false,
error: false,
search: fromJS({})
})
afterState = fromJS({
showFilter: false,
loading: false,
error: false,
search:
key1: [{}, {},...],
key2: [{}, {}, {}...]
})
New data:
const searchText = 'test'
const data = [{object1}, {object2},....]
const expectedResult = state
search has to be immutable as it can change. key1, key2... doesn't need to, as once they're initilised won't change.
Two questions:
I think I need fromJS function in searchKey in order to get a map, I mean, fromJS function does not nest maps
var t = beforeState.get('search').constructor.name;
console.log(t) //gets Map but without fromJS gets Object
But as array inside key1, key2, can't mutate, another fromJS would't be needed. Is it that way?
How can I insert key1, key2.. values inside search field?
Using mergeDeep, seems to be ok:
var boxes = Immutable.fromJS({
box1: {
id:1
},
box2: {
id:2
},
search: Immutable.fromJS({box3: {z:7}})
});
var data = Immutable.fromJS({
search: {
box3: {id:3}
}
});
var newBoxes = boxes.mergeDeep(data);
console.log(newBoxes.get('search').toJS());
Related
I just tried to run the JSONIX sample purchase order.
I did it like it was mentioned on the Highscore WebSite.
What makes me wonder was this sample bases on the use of a XSD, the validation of the incoming XML is used for elements with child nodes but not for simple tags.
This will show an error:
... <item_will_cause_error partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
... </item_will_cause_error>
This not:
... <item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity_will_cause_error>1</quantity_will_cause_error>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
... </item>
So, is it possible to switch on a strong validation, because <quantity_will_cause_error>is not a valid element.
Kind regards
Markus
now I use this
var Jsonix = require('jsonix').Jsonix;
//Include or require PO.js so that PO variable is available
//For instance, in node.js:
var PO = require('./mappings/PO').PO;
//First we construct a Jsonix context - a factory for unmarshaller
//(parser)
//and marshaller (serializer)
var context = new Jsonix.Context([ PO ]);
//Then we create a unmarshaller
var unmarshaller = context.createUnmarshaller();
//Unmarshal an object from the XML retrieved from the URL
var fs = require('fs');
var Ajv = require('ajv');
var XMLSchemaJsonSchema =
JSON.parse(fs.readFileSync(
'./node_modules/jsonix/jsonschemas/w3c/2001/XMLSchema.jsonschema')
.toString());
var JsonixJsonSchema = JSON.parse(fs.readFileSync(
'./node_modules/jsonix/jsonschemas/jsonix/Jsonix.jsonschema')
.toString());
var POJsonSchema = JSON.parse(fs.readFileSync(
'./mappings/PO.jsonschema').toString());
var ajv = new Ajv();
ajv.addSchema(XMLSchemaJsonSchema,
'http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema');
ajv.addSchema(JsonixJsonSchema,
'http://www.jsonix.org/jsonschemas/jsonix/Jsonix.jsonschema');
var validate = ajv.compile(POJsonSchema);
unmarshaller.unmarshalFile('./po.xml',
//This callback function will be provided
//with the result of the unmarshalling
function (unmarshalled) {
var po_ = unmarshalled;
var valid = validate(po_);
if (!valid) {
console.log('Validation failed.');
console.log('Validation errors:');
console.log(validate.errors);
}
});
The Result looks like this:
Validation failed.
Validation errors:
[ { keyword: 'type',
dataPath: '.value.items.item[1].shipDate.timezone',
schemaPath: '#/definitions/integer/type',
params: { type: 'integer,null' },
message: 'should be integer,null' },
{ keyword: 'type',
dataPath: '.value.items.item[1].shipDate',
schemaPath: '#/anyOf/1/type',
params: { type: 'null' },
message: 'should be null' },
{ keyword: 'anyOf',
dataPath: '.value.items.item[1].shipDate',
schemaPath: '#/anyOf',
params: {},
message: 'should match some schema in anyOf' },
{ keyword: 'enum',
dataPath: '.name.localPart',
schemaPath: '#/anyOf/1/properties/name/allOf/1/properties/localPart/enum',
params: { allowedValues: [Object] },
message: 'should be equal to one of the allowed values' },
{ keyword: 'anyOf',
dataPath: '',
schemaPath: '#/anyOf',
params: {},
message: 'should match some schema in anyOf' } ]
But this make me again wonder: dataPath: '', an error on the root ???
There is a way to display the dataSource as rows and not columns?
My dataSource has only one record with 30 properties. I would like to display the properties as rows (property1 => row1, property2 => row2, ...) instead of columns (property1 => column1, property2 => column2, ....).
In fact, I would like to retrieve 3 records (each one with 30 properties), but the 3 records would be the colums and the common 30 properties would be the rows.
How can I do that?
This is what I did so far, but I'm not sure this is the right way.
var _dataSource = function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: { // returns only 3 records
url: url,
dataType: "json"
}
},
schema : {
data: "data",
total: "total",
parse: function (data) {
console.log(data);
var dataArray = [];
var i = 0;
for (var property in data[0]) {
console.log(property);
console.log(data[0][property]);
var record = {
header: "",
headerId: "",
record1: "",
record2: "",
record3: ""
};
record.header = headerRows[i]; // array of header string (the 30 properties)
record.headerId = property;
record.record1 = data[0][property];
record.record2 = data[1][property];
record.record3 = data[2][property];
console.log(record);
dataArray.push(record);
i++;
}
return dataArray;
}
}
});
return dataSource;
};
But this gives the error: TypeError: e is undefined
Got it! So simple!
Instead of build the logic on schema.parse, I did it on schema.data.
Actually, it makes more sense on schema.data. Don't know why I was trying on schema.parse.
I want to define my mongoose schema from JSON file. This is my JSON file structure:
{
"default": [
{
"item": "productTitle",
"label": "Product Title",
"note": "e.g Samsung GALAXY Note 4",
"type": "text",
"required": "Product Name cannot be blank..."
},
{
"item": "productCode",
"label": "Product Code",
"type": "text",
"required": "Product Code cannot be blank..."
}
]}
This is my node.js model:
// Load the module dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var fs = require('fs');
var file = __dirname + '/product.server.model.json';
// Read the json file
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
productJson[data.default[i].slug] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
});
// Define a new 'ProductSchema'
var ProductSchema = new Schema(
// Here I want to put JSON Data 'productJson'
);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I tried every possible way to define mongoose schema from JSON data 'productJson'. But unless I pre-define my mongoose schema, it is not working. Is there any way to define mongoose schema from JSON data in my model? Any suggestion please?
fs.readFile is an asynchronous function which means that it returns immediately and then later provides its results to the caller via the callback function that you provide as the third parameter.
As such, you need to hold off on using productJson until its populated within that callback. That means moving your schema and model creation inside the callback as well.
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
});
Another alternative you can use here is to use the synchronous fs.readFileSync method to read the file instead. This is helpful in startup/initialization cases like this where your application as a whole shouldn't proceed until this file is processed.
var data = fs.readFileSync(file, 'utf8');
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I have a simple set of JSON data that I am pulling from a local file and loading into a datatable
Using YUI, how can I filter the response of this request to match only the data that is relevant to the request data?
EDIT: improper formatting on first post
YUI().use('aui-datatable', 'datatable-sort', 'aui-io-request', 'aui-tabview', 'datasource-io',
function(Y) {
var columns = [{
key : 'id',
sortable : true
}, {
key : 'name',
sortable : true
},{
key : 'price',
sortable : true
}];
var dataTable = new Y.DataTable({
columns : columns
}).render("#searchResultsTab");
var node = Y.one('#searchButton');
var criteria = document.getElementById("searchCriteria");
node.on(
'click', //on Search..
function(){
dataSource = new Y.DataSource.IO({source:'mydata.json'});
request = document.getElementById("searchBox").value;
dataSource.sendRequest({
on: {
success: function(e){
var response = e.data.responseText;
jdata = Y.JSON.parse(response);
dataTable.set('data', jdata.info); //setting table data to json response
},
failure: function(e){
alert(e.error.message);
}
}
});
}
);
new Y.TabView(
{
srcNode: '#searchResultsContainer'
}
).render();
});
mydata.json
{"info" : [
{"id": 1,"name": "A green door","price": 12.50 },
{"id": 2,"name": "A blue door","price": 10.50 },
{"id": 3,"name": "A red door","price": 8.50 }
}
In your on success method filter your response data before setting the datatable data source. Here is an example of model list filtering: http://yuilibrary.com/yui/docs/model-list/#filtering-models
var CustomGrid = declare([Grid, Keyboard, Selection]);
var questionGrid = new CustomGrid({
store: questionCacheStore,
columns: [
editor({
label: "Questions",
field: "question",
editor: "text",
editOn: "dblclick",
sortable:true})
],
selectionMode: "single",
cellNavigation: false
}, "questions");
I am new to Dgrid. So, please do bear with me .
i was able to populate the dgrid with a JsonStore content. But when i click on the column 'Questions', it doesn't get sorted as in local data store.instead it shows an error Uncaught TypeError: Object [object Object] has no method 'sort'. Is it required to define such a method . If so, how and where should i define it ?
I am not the person to answer your J2EE question. I asked that question recently. The solution that I found was to inject the HttpServletRequest directly. This allowed me access to the query string parameters. From there I was able to get the sort direction (ascending, descending) and column to sort. Hopefully the snippets below will help.
Example Grid Setup
require(["dojo/store/JsonRest", "dojo/store/Memory", "dojo/store/Cache",
"dojo/store/Observable", "dgrid/OnDemandGrid", "dojo/_base/declare", "dgrid/Keyboard",
"dgrid/Selection", "dojo/domReady!"],
function(JsonRest, Memory, Cache, Observable, Grid, declare, Keyboard, Selection) {
var rest = new JsonRest({target:"/POC_Admin/rest/Subcategory/", idProperty: "subcatId"});
var cache = new Cache(rest, new Memory({ idProperty: "subcatId" }));
var store = new Observable(cache);
var CustomGrid = declare([ Grid, Keyboard, Selection ]);
var grid = new CustomGrid({
columns: {
subcatId: "ID",
name: "Name"
},
store: store
}, "grid");
grid.on("dgrid-select", function(event){
// Report the item from the selected row to the console.
console.log("Row selected: ", event.rows[0].data);
});
grid.startup();
});
Example Rest GET
#Context private HttpServletRequest servletRequest;
#GET
#Path("")
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String getSubcategories(#QueryParam("name") String name) throws IOException {
//Respond to a QueryString value.
if (servletRequest.getQueryString() != null && servletRequest.getQueryString().length() > 0) {
String querystringKey = servletRequest.getQueryString();
System.out.println("QSKey = " + querystringKey);
System.out.println("Substr: " + querystringKey.substring(0, 4));
if (querystringKey.length()>4) {
if (querystringKey.substring(0, 4).contains("sort")) {
//We have the sort request.
}
}
}
//Return all results otherwise from your DAO at this point
}