New Parse forces "optional", how to query a PFUser? - xcode

I have this code that due to the x-code changes is no longer working.
var query = PFUser.query()
var user = PFUser.currentUser()!.username
query!.whereKey("username", equalTo: "\(user)")
query!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
The problem is that the PFUser.currentUser()!.username aka, the "user" variable now prints out the following : Optional("username")
Therefore, it searches for a username with the text: Optional("") and a username between the quotes.
So it doesn't find a username.
Ever since the last x-code update, the query is requiring this optional crap.

got it to work.
var query = PFUser.query()
query!.whereKey("username", equalTo: PFUser.currentUser()!.username!)
query!.findObjectsInBackgroundWithBlock {
added a ! after username in PFUser.currentUser()!.username!

Related

Unable to get result of productByHandle query when nil when using shopify_api with graphql query

I am trying to retrieve the result from a graphQL query when the product is nil by using the productByHandle query, but it's erroring out.
My code in Ruby:
client = ShopifyAPI::GraphQL.client
product_handle_query = client.parse <<-'GRAPHQL'
query ($productHandle: String!) {
productByHandle(handle: $productHandle) {
id
handle
title
tags
productType
vendor
}
}
GRAPHQL
result = client.query(product_handle_query, variables: {productHandle: productHandle})
puts result.data.productByHandle
This should return nil, but when I try and message out, it returns with this error:
NoMethodError (undefined method `productByHandle' for #< productByHandle=nil>)
This query works fine in Insomnia, where the output looks like this:
{
"data": {
"productByHandle": null
},
"extensions": {
"cost": {
"requestedQueryCost": 1,
"actualQueryCost": 1,
"throttleStatus": {
"maximumAvailable": 2000.0,
"currentlyAvailable": 1999,
"restoreRate": 100.0
}
}
}
}
I have also tried changing from String! (which is not-null type which is what is returning) to String, but I get this error:
GraphQL::Client::ValidationError (Nullability mismatch on variable $productHandle and argument handle (String / String!))
My variable for $productHandle is indeed a string, so not sure why this isn't working either.
Any help would be appreciated.
Thanks!
Figured out how to read the result from the output above:
result.original_hash["data"]["productByHandle"]
This returns nil and allows me to continue to create a new product.

Chat app list last messages of each peer using parse server

I am doing a chat app using parse server, everything is great but i tried make to list just last message for every remote peer. i didn't find any query limitation how to get just one message from every remote peer how can i make this ?
Query limitation with Parse SDK
To limit the number of object that you get from a query you use limit
Here is a little example:
const Messages = Parse.Object.extend("Messages");
const query = new Parse.Query(Messages);
query.descending("createdAt");
query.limit(1); // Get only one result
Get the first object of a query with Parse SDK
In you case as you really want only one result you can use Query.first.
Like Query.find the method Query.first make a query and will return only the first result of the Query
Here is an example:
const Messages = Parse.Object.extend("Messages");
const query = new Parse.Query(Messages);
query.descending("createdAt");
const message = await query.first();
I hope my answer help you 😊
If you want to do this using a single query, you will have to use aggregate:
https://docs.parseplatform.org/js/guide/#aggregate
Try something like this:
var query = new Parse.Query("Messages");
var pipeline = [
{ match: { local: '_User$' + userID } },
{ sort: { createdAt: 1 } },
{ group: { remote: '$remote', lastMessage: { $last: '$body' } } },
];
query.aggregate(pipeline)
.then(function(results) {
// results contains unique score values
})
.catch(function(error) {
// There was an error.
});

Criteria Builder query LIKE in json field

I am trying to build a query with Criteria Builder(LIKE), to look for a string in JSONARRAY field like this:
[
{
"family_class": "Electric",
"family_name": "lightBulb"
},
{
"family_class": "Others",
"family_name": "Oil"
}
]
one option would be to look for the family_name attribute, or maybe check if it contains the string there.
if (residues != null && residues.length > 0) {
List<Predicate> predicates = new ArrayList<Predicate>();
for (String residue : residues) {
predicates.add(cb.like(root.get("jsonColumn"), residue.toLowerCase()));
}
cr.select(root).where(predicates.toArray(new Predicate[] {}));
Query<SyncCollectionPoints> q = sess.createQuery(cr);
List<SyncCollectionPoints> result= q.getResultList();
This is the error i get:
Unrecognized token 'oil': was expecting ('true', 'false' or 'null')
All i want is to return the lines that have that string in the jsonColumn field.
I got it to work like this:
#Formula(value = "lower(jsonColumn::text)")
private String residuesToSearch;
just a simple cast did the trick

Resolving query type with promise in bucklescript

I've got this query im trying to test with with the reason graphql_ppx library. code gist
This is a screenshot of the editor type annotations:
Using the #mhallin/graphql_ppx library, i've got the following query set up:
module FilmQuery = [%graphql
{|
{
allFilms {
films {
id
title
releaseDate
}
}
}
|}
];
exception Graphql_error(string);
/* Construct a "packaged" query; FilmQuery takes no arguments: */
let filmQuery = FilmQuery.make();
/* Send this query string to the server */
let query = filmQuery##query // type string
I get an the following error when i send the query to the server it returns the following error.
{ errors: [ { message: 'Must provide query string.' } ] }
But if you Js.log(query) you see its being constructed which works on https://swapi.apis.guru
query films($first: Int) {
allFilms(first: $first) {
films {
id
title
releaseDate
}
}
}
If you Js.log(filmQuery) you get:
{ query: 'query {\nallFilms {\nfilms {\nid \ntitle \nreleaseDate \n}\n}\n}',
variables: null,
parse: [Function: parse] }
If your run the same query in Altair and you check the query that was sent in the devtools network tab you see:
{"query":" query films($first: Int) {\n allFilms(first: $first) {\n films {\n id\n title\n releaseDate\n }\n }\n }\n","variables":{}}
The editor is provided this type error:
"- error
[bucklescript]
This has type:
string
But somewhere wanted:
Js.t({.. query : string, variables : Js.Json.t })
string"
How do I get this promise/unit type resolved? Thank you.
So the new question is: Why isn't the sendQuery() function recognizing the filmQuery##parse key?
Your sendQuery method is expecting a type in the shape of what is returned from FilmQuery.make(), but you are passing it just the query property, which is a string.
You can fix this by passing filmQuery as into sendQuery instead of just the query property from filmQuery that is referenced by the query variable.

Why can I not remove an unused function from my Swift Class?

See the function 'postRequest' in this UserModel class I have defined. Well the function is not used anymore anywhere and when I try to remove it XCode syntax highlighting crashes and my program will not compile with a segmentation fault error 11 which points to nowhere.
I moved the function into a struct called SharedModel. So this function is not called anywhere! Why can I not remove it from the file? It makes no sense, I just want to remove an unused function. But Xcode keeps crashing and it makes me keep it! What is going on.
import Foundation
import SwiftHTTP
import SwiftyJSON
public enum UserProperties : String {
case user_id = "user_id", single_access_token = "single_access_token", first_name = "first_name",
last_name = "last_name", role = "role", email = "email", username = "username", barn_id = "barn_id",
location_id = "location_id", farm_id = "farm_id"
static let allValues = [user_id, single_access_token, first_name, last_name, role, email, username, barn_id, location_id, farm_id]
}
class UserModel {
var userPropertiesJSON: JSON?
init () {
}
func postRequest(url: String, params: Dictionary<String,AnyObject>, completionHandler: (JSON?) -> ()) {
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
//The expected response will be JSON and be converted to an object return by NSJSONSerialization instead of a NSData.
request.responseSerializer = JSONResponseSerializer()
//we have to add the explicit type, else the wrong type is inferred. See the vluxe.io article for more info.
//let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
request.POST(url, parameters: params, success: {(response: HTTPResponse) in
println(response.responseObject!)
let json = JSON(response.responseObject!)
completionHandler(json)
},failure: {(error: NSError, response: HTTPResponse?) in
completionHandler(false)
})
}
func login(username: String, password: String, completionHandler: (Bool) -> ()) {
let params: Dictionary<String,AnyObject> = ["username": username, "password": password]
SharedModel.postRequest("http://farmcentral.softimum.com/user_sessions.json", params: params) { jsonOrError in
if let json: JSON = jsonOrError {
self.userPropertiesJSON = json
SharedModel.userPropertiesJSON = json
completionHandler(true)
} else {
completionHandler(false)
}
}
}
}
UPDATE
Still and issue but I have narrowed it down to the exact line of code that if removed causes xcode to crash and causes the build to stop compiling due to a segment fault 11 error.
This is the offending line: let json = JSON(response.responseObject!)
This line is in the function inside the closure. When I remove this line Xcode crashes. I am running cocoapods beta version, this might be a bug.
This was a bug with the framework I was using called SwiftyJSON. The solution was to import SwiftyJSON.swift file directly into your project.
Here is the Github issue: https://github.com/SwiftyJSON/SwiftyJSON/issues/67

Resources