How to construct Parse Objects from JSONs? - parse-server

I have JSONs like this;
{
createdAt: a_date,
text: "some text",
likes: 8
}
And I want to convert them into PFObjects… here’s how I do it;
let post = PFObject(className: "Post", dictionary: jsonPost)
The thing is that after that, the PFObject doesn’t have a value at its createdAt property.
post.createdAt <== this is always nil
I did some digging and tried this, but still no success;
jsonPost["_created_at"] = ["__type": "Date", "iso": "2020-09-23T13:31:08.877Z"]
Any idea why?

I think you might need to manually assign each param:
let postJson = {
createdAt: a_date,
text: "some text",
likes: 8
};
// create the Parse Object with Class 'Post'
let post = Parse.Object.extend('Post');
// assign param
post.set('text', postJson.text)
post.set('likes',postJson.likes)
post.save().then()...
createdAt is automatically handled by Parse Server when you save an object. If you want to manually control it with your own timestamp, then you will need to add a field:
post.set('myCreatedAt',postJson.createdAt)

Related

How to use gt/le operator in aurelia slickgrid with Odata

I want to send my own operator in odata request and not use the aurelia slickgrid inbuilt "eq" operator.
This is my column definition
{
id: 'LockoutEndDateUtc', name: 'Status', field: 'LockoutEndDateUtc', minWidth: 85, maxWidth: 95,
type: FieldType.boolean,
sortable: true,
formatter: Formatters.multiple,
params: { formatters: [this.StatusFormatter, Formatters.checkmark] },
filterable: true,
filter: {
collection: [
{ value: 'le ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'True' },
{ value: 'gt ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'False' }
], //['', 'True', 'False'],
model: Filters.singleSelect,//multipleSelect//singleSelect,
}
}
This is the UI
This is how the request filter looks like..
$filter=(LockoutEndDateUtc%20eq%20le%202022-06-28T12%3A59%3A25Z)
If i remove %20eq from the above request, everything else works. So my question is how to i remove %20eq. Or how do i send my own gt, le in the request.
You can't really do that on a boolean filter (you could however do it on a date filter with operator) and I don't think I've added any ways to provide a custom filter search the way you want to do it, but since you're using OData, you have a bit more control and you could change the query string yourself. To be clear, it's not at all recommended to change the OData query string, it's a last solution trick and at your own risk, but for your use case it might be the only way to achieve what you want.
prepareGrid() {
this.gridOptions = {
// ...
backendServiceApi: {
service: new GridOdataService(),
process: (query) => this.getCustomerApiCall(query),
} as OdataServiceApi
};
}
}
getCustomerApiCall(query: string) {
let finalQuery = query;
// in your case, find the boolean value from the column and modify query
// your logic to modify the query string
// untested code, but it would probably look similar
if (query.includes('LockoutEndDateUtc%20eq%20true')) {
// calculate new date and replace boolean with new date
finalQuery = query.replace('LockoutEndDateUtc%20eq%20true', 'LockoutEndDateUtc%20le%202022-06-28T12%3A59%3A25Z');
}
return finalQuery;
}
Another possible solution but requires a bit more work.
If I'd be using a regular grid, without backend service and without access to the query string, I would probably add an external drop down outside of the grid and also add the date column and then control filters in the grid by using dynamic filtering. You can see a demo at Example 23, the principle is that you keep the column's real nature (date in your case) and filter it, if you want something like a "below today's date" then add an external way of filtering dynamically (a button or a drop down) and control the filter dynamically as shown below (from Example 23)

Filtering dstore collection against an array field

I'm trying to filter a dstore collection by a field that has an array of values. My json data looks like the following (simplified):
[{
user_id: 1,
user_name: "John Doe",
teams: [{team_id: 100, team_name: 'Red Sox'}, {team_id: 101, team_name: 'Buccaneers'}]
},
{
user_id: 2,
user_name: "Fred Smith",
teams: [{team_id: 100, team_name: 'Buccaneers'}, {team_id: 102, team_name: 'Rays'}]
}]
I can do a simple filter against the username field and it works perfectly.
this.dstoreFilter = new this.dstore.Filter();
var results = this.dgrid.set('collection', this.dstore.filter(
this.dstoreFilter.match('user_name',new RegExp(searchTerm, 'i'))
));
How, though, do I construct a filter to show me only those players who play for the Red Sox, for example. I've tried using the filter.contains() method, but I can't find any adequate documentation on how it works. Looking at the dstore code, I see that the filter.contains() method has the following signature: (value, required, object, key), but that's not helping me much.
Any guidance would be much appreciated. Thanks in advance!
You can find documentation on Filtering here.
In your case, .contains() will not work because it is intended to work on values of array type. What you want to filter here is array of objects. Here is a quote from the doc link:
contains: Filters for objects where the specified property's value is an array and the array contains any value that equals the provided value or satisfies the provided expression.
In my opinion, the best way here is to override the filter method where you want to filter by team name. Here is some sample code:
this.grid.set('collection', this.dstore.filter(lang.hitch(this, function (item) {
var displayUser = false;
for(var i=0; i < item.teams.length; i++){
var team = item.teams[i];
if(team.team_name == 'Red Sox'){
displayUser = true;
break;
}
}
return displayUser;
})));
this.grid.refresh();
For each user in the store, if false is returned, it's display is set to false and if true is returned it gets displayed. This is by far the easiest way that I know of to apply complex filtering on dstore.
Some similar questions that you might want to read up: link, link, link

How to search array of int as property?

My Show Object:
class Show extends Realm.Object { }
Show.schema = {
name: 'Show',
primaryKey: 'showId',
properties: {
showId: 'int',
showName:{ type: 'string', default: '' },
episodes:{ type: 'int[]', default: [] },
}
};
How then can I search the Show objects via the episodes property?
I have already search here and there and tried:
.filtered('episodes == $0',12345)
.filtered('episodes IN $0',12345)
but nothing works.
IN predicates aren't yet supported, however, there are a couple of workarounds:
Property Array Contains Value
If you want to know if an array property on your Realm object contains one or more values, you can't use primitive values like int[] in your example. If instead you create an Episode schema with an id property, you can then do a filtered('episodes.id == $0', 12345).
Scalar Property in Array
This can be done by mapping and joining a set of predicates until IN is supported which looks something like the following psuedocode:
.filterted([1,2,3].map(id => 'property == id').join(' OR '))

Keen-io: i can't delete special event using extraction query filter

using extraction query (which used url decoded for reading):
https://api.keen.io/3.0/projects/xxx/queries/extraction?api_key=xxxx&event_collection=dispatched-orders&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800
return
{
result: [
{
mobile: "13185716746",
keen : {
timestamp: "2015-02-10T07:10:07.816Z",
created_at: "2015-02-10T07:10:08.725Z",
id: "54d9aed03bc6964a7d311f9e"
},
data : {
itemId: 2130,
num: 1
},
features: {
communityId: 2000,
dispatcherId: 39,
tradeId: 8581
}
}
]
}
but if i use the same filters in my delete query url (which used url decoded for reading):
https://api.keen.io/3.0/projects/xxxxx/events/dispatched-orders?api_key=xxxxxx&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800
return
{
properties: {
data.num: "num",
keen.created_at: "datetime",
mobile: "string",
keen.id: "string",
features.communityId: "num",
features.dispatcherId: "num",
keen.timestamp: "datetime",
features.tradeId: "num",
data.itemId: "num"
}
}
plz help me ...
It looks like you are issuing a GET request for the delete comment. If you perform a GET on a collection you get back the schema that Keen has inferred for that collection.
You'll want to issue the above as a DELETE request. Here's the cURL command to do that:
curl -X DELETE "https://api.keen.io/3.0/projects/xxxxx/events/dispatched-orders?api_key=xxxxxx&filters=[{"property_name":"features.tradeId","operator":"eq","property_value":8581}]&timezone=28800"
Note that you'll probably need to URL encode that JSON as you mentioned in your above post!

Elasticsearch/Lucene highlight

How to highlight result query with fuzzyLikeThisFieldQuery in elasticsearch? I can pick up on fuzzyQuery but not fuzzyLikeThisFieldQuery. For example, in the code below i used fuzzyQuery:
QueryBuilder allquery = QueryBuilders.fuzzyQuery("name", "fooobar").minSimilarity(0.4f);
SearchRequestBuilder builder = ds.getElasticClient()
.prepareSearch("data")
.setQuery(allquery)
.setFrom(0)
.setSize(10)
.setTypes("entity")
.setSearchType(SearchType.DEFAULT)
.addHighlightedField("name")
.addField("name");
SearchResponse sr = builder.execute().actionGet();
the result is
If you want to have a <em>foobar</em> for oracle
But if i use fuzzyLikeThisFieldQuery, didn't highlight
QueryBuilder allquery = QueryBuilders.fuzzyLikeThisFieldQuery("name").likeText("fooobar").minSimilarity(0.4f);
the result is
If you want to have a foobar for oracle
Anyone know why?
You need to call these two functions to set the highlighter tags..
builder.setHighlighterPreTags("<pre>").setHighlighterPostTags("</pre>");
I need to highlight the keyword and use the method I've written below works fine for me:
searchRequest.setQuery(
QueryBuilders.queryString(q))
.addHighlightedField("title")
.addHighlightedField("text")
.setHighlighterPreTags("<em>")
.setHighlighterPostTags("</em>");
_searchResponse = searchRequest.execute().actionGet();
I use Gson to parse response string as a json object and cast to my entity like below:
root = new JsonParser().parse(_searchResponse.toString());
p.results.add(root.getAsJsonObject().get("hits").getAsJsonObject().get("hits"));
You will get such a response like this:
content: {
results: [
[
{
_index: "news",
_type: "news",
_id: "111",
_score: 0.6056677,
_source: {
id: "1349298458",
title: "Title text",
text: "Detail text"
},
highlight: {
text: [
" some text <em>keyword</em> some text <em>keyword</em>- some text <em>keyword</em> some text."
]
}
},...
Wish you to get how it works and try it yourself.