How to update, get and delete sync gateway document using Guzzle php

Hi, I created document using guzzle. I try to delete a document. but i am getting error “Document exists”. How to get document using guzzle php?

this is my php code

public function saveCategory($params = array()){  
  $required_params = array('cat_name','cat_color','sync-session');
  if(0!=count(array_diff($required_params,array_keys($params)))){
    App::abort(500, 'Invalid Parameters!');
  }
  $document_id =$this->docId('category');
  $data=['cat_id'=>$this->docId('category'),
          'cat_color'=>$params['cat_color'],
          'cat_name'=>$params['cat_name'],
          'type'=>'category'           
        ];
  $cookieJar = CookieJar::fromArray(['SyncGatewaySession' => $params['sync-session']],'localhost');
  $client = new \GuzzleHttp\Client ([
                        'cookies' => $cookieJar,
                        'allow_redirects' => false,
                        'debug' => false
                        ]);
  $response = $client->put($this->db_url."/".$document_id,['body'=>json_encode($data)]);    
  return $response;
}


public function editCategory($params = array()){
  $required_params = array('id','rev_id','cat_id','sync-session','cat_color','cat_name');
  if(0!=count(array_diff($required_params,array_keys($params)))){
    App::abort(500, 'Invalid Parameters!');
  }
  $document_id = $params['id'];
  $rev_id = $params['rev_id'];
  $data=['cat_id'=>$params['cat_id'],
          'cat_color'=>$params['cat_color'],
          'cat_name'=>$params['cat_name'],
          'type'=>'category'
        ];
  $cookieJar = CookieJar::fromArray(['SyncGatewaySession' => $params['sync-session']],'localhost');
  $client = new \GuzzleHttp\Client ([
                        'cookies' => $cookieJar,
                        'allow_redirects' => false,
                        'debug' => false
                        ]);
 $response = $client->put($this->db_url."/".$document_id."?rev=".$rev_id,['body'=>json_encode($data)]);
 return $response;
}




public function deleteCategory($document_id){    
    $client = new \GuzzleHttp\Client ([
                        'allow_redirects' => false,
                        'debug' => false
                        ]);
  $response = $client->delete($this->db_url."/".$document_id);
  return $response;
}

I executed the test case by commad line -(vendor\bin\phpunit)
Test case

public function deleteCatergory(){ 
  $service = new UserService;         
  $result = $service->deleteCategory('category_0274b86e-365b-b52e-ec45-9f4ea715b362');        
  $this->assertTrue(TRUE); 
}

I am using

  • PHP 7.1.9
  • Sync gateway 1.5.1
  • CBS 5.0
  • Laraval 5.5.13

can anyone help to me?
Thank q

You are missing the rev_id param in your delete request

The API is documented here

More generally, to familiarize yourself with the Sync Gateway API, I would recommend using the postman collection to try out/ test the Sync Gateway API. GitHub - couchbaselabs/Couchbase-Sync-Gateway-Postman-Collection: Postman Collections for Sync Gateway 3.0 REST Interface

1 Like

I corrected my code like this

public function deleteCategory($document_id,$rev_id){
   $client = new \GuzzleHttp\Client ([
                          'allow_redirects' => false,
                          'debug' => false
                          ]);
    $response = $client->delete($this->db_url."/".$document_id."?rev=".$rev_id);
    return $response;
}

i was try with curl also.

curl -X DELETE "http://localhost:4985/cbapos/category_0274b86e-365b-b52e-ec45-9f4ea715b362?rev=5-9807ac4ad159e81afce3be6362d6d821" -H "accept: application/json"

i am getting error like this

"error : forbidden, reason : invalid document type: undefined"

What do you get when you do a GET using cURL on that doc Id ? Also, share your sync gateway config file.

It is possible that you may have some validation logic in your sync function in your config file that is prohibiting this.

This is my cURL
curl -X GET “http://localhost:4985/pos/category_0274b86e-365b-b52e-ec45-9f4ea715b362?rev=5-9807ac4ad159e81afce3be6362d6d821” -H “accept: application/json”

i am getting doc_id “category_0274b86e-365b-b52e-ec45-9f4ea715b362”.

This is my sync gateway config file :
{
“adminInterface”: “127.0.0.1:4985”,
“interface”: “0.0.0.0:4984”,
“log”: ["*"],
“databases”: {
“pos”: {
“server”: “http://admin:test1234@127.0.0.1:8091”,
“bucket”: “todo”,
“users”: {
“user1”: {“password”: “pass”, “admin_channels”: [“user1”]},
“user2”: {“password”: “pass”, “admin_channels”: [“user2”]},
“mod”: {“password”: “pass”, “admin_roles”: [“moderator”]},
“admin”: {“password”: “pass”, “admin_roles”: [“admin”]}
},
“roles”: {
“moderator”: {},
“admin”: {}
},
“sync”: `function(doc, oldDoc){

	if (doc.type == "category") {      
	  setChannel();
	  setAccess();

	} else if (doc.type == "item") {    
	  setChannel();
	  setAccess();
	
	}

  function setChannel() {
	var owner = getOwner();
	channel(doc.store_name);
  }

  function setAccess() {
	var owner = getOwner();
	access(owner, doc.store_name);
  }
 
  function getType() {
	return (isDelete() ? oldDoc.type : doc.type);
  }	
}`
}

}
}

what the contents of the document. Does it have a valid “type” ?
In your sync function, print out the value of type (for oldDoc and doc) in getType() method.

This is the document i am getting
{"_id":“category_0274b86e-365b-b52e-ec45-9f4ea715b362”,"_rev":“5-9807ac4ad159e81afce3be6362d6d821”,“cat_color”:2,“cat_id”:“category_56a78f29-5b0c-fe19-8b41-3f7641ec20ab”,“cat_name”:“category_001”,“owner”:“xyz”,“store_name”:“abc”,“type”:“category”}

cURL
curl -X GET “http://localhost:4985/pos/category_0274b86e-365b-b52e-ec45-9f4ea715b362?rev=5-9807ac4ad159e81afce3be6362d6d821” -H “accept: application/json”

this is my updated config file
{
“adminInterface”: “127.0.0.1:4985”,
“interface”: “0.0.0.0:4984”,
“log”: ["*"],
“databases”: {
“pos”: {
“server”: “http://admin:test1234@127.0.0.1:8091”,
“bucket”: “todo”,
“users”: {
“user1”: {“password”: “pass”, “admin_channels”: [“user1”]},
“user2”: {“password”: “pass”, “admin_channels”: [“user2”]},
“mod”: {“password”: “pass”, “admin_roles”: [“moderator”]},
“admin”: {“password”: “pass”, “admin_roles”: [“admin”]}
},
“roles”: {
“moderator”: {},
“admin”: {}
},
“sync”: `function(doc, oldDoc){

	if (doc.type == "category") {      
	  setChannel();
	  setAccess();

	} else if (doc.type == "item") {    
	  setChannel();
	  setAccess();
	
	}else if (doc.type == "discount") {    
	  setChannel();
	  setAccess();
	
	}else{
	  log("Invalid document type: " + doc.type);
	  throw({forbidden: "Invalid document type: " + doc.type});
	}
  function hasPrefix(value, prefix) {
	if (value && prefix) {
	  return value.substring(0, prefix.length) == prefix
	} else {
	  return false
	}
  }
  function setChannel() {
	var owner = getOwner();
	channel(doc.store_name);
  }

  function setAccess() {
	var owner = getOwner();
	access(owner, doc.store_name);
  }

  function isCreate() {
	// Checking false for the Admin UI to work
	return ((oldDoc == false) || (oldDoc == null || oldDoc._deleted) && !isDelete());
  }

  function getType() {
	return (isDelete() ? oldDoc.type : doc.type);
  }

  function isDelete() {
	return (doc._deleted == true);
  }

  function getOwner(){
	return doc._deleted ? oldDoc.owner : doc.owner;
  }
}`
}

}
}

when i try to delete document using cURL, i am getting error .
cURL code
curl -X DELETE “http://localhost:4985/pos/category_1c28f3e4-079c-9eb1-b97e-05b91fc346a2?rev=1-67650cd0b5e07e05a23876c04430e0da” -H “accept: application/json”

error
"error" : “conflict”, “reason”:“document exists”

how can i solve this issue.

You mentioned a different problem earlier of getting a “Forbidden error”
…and now you see a conflict.

So let me address the two separately because they are unrelated issues,

  • Conflict : The reason you are seeing this is because you are attempting to delete (or update) a document with a rev Id that has already been deleted (“tombstoned”). So the rev Id that you are specifying is not the latest one …It is the parent or ancestor of the revision that’s already deleted .

For instance, looking at your calls, the latest revId of document is “5-9807ac4ad159e81afce3be6362d6d821” as reported by your GET. You should be specifying that in your “rev” parameter and not "rev=1-67650cd0b5e07e05a23876c04430e0da” which is deleted.

Please spend few moments familiarizing with the Sync Gateway APIs (I had shared the link earlier) - The docs explains what the revId should be. Also, if you are unfamiliar with revision trees and conflicts, please take a look at this blog post .

  • Forbidden : The reason you are getting the Forbidden error is because your sync function is trying to fetch the doc properties (like “type”) even when it’s deleted - when a document is deleted, there isn’t anything in the document body to process.

So ensure that you first check to see if doc is deleted and then do relevant processing

For example, something like this …

 if (!isDelete()) {
 // process the document as needed
}

function isDelete() {
    return (doc._deleted == true);
  }

Thank you priya.rajagopal. it is working fine :slight_smile: