Commit 6d9e20da authored by aaa's avatar aaa

180312d - 1.fixed POST fwd , 2. Using my own guzzlehttp class

parent 9b688a72
......@@ -10,7 +10,7 @@ Note : for relay_headers to work you need the modified guzzlerestgenerator modul
At this point you must manually enable guzzlenode_user_api_access and guzzlenode_role_api_access FIELDS from
http://mydrupalsite/admin/structure/types/manage/guzzle_rest/form-display
###Access rights:
### Access rights:
This is a general permission to be able to access ALL guzzlenodes/external APIs (but not use them - you will need to specify usernames/roles inside EACH guzzlenode). Note 1: this ENABLES/DISABLES everything for everyone.So, you MUST have this permission in order to do anything. Note 2: From "RESTful Web Services" you can further control access to Drupal GET,POST,PATCH REST points. The final check is done when you check if the current USERNAME is declared in the specific guzzlenode
- Give permissions /admin/people/permissions to Drupal REST -> from here allow GET,POST,PATCH REST access to this drupal guzzlenode
......@@ -47,15 +47,39 @@ this will relay/forward your request as :
## Usage external-client-side #2:
###Parameters :
-
-
-
##To Do:
### Forward POST
If you POST to the
**http://mydrupal.com/api/relay/post/3**
and you have POST/Payload body forward enabled then, the body you have post will be forwarded to the external API call.
### Forward Headers
If you have enabled this :
If you post a header named
**authorisation2:...**
then it will be forwarded as a standard
**authorisation:..**
header to the external API
### Args :
**http://mydrupal.com/api/relay/getalbums?_format=json&arg[2]=world&arg[1]=hello**
will send to the external API a request like
**http://myexternalserver/hello/world**
At this point we accept up to 5 args : arg[1]...arg[5].
### Parameters :
Pass parameters to External API url
eg
**http://mydrupal.com/api/relay/3?_format=json&param_name[1]=hello&param_value[1]=55555555&param_name[2]=world&param_value[2]=44444**
Will produce :
**http://myexternalserver?hello=55555555&world=44444**
At this point we accept up to 5 params : param_name[1],param_value[1]...param_name[5],param_value[5]
## To Do:
- Allow FIXED payload to accept variables from drupal rest call API point
- replace use Drupal\guzzlerestgenerator\Http\GuzzleDrupalHttp with a local one
- Implement POST
- Implement PUT
- Implement access per SPECIFIC guzzle_node (per role or user)
......
......@@ -11,29 +11,30 @@ use Drupal\Core\Routing\RouteMatchInterface;
* Implements hook_rest_entity_form_alter(). ENABLE the 2 new guzzlenode fields
*/
function d8_guzzlenode_rest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
//ENABLE all our custom fileds.(we do that because this module add the fields to an already existing form -so /config/install/optional will NOT work)
$fields_to_enable=array('field_guzzlenode_user_api_access',
'field_guzzlenode_role_api_access',
'field_guzzlenode_call_limit',
'field_gnode_allow_arg_fwd',
'field_gnode_allow_head_fwd',
'field_gnode_allow_param_fwd',
'field_gnode_allow_payload_fwd'
);
foreach ($fields_to_enable as $field) {
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent($field
/*, [
//'type' => 'string',
'label' => 'above',
//'settings' => ['link_to_entity' => 'false'],
]
*/
)->save();
}//END of foreach ($fields_to_enable as $field) {
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent('field_guzzlenode_user_api_access'
/* , [
'type' => 'string',
'label' => 'above',
'settings' => ['link_to_entity' => 'false'],
]*/
)->save();
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent('field_guzzlenode_role_api_access'
/* , [
'type' => 'string',
'label' => 'above',
'settings' => ['link_to_entity' => 'false'],
]*/
)->save();
// \Drupal::logger('DEBUG d8_guzzlenode_rest')->notice("jon CUSTOM entity_form_display "); //DEBUG
} // END of function d8_guzzlenode_rest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
......
<?php
namespace Drupal\d8_guzzlenode_rest\Http;
use GuzzleHttp\Client;
use GuzzleHttp;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Get a response code from any URL using Guzzle in Drupal 8!
*
* Usage:
* In the head of your document:
*
* use Drupal\guzzle_rest\Http\GuzzleDrupalHttp;
*
* In the area you want to return the result, using any URL for $url:
*
* $check = new GuzzleDrupalHttp();
* $response = $check->performRequest($requestUrl, $requestMethod, $requestHeaders, $requestPayloadData);
*
**/
class GuzzleDrupalHttp {
use StringTranslationTrait;
public function performRequest($requestUrl, $requestMethod = 'GET', $requestHeaders = '', $requestPayloadData = '') {
$client = new \GuzzleHttp\Client();
try {
// Massage $requestHeaders to generate $headers array, ready for REST call
$requestHeaders = preg_replace(array('/\n/', '/\r/'), '#PH#', $requestHeaders);
//foreach(explode("\r\n", $requestHeaders) as $row) {
foreach(explode('#PH#', $requestHeaders) as $row) {
$matches= explode(':', $row);
if($matches[0]!=null) $headers[$matches[0]] = $matches[1]; //jon 180222a
/*
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$headers[$matches[0]] = $matches[1];
} */
// if($matches[0]!=null) \Drupal::logger('HEADERS got ')->notice("$matches[0]=$matches[1] ,AAAAAAAAAAAA row=$row , requestHeaders=$requestHeaders");
}
if($requestPayloadData != ''){
$body=$requestPayloadData;
// Massage $requestPayloadData to generate $body array, ready for REST call
/* ORIGINAL code
foreach(explode("\r\n", $requestPayloadData) as $row) {
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$body[$matches[1]] = $matches[2];
}
}
*/ //END of ORIGINAL code
}else{
$body = '';
}
switch($requestMethod){
case "GET":
$res = $client->get($requestUrl, [
'http_errors' => false,
'headers' => $headers
]);
break;
case "POST":
\Drupal::logger('d8_guzzlenode_rest')->notice("OWN GuzzleDrupalHttp requestPayloadData=$requestPayloadData ||| res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
// NOTE *** $body must be a VALID be a JSON string
//NOTE *** REMOVE $body PARSING FROM above **
// SAMPLE CODE that accepts : "userId": '9',"title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint"
$string = $body; //"business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";
///$string = str_replace(array("\n", "\r" , '"',"'"), '', $body); //remove \n \r and "
// $string = str_replace(array("\n", "\r" ), '', $body); //remove \n \r and " ?????????? Maybe remove this
$finalArray=json_decode($string,true);
$res = $client->request('POST', $requestUrl,['json' => $finalArray ,'headers' => $headers ]); //OK Works
\Drupal::logger('CASE POST 444')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
/* //ORIGINAL LINE 'body' json deprecated
$res = $client->post($requestUrl, [
'http_errors' => false,
'headers' => $headers,
//'body' => $body
] //,[ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']]
);
*/
break;
case 'PUT':
$res = $client->put($requestUrl, [
'http_errors' => false,
'headers' => $headers,
'body' => $body
]);
break;
default:
throw new Exception('Invalid Request Method');
}
return($res);
} catch (RequestException $e) {
return($this->t('Error'));
}
}
}
\ No newline at end of file
<?php
namespace Drupal\guzzlerestgenerator\Http;
use GuzzleHttp\Client;
use GuzzleHttp;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Get a response code from any URL using Guzzle in Drupal 8!
*
* Usage:
* In the head of your document:
*
* use Drupal\guzzle_rest\Http\GuzzleDrupalHttp;
*
* In the area you want to return the result, using any URL for $url:
*
* $check = new GuzzleDrupalHttp();
* $response = $check->performRequest($requestUrl, $requestMethod, $requestHeaders, $requestPayloadData);
*
**/
class GuzzleDrupalHttp {
use StringTranslationTrait;
public function performRequest($requestUrl, $requestMethod = 'GET', $requestHeaders = '', $requestPayloadData = '') {
$client = new \GuzzleHttp\Client();
try {
// Massage $requestHeaders to generate $headers array, ready for REST call
$requestHeaders = preg_replace(array('/\n/', '/\r/'), '#PH#', $requestHeaders);
//foreach(explode("\r\n", $requestHeaders) as $row) {
foreach(explode('#PH#', $requestHeaders) as $row) {
$matches= explode(':', $row);
if($matches[0]!=null) $headers[$matches[0]] = $matches[1]; //jon 180222a
/*
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$headers[$matches[0]] = $matches[1];
} */
// if($matches[0]!=null) \Drupal::logger('HEADERS got ')->notice("$matches[0]=$matches[1] ,AAAAAAAAAAAA row=$row , requestHeaders=$requestHeaders");
}
if($requestPayloadData != ''){
$body=$requestPayloadData;
// Massage $requestPayloadData to generate $body array, ready for REST call
/* ORIGINAL code
foreach(explode("\r\n", $requestPayloadData) as $row) {
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$body[$matches[1]] = $matches[2];
}
}
*/ //END of ORIGINAL code
}else{
$body = '';
}
//\Drupal::logger('GUZRESTGEN-ORIG before switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
//if ($requestMethod=='POST') \Drupal::logger('GUZRESTGEN-ORIG POSTTTTT')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
switch($requestMethod){
case "GET":
//\Drupal::logger('CASE GET')->notice("res".json_decode($res,true) ."||| requestPayloadData=$requestPayloadData ||||||||| requestMethod=$requestMethod");
$res = $client->get($requestUrl, [
'http_errors' => false,
'headers' => $headers
]);
break;
case "POST":
//\Drupal::logger('GUZRESTGEN-ORIG POSTTTTT22222')->notice("requestPayloadData=$requestPayloadData ||| res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
//$res = $client->request('POST', $requestUrl, ['json' => ['foo' => 'bar']]); //ok works
// NOTE *** $body must be a VALID be a JSON string
// RELAY JSON from $body { "userId": "9", "title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint", "id": 101 } //THIS IS VALID JSON
//$res = $client->request('POST', $requestUrl, [ 'json' => ["userId"=> '9', "title"=> "AAAAAAAAAAtitle", "body"=> "AAAAAAAAAAAAABODY aliquidmagnam sint"] ]); //ΟΚ Works 100%
//NOTE *** REMOVE $body PARSING FROM above **
// SAMPLE CODE that accepts : "userId": '9',"title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint"
$string = $body; //"business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";
///$string = str_replace(array("\n", "\r" , '"',"'"), '', $body); //remove \n \r and "
// $string = str_replace(array("\n", "\r" ), '', $body); //remove \n \r and " ?????????? Maybe remove this
/*$string='
{
"type":[{"target_id":"article",
"target_type": "node_type",
"target_uuid": "ff9b4624-1224-49f6-be47-d19a22664f8e"
}],
"title":[{"value":"Hello World222222222"}],
"body":[{"value":"How are you?222222222"}]
}
' ; */
$finalArray=json_decode($string,true);
// \Drupal::logger('GUZRESTGEN-ORIG POSTTTTT22222 bbb ')->notice("res=".json_encode($body,true) ." ||||||||| requestUrl=$requestUrl |||| requestMethod=$requestMethod");
//$response = $check->performRequest($requestUrl, 'POST', $requestHeaders, $requestPayloadData);
//$response = $client->request('POST', $requestUrl, ['json' => $finalArray ,'headers' => $headers ]);
// \Drupal::logger('CASE POST 3333')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
$res = $client->request('POST', $requestUrl,['json' => $finalArray ,'headers' => $headers ]); //OK Works
\Drupal::logger('CASE POST 444')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
/* //ORIGINAL LINE 'body' json deprecated
$res = $client->post($requestUrl, [
'http_errors' => false,
'headers' => $headers,
//'body' => $body
] //,[ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']]
);
*/
break;
case 'PUT':
$res = $client->put($requestUrl, [
'http_errors' => false,
'headers' => $headers,
'body' => $body
]);
break;
default:
throw new Exception('Invalid Request Method');
\Drupal::logger('GUZRESTGEN-ORIG DEFAULT switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
}
\Drupal::logger('GUZRESTGEN-ORIG AFTER switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
return($res);
} catch (RequestException $e) {
return($this->t('Error'));
}
}
}
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment