Jump to content

GraphQL for ProcessWire


dadish

Recommended Posts

On 7/8/2021 at 1:24 PM, Tom. said:

I have corrected my cors headers so it doesn't return an error, but it's still not working. Have you had any success having the login work cross-origin? I imagine so as this is a pretty common use case for use an API cross-origin. 

Here is the CORS setup that works for me.

<?php

// https://github.com/dadish/ProcessGraphQL/blob/622c9db61cb7cf3ef998edb31e4e0e47b3c96669/test/server.php#L20-L43

function cors() {
  // Allow from any origin
  if (isset($_SERVER['HTTP_ORIGIN'])) {
      // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
      // you want to allow, and if so:
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

  // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          // may also be using PUT, PATCH, HEAD etc
          header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
      exit(0);
    }
}

Could you try it and let me know if it solves your problem with different domains?

Link to comment
Share on other sites

On 7/10/2021 at 9:56 PM, dadish said:

Here is the CORS setup that works for me.

<?php

// https://github.com/dadish/ProcessGraphQL/blob/622c9db61cb7cf3ef998edb31e4e0e47b3c96669/test/server.php#L20-L43

function cors() {
  // Allow from any origin
  if (isset($_SERVER['HTTP_ORIGIN'])) {
      // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
      // you want to allow, and if so:
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

  // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          // may also be using PUT, PATCH, HEAD etc
          header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
      exit(0);
    }
}

Could you try it and let me know if it solves your problem with different domains?

Didn't work for me, maybe it's an issue with Fetch API. What do you use to make your HTTP requests? 

 

EDIT: 
Better still, could you provide me with example code where you have CORs working through JavaScript requests? That would be super helpful as I've tried so many different things and really struggling with this. 

I do a request to login, but after that any other request is logged out. Are you meant to include the login request with every request? I'm struggling to understand the "cookie being include with every future request" as that part just doesn't seem to be happening for me. 

@dadish

Link to comment
Share on other sites

42 minutes ago, Tom. said:

Shameless Bump ?

No problem. Sorry for not answering sooner.

On 7/16/2021 at 6:39 PM, Tom. said:

Didn't work for me, maybe it's an issue with Fetch API. What do you use to make your HTTP requests? 

I used fetch api. Just like you.

On 7/16/2021 at 6:39 PM, Tom. said:

Better still, could you provide me with example code where you have CORs working through JavaScript requests?

Sure. I created a sample app with create-react-app. Then I start the app with `npm start`. And here is my App.js file.

const query = async (query) => {
  const res = await fetch("https://skyscrapers.nurgulyashyrov.com/graphql/", {
    method: "POST",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({ query }),
  });
  const json = await res.json();

  console.log("json", json);
};

const execute = async () => {
  await query(`{ logout { statusCode }}`);
  await query(`{ me { name }}`);
  await query(`{ login(name: "name", pass: "pass") { statusCode } }`);
  await query(`{ me { name }}`);
};

execute();

function App() {
  return null;
}

export default App;

Note that the app starts a server that runs on http://localhost:3000. If you are testing by simply opening a file in the browser then it will probably not work. So you need your browser address bar to start with http(s):// and not with file:///

EDIT: You will have to substitute the url with your own, of course. The graphql api is setup exactly as in my previous post. I assume you noticed that the CORS headers are inside the cors() function and that you have to call that function before final response.

  • Like 1
Link to comment
Share on other sites

On 7/22/2021 at 10:47 AM, dadish said:

No problem. Sorry for not answering sooner.

I used fetch api. Just like you.

Sure. I created a sample app with create-react-app. Then I start the app with `npm start`. And here is my App.js file.

const query = async (query) => {
  const res = await fetch("https://skyscrapers.nurgulyashyrov.com/graphql/", {
    method: "POST",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({ query }),
  });
  const json = await res.json();

  console.log("json", json);
};

const execute = async () => {
  await query(`{ logout { statusCode }}`);
  await query(`{ me { name }}`);
  await query(`{ login(name: "name", pass: "pass") { statusCode } }`);
  await query(`{ me { name }}`);
};

execute();

function App() {
  return null;
}

export default App;

Note that the app starts a server that runs on http://localhost:3000. If you are testing by simply opening a file in the browser then it will probably not work. So you need your browser address bar to start with http(s):// and not with file:///

EDIT: You will have to substitute the url with your own, of course. The graphql api is setup exactly as in my previous post. I assume you noticed that the CORS headers are inside the cors() function and that you have to call that function before final response.

Interesting, this is the exact same implementation that I'm using however it's not keeping the cookie. May I ask if you are using Node JS server? I believe this may be the reason it's not working as mine is apache with vanilla JavaScript. I could prefix any call I need to be authenticated with the login query, my only concern is that would require using localStorage to keep a session alive but it isn't secure to store the login password. 

Have you had any success using vanilla JavaScript running on Apache @dadish

 

Link to comment
Share on other sites

Hi guys!

I really like this Module so far. One thing bothers me though:
the returned data from GraphQL is kinda "messy", e.g. if i have only one element returned from a list operation,
I don't want it to be returned as an array holding one element, but instead just return the one object instead.

I've written a quick and dirty JS function, which transforms the data I receive into the format described above.

transformGqlResponse (response, pagename) {
  const data = response.data[pagename]
  const content = data.list[0]

  for (const item in content) {
    if (Object.prototype.hasOwnProperty.call(content[item], 'list')) {
      content[item] = content[item].list[0]
    }
  }

  return content
}

Obviously this poses a problem for deeply nested list operations.

Is there a way to transform the data like that before it is returned to my frontend, like make the list operation return the object instead of an array when the list operation result only yields one item?

 

Also first post, LOL.

Link to comment
Share on other sites

  • 4 weeks later...

Hi Guys,

i want to get a hooked page property into my graphql schema. Does anybody know how i can configure/implement this?

/* the examble from https://processwire.com/docs/modules/hooks/#how-can-i-add-a-new-property-via-a-hook */
wire()->addHookProperty('Page::intro', function($event) {
  $page = $event->object;
  $intro = substr(strip_tags($page->body), 0, 255);
  $lastPeriodPos = strrpos($intro, '.');
  if($lastPeriod !== false) $intro = substr($intro, 0, $lastPeriodPos);
  $event->return = $intro;
});

I am playing around with the getQueryFields-Hook but I don't know what to do next:

wire()->addHookAfter('ProcessGraphQL::getQueryFields', function ($event) {

	$types = $event->return;
	foreach($types as $type) {
		if($type['name'] === 'mytype') {
			/** @var ObjectType $pageType */
			$pageType = $type['type']->getField('list')->getType()->getOfType();
			$fields = $pageType->getFields();
			
			// ????
			// and here i will add some fields
		}
	}

	$event->return = $types;
});

 

Link to comment
Share on other sites

11 hours ago, Neue Rituale said:

Hi Guys,

i want to get a hooked page property into my graphql schema. Does anybody know how i can configure/implement this?

Haven't tried it, but something like this should work. https://webonyx.github.io/graphql-php/getting-started/ Scroll down to the first example and see how fields are defined in GraphQL.

In your case it should look similar to this.

<?php

$fields[] = [
  'name' => 'intro',
  'type' => Type::string(),
  'resolve' => function ($page) {
    return $page->intro;
  }
];

Play around with it and you'll get there.

  • Like 1
Link to comment
Share on other sites

5 hours ago, Tom. said:

May I ask if you are using Node JS server? I believe this may be the reason it's not working as mine is apache with vanilla JavaScript.

Hey Tom. What do you mean "using Node JS server?" Do you mean where the JavaScript files coming from? If that's your question, then it should not matter. It does not matter where the javascript files are coming from.

I did a little research and found out that it works in Firefox but not in Chrome. I don't use Chrome, that's why I couldn't reproduce your issue. Have you tried the above JS code in Firefox? If not please try it out and tell me the results. If that works then we will work on fixing it for the Chrome browser.

 

  • Like 3
Link to comment
Share on other sites

On 7/25/2021 at 11:30 PM, zynth said:

Is there a way to transform the data like that before it is returned to my frontend, like make the list operation return the object instead of an array when the list operation result only yields one item?

You can do it manually on the ProcessWire side. Before returning the result to the client, simply do the JS trick that you posted in PHP and return the result to the client.

  • Like 2
Link to comment
Share on other sites

14 hours ago, dadish said:

Hey Tom. What do you mean "using Node JS server?" Do you mean where the JavaScript files coming from? If that's your question, then it should not matter. It does not matter where the javascript files are coming from.

I did a little research and found out that it works in Firefox but not in Chrome. I don't use Chrome, that's why I couldn't reproduce your issue. Have you tried the above JS code in Firefox? If not please try it out and tell me the results. If that works then we will work on fixing it for the Chrome browser.

 

Hi @dadish,

That may explain a lot, Chrome has very strict rules when it comes to CORS. I have been looking at different systems such as Strapi which is designed to be Headless and that uses this method:

image.png.c090ea0d2922d481c2a4e3069df8d212.png

So it returns an Authorization code that could be stored in Local Storage then passed into future requests using the Authorization header. This could be implemented into ProcessWire with a custom field on the User page for jwt and generating a key if a successful login was made and returning it to the user. graphql.php could then check if the authorization header has been passed and if it finds a matching jwt code - force log them in before processing the query. 

Seems really simple to implement. I'm unsure whether it's worth shipping with that functionality or have people build it in? What do you think @dadish?
 

Link to comment
Share on other sites

4 minutes ago, Tom. said:

Seems really simple to implement. I'm unsure whether it's worth shipping with that functionality or have people build it in? What do you think @dadish?

I would prefer people implement their own authenticaton/session flow. The thing you describe above should be simple to implement with the ProcessGraphQL::getMutationFields hook. I think I will remove the login(name: "name", pass: "pass") query field in the future and add a clear documentation/example on how you could implement your own authentication flow.

Thanks a lot for the idea @Tom.. I think it would be more flexible this way.

Link to comment
Share on other sites

1 hour ago, dadish said:

I think I will remove the login(name: "name", pass: "pass") query field in the future and add a clear documentation/example on how you could implement your own authentication flow.

Interesting, what would you do that for? I would be more than happy to implement the authentication flow above and ship with it? That would suit most peoples needs. It would make it more feature rich out of the box.

Link to comment
Share on other sites

2 minutes ago, Tom. said:

That would suit most peoples needs. It would make it more feature rich out of the box.

Or in other words, it would force people to use a predefined method of authentication, instead of allowing them to use their own preferred version. Some people may prefer JWT tokens, others might want cookie based auth or maybe people need to use third party authentication like AWS Incognito..., the list goes on.

Link to comment
Share on other sites

3 hours ago, dadish said:

Some people may prefer JWT tokens, others might want cookie based auth

Hi @dadish

Would it be okay if you PM you regarding this? I would like to create a module to enable JWT auth. I have it working by modifying the source code but I would like to create it as a module so others can use it easily and I also don't want to miss out on any bug fixes or updates as I've modified the module.

 

Link to comment
Share on other sites

  • 2 months later...
3 hours ago, dadish said:

Hi @Tom.. I am trying to figure out what is EntryCreateInput type. Looks like you're extending graphql module somehow. If you can tell me more about that input type, I might be able to figure out the problem.

It's just a default text field with the HTML Entity Encoder enabled. 

Link to comment
Share on other sites

5 hours ago, Tom. said:

It's just a default text field with the HTML Entity Encoder enabled. 

Whatever it is, I suspect it's causing problems. Try changing the field type for job_title to another field that ProcessGraphQL module supports and see if the error is gone. Then, if it is possible you can share your custom field in github and I can take a look at it.

Link to comment
Share on other sites

  • 1 month later...
{"errors":[{"message":"Syntax Error: Unexpected \u003CEOF\u003E","extensions":{"category":"graphql"},"locations":[{"line":1,"column":1}]}]}

I'm getting this error for the GraphQl page for domain.com/subfolder/graphql/
GraphiQl (domain.com/subfolder/graphiql/) is working fine. Also domain.com/subfolder/processwire/setup/graphql/

I assume this has something to do with my pw-installation inside a subfolder?
I already saw that hint with the slash and also tried this in my graphql-template

<?php namespace ProcessWire;

header('Content-Type: application/json');
$ProcessGraphQL = $modules->get('ProcessGraphQL');
$ProcessGraphQL->GraphQLServerUrl = '/subfolder/graphql/';
echo json_encode($ProcessGraphQL->executeGraphQL(), true);

In my htaccess i have
RewriteBase /subfolder/

and in my config file I still have
$config->httpHosts = array('domain.com', 'www.domain.com');

Link to comment
Share on other sites

Hi @ngrmm. I suggest you to start debugging the request from your template. Depending on how you are sending the request, first try to simply echo it. In your template, simply echo back the graphql request. Could look something like this.

<?php

echo $input->post('query');

// Or:
// echo $_POST['query']

// Or:
// $rawBody     = file_get_contents('php://input');
// $requestData = json_decode($rawBody ?: '', true);
// echo $requestData['query']

And see if your PW installation correctly receives the graphql request. You can look at how GraphQL module makes different attempts to capture the request itself here. https://github.com/dadish/ProcessGraphQL/blob/530a72e349d7a262d26af9452f5681fa36ee5d33/ProcessGraphQL.module#L161-L183

When you find out a proper way to capture a request in your template file, you can manually pass the request to the Graphql module. Something like below

<?php
     
$query = $input->post('query');
$variables = $input->post('variables');

echo json_encode($modules->get('ProcessGraphQL')->executeGraphQL($query, $variables), true);

Let me know if this helps.

Link to comment
Share on other sites

  • 2 weeks later...
On 12/21/2021 at 6:26 AM, dadish said:

Hi @ngrmm. I suggest you to start debugging the request from your template. Depending on how you are sending the request, first try to simply echo it. In your template, simply echo back the graphql request. Could look something like this.

<?php

echo $input->post('query');

// Or:
// echo $_POST['query']

// Or:
// $rawBody     = file_get_contents('php://input');
// $requestData = json_decode($rawBody ?: '', true);
// echo $requestData['query']

@dadish I tried the above code
 

<?php namespace ProcessWire;

echo $_POST['query'];

and I'm getting this error in TracyDebugger

PHP Notice: Undefined index: query in .../httpdocs/xxxxxxxxxxx/site/templates/graphql.php:3

My graphi template has the forward slash activated.
Just to understand this, is it right that I first configure the output with the GraphiQL-tool. And this output is then shown on /graphql/ as json?

 

UPDATE: seems it has something to do with my site-settings
I tried it in JS and it works
However when I use /graphql/ as URL i see an object in the console. When I use /processwire/setup/graphql/ I see a json in the console
 

	$.post(
		'/graphql/',
		{
			query: "{ eventsArticle { list { id  } } }"
		},
		function (res) {
			console.log(res);
		}
	);

 

Link to comment
Share on other sites

  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...