Firestore document not incrementing using REST API - php

I am trying to increment my Cloud Firestore using the REST API, however the documentation is unclear as to how this works. Here is my current implementation:-
I am trying to increment the integer value 'c' by 2, so if server value stored is 10 I want it to become 12 with this. Please help.
{
"writes": [
{
"currentDocument": {
"exists": true
}
},
{
"transform": {
"document": "projects/project_name/databases/(default)/documents/collection_name/user_id",
"fieldTransforms": [
{
"increment": {
"c": {
"integerValue": "2"
}
}
}
]
}
}
]
}
Error I keep getting:-
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"\": Root element must be a message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"\": Root element must be a message."
}
]
}
]
}
}
Edit: Here's the error after fixing my payload:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"writes\" at 'document': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "document",
"description": "Invalid JSON payload received. Unknown name \"writes\" at 'document': Cannot find field."
}
]
}
]
}
}

As per the FieldTransform documentation, you must set a fieldPath on your JSON representation. Here's the list of possible types for union field transform_type:
{
"fieldPath": string,
// Union field transform_type can be only one of the following:
"setToServerValue": enum (ServerValue),
"increment": {
object (Value)
},
"maximum": {
object (Value)
},
"minimum": {
object (Value)
},
"appendMissingElements": {
object (ArrayValue)
},
"removeAllFromArray": {
object (ArrayValue)
}
// End of list of possible types for union field transform_type.
}
You should remove the fieldPath which is c inside the increment:
"fieldTransforms": [
{
"increment": {
"c": {
"integerValue": "2"
}
}
}
]
and change it to this structure:
"fieldTransforms": [
{
"fieldPath": "<FieldName>",
"increment": {
"integerValue": "2"
}
}
]
And also, just want to note that currentDocument and transform should be both inside the objects of writes. For reference, here's the full JSON representation based on your given JSON representation above:
{
"writes": [
{
"currentDocument": {
"exists": true
},
"transform": {
"document": "projects/project_name/databases/(default)/documents/collection_name/user_id",
"fieldTransforms": [
{
"fieldPath": "c",
"increment": {
"integerValue": "2"
}
}
]
}
}
]
}
Here's the result by using the Postman:
For more information, you may want to check Firebase REST API: Write.

Related

can I throw custom error in laravel-lighthouse

is the any way that throw an error by GraphQL\Error\Error with no additional data except message.
the current return data is
{
"errors": [
{
"message": "Some Errors",
"extensions": {
"reason": "",
"category": "custom"
},
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"to the path"
],
"trace": [{},{},{},{}]
}
],
"data": {
"testQuery": null
}
}
it contains unnecessary data
but I want something like:
{
"errors": [
{
"message": "Some Errors",
"extensions": {
"reason": "",
"category": "custom"
},
],
"data": {
"testQuery": null
}
}
You can throw your own exceptions, that will allow you to do that. Check https://lighthouse-php.com/5/digging-deeper/error-handling.html#registering-error-handlers.
for a simple error you can use this code, in case you don't want to create an error handler class
use GraphQL\Error\Error;
...
return Error::createLocatedError('Some Errors');

How to add item to an object in php

I have a nested object which is generated by a base data in a function. the data generated is several levels deep (data_tree)
To enter each children I use a recursive function.
What I want is to add the data of the children2 item to children and remove children2
Next I show the data_tree in JSON format to get an idea of ​​how the structure is. remember that the data_tree is an object
{
"data_tree": [
{
"code":"PE",
"country":"Peruvian",
"language" :"spanish",
"children":[
{
"code": "DEP1" ,
"region":"Tumbes",
"children": [
{
"code": "PRO1",
"province":"Contralmirante Villar"
}
],
"children2": [
{
"code": "PRO2",
"province":"Zarumilla "
}
]
},
{
"code": "DEP2" ,
"region":"Piura",
"children": [],
"children2": [
{
"code": "PRO4",
"province" :"Paita"
},
{
"code": "PRO5",
"province":"Sullana"
}
]
},
{
"code": "DEP3" ,
"region":"Lambayeque"
}
],
"children2":[
{
"code": "DEP4" ,
"region":"La Libertad"
},
{
"code": "DEP5" ,
"region":"Lima"
}
]
},
{
"code":"EC"
"country":"Ecuador",
"language" :"spanish",
"children":[
{
"code": "4" ,
"province":"Quito"
},
{
"code": "5" ,
"province":"Guayaquil"
}
],
"children2":[]
}
]
}
the recursive function i use is: if it has children it keeps iterating.
$traverse = function ($data_tree) use (&$traverse) {
foreach ($data_tree as &$node) {
if (empty($node->children)) { //if the children is empty
unset($node->children); //I remove the children to add it with the data of children2
$node->children =$node->children2;
unset($node->children2);//I delete children2
}else{
//in case I have data, how do I add the data from dechildren2 to children?
}
$traverse($node->children);
}
};
$traverse($data_tree);
return $data_tree;
All problem solved using json decode mean in associative array
$data_json='[{"children":[],"children2":[{"children":[],"children2":[{"code":"PRO1","children":[],"children2":[{"code":"PRO1"}]}]}]},{"children":[],"children2":[{"children":[{"code":"PRO1","children":[],"children2":[{"code":"PRO1"}]}]}]}]';
//$data_tree=;
$data_tree =json_decode($data_json,true);
// var_dump($data_tree);
$traverse = function (&$data_tree) use (&$traverse) {
foreach ($data_tree as &$node) {
// var_dump($node);
if (empty($node['children']) && !empty($node['children2'])) { //if the children is empty
// var_dump($node);
$node['children'] =$node['children2'];
unset($node['children2']);//I delete children2
}else{
//in case I have data, how do I add the data from dechildren2 to children?
}
if(isset($node['children'])){
$traverse($node['children']);
}
if(isset($node['children2'])){
$traverse($node['children2']);
}
}
};
$traverse($data_tree);
Output
[{"children":[{"children":[{"code":"PRO1","children":[{"code":"PRO1"}]}]}]},{"children":[{"children":[{"code":"PRO1","children":[{"code":"PRO1"}]}]}]}]

PHP Select Data from Json

My JSON Data
{
"users": [
{
"userid": 1,
"username": "Admin",
"usermail": "admin#admin.com",
"authority": [
{
"authorityid": 1,
"authoritytext": "Admin",
"mission": [
{
"permission": "add"
},
{
"permission": "delete"
},
{
"permission": "move"
}
]
},
{
"authorityid": 1,
"authoritytext": "Super Admin",
"mission": [
{
"permission": "no add"
},
{
"permission": "no delete"
},
{
"permission": "only moderate"
}
]
}
]
}
]
}
MY PHP
foreach($result->users as $ok) {
foreach($ok->authority as $okey) {
foreach($okey->mission as $okeyokey) {
$test = $okeyokey->permission;
echo $test;
}
}
}
How to make this?
I want show parse json only authority{0} -> misson{0} show "permission" "add" please help me .
Maybe look ScreenShot >>>>>
I want filter {0}{1}{2} and select 0 -> show parse json
enter image description here
Is this what you are looking for?
<?php
$jsonData = '{
"users": [
{
"userid": 1,
"username": "Admin",
"usermail": "admin#admin.com",
"authority": [
{
"authorityid": 1,
"authoritytext": "Admin",
"mission": [
{
"permission": "add"
},
{
"permission": "delete"
},
{
"permission": "move"
}
]
},
{
"authorityid": 1,
"authoritytext": "Super Admin",
"mission": [
{
"permission": "no add"
},
{
"permission": "no delete"
},
{
"permission": "only moderate"
}
]
}
]
}
]
}';
$data = json_decode($jsonData);
echo($data->users[0]->authority[0]->mission[0]->permission);
You are getting objects and arrays confused
foreach($result->users as $currentUser){
$auths = $currentUser->authority;
foreach($auths as $currentAuth){
foreach($currentAuth->mission as $permission){
foreach($permission as $positionLabel => $permissionValue){
if($permissionValue == "add"){
// code here
}
}
}
}
}
Make sure you are using good labels. Dummy placeholders can be fine, but it makes tracking bugs really hard. I assume you want to check if they hold permission using a database, using PDO?
// array
$arr = ["this", "is", "an", "array"];
echo $arr[0] // prints out the word this.
$json = { "attribute": "value"}
echo $json->attribute // prints out the word value.
You can have arrays in JSON objects, and JSON Objects in arrays. How you access them are different.

[Dialogflow]Update Permission through Webhook format (for push notifications)

ORIGINAL REQUEST: I'm trying to implement the push notifications following the documentation: https://developers.google.com/actions/assistant/updates/notifications
I'm using Dialogflow with webhooks (in PHP) and the documentation is giving example in nodeJS
Right now, i'm blocked because of the Update permission, here's my Webhook response :
{
"source": "webhook",
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
]
},
"updatePermission": {
"intent": "notification.simple.text"
}
}
}
}
}
When I do the simulation, asks me a permission for a push, but not for the intent I specified.
I'm quiet sure that the problem is the updatePermission, something must be wrong with that:
Is it the field name?
In intent, i put the intent name that i filled in dialogflow, maybe do i have to an use action? Is it in the good format ?
If someone can help me or just give me an example of a clean response for an update permission.
Thanks!
Solution
I just found why, my json wasn't good, the updatePermissionValueSpec must be into data object.
{
"source": "webhook",
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
],
"updatePermissionValueSpec": {
"intent": "notification_simple_text"
}
}
}
}
}
}
I believe updatePermission should be named updatePermissionValueSpec.
Example response:
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "PLACEHOLDER"
}
}
]
},
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
],
"updatePermissionValueSpec": {
"intent": "intent_name"
}
}
}
}
}

Elastic Search different reults on URL query and JSON POST

I'm completing a search function on a big online webstore.
I have a problem with additional fields. When I try searching for some fields in browser, it works, but when posting a JSON using bool filter, it gives me 0 results (doesn't raise an error).
Basically: when I visit localhost:9200/search/items/_search?pretty=true&q=field-7:Diesel
It works well, however, in JSON it doesn't.
I've been googling all day and couldn't find any help in ElasticSeach documents. What frustrates me even more is that some other fields in bool query work OK, but this one doesn't.
I don't have any mapping and ES works for me out of the box - querying on the "name" field works well, as well as any other field, as well as for this field too - but only inside browser.
I realise that querying ES over browser uses so called "query string query".
Anyway, here is an example JSON that I'm posting to ElasticSearch.
(searching all items that have "golf mk5" in their name, which have diesel fuel type - by searching field-7).
{
"query": {
"filtered": {
"filter": {
"bool": {
"must_not": [
{
"term": {
"sold": "1"
}
},
{
"term": {
"user_id": "0"
}
}
],
"must": [
{
"term": {
"locked": "0"
}
},
{
"term": {
"removed": "0"
}
},
{
"terms": {
"field-7": [
"Diesel"
]
}
}
]
}
},
"query": {
"match": {
"name": {
"operator": "and",
"query": "+golf +Mk5"
}
}
}
}
},
"sort": [
{
"ordering": {
"price": "desc"
}
}
],
"from": 0,
"size": 24,
"facets": {
"category_count": {
"terms": {
"field": "category_id",
"size": 20,
"order": "count"
}
},
"price": {
"statistical": {
"field": "price"
}
}
}
}
Using a query_string-query, the text is analyzed. With the term-query (and -filter), it is not.
Since you're not specifying a mapping, you'll get the standard-analyzer for string fields. It tokenizes, lowercases and removes stopwords.
Thus, the term Diesel will be indexed as diesel. Your terms-filter is looking up the exact term Diesel, which is different.

Categories