Jump to content

GraphQL for ProcessWire


dadish

Recommended Posts

Hi there,

I could use some help. I'm trying to run the module on a multilanguage installation.
The tip with the / does not help me.
Here is the page:
https://pwtestsite.000webhostapp.com/graphiql/

Do you have any idea what it could be?
Could it be the multilanguage context?
I'm from Germany and the default language is English - by the way, if who knows if you can change the default language, I would be very grateful. So, when I enter the url, it will be supplemented by a "/en/" in the browser.

Thanks a lot in advance.

Best regards

Link to comment
Share on other sites

7 hours ago, SlackMcKracken said:

I could use some help. I'm trying to run the module on a multilanguage installation.

You need to use the language field. In your graphql endpoint there is a language field. So it will look like

{
  language(name:"<language_name_here>")
  test {
    list {
      testtext
    }
  }
}

 

  • Like 1
Link to comment
Share on other sites

  • 3 weeks later...
On 6/23/2020 at 8:20 PM, pmichaelis said:

I don't know if there have been any requests, but is ist possible to make the module work with "Repeater Matrix Fieldtypes"?

You can add support for Repeater Matrix Fieldtypes via custom third-party modules. Refer to documentation on how you can create one. https://github.com/dadish/ProcessGraphQL#third-party-fieldtypes-support

  • Like 3
Link to comment
Share on other sites

  • 4 weeks later...

@sodesign Not sure if you still need this but this release brings support for interfaces that I previously talked about. Hope you'll find it helpful.

  • Like 2
Link to comment
Share on other sites

13 hours ago, dadish said:

@sodesign Not sure if you still need this but this release brings support for interfaces that I previously talked about. Hope you'll find it helpful.

That's great news, and thanks for letting me know.

I've recently been working on a nuxt.js project with Craft CMS which uses interfaces, and I'm very excited to now have this capability in PW as well.

Link to comment
Share on other sites

  • 5 months later...

I’m having problems getting the getQuery hook to execute. If I copy-paste the code from https://github.com/dadish/ProcessGraphQL#getquery-hook to graphql.php (or graphiql.php and ready.php for that matter) and just try to log something inside the function, the hook is never executed. @dadish is the documentation still up-to-date in this regard?

I’m on PW 3.0.165 and module version 1.3.0

Link to comment
Share on other sites

  • 2 weeks later...
On 1/20/2021 at 10:59 AM, charger said:

I’m having problems getting the getQuery hook to execute. If I copy-paste the code from https://github.com/dadish/ProcessGraphQL#getquery-hook to graphql.php (or graphiql.php and ready.php for that matter) and just try to log something inside the function, the hook is never executed. @dadish is the documentation still up-to-date in this regard?

I’m on PW 3.0.165 and module version 1.3.0

Here’s the updated code that works for me:

<?php namespace ProcessWire;

use GraphQL\Type\Definition\Type;

$processGraphQL = $modules->get('ProcessGraphQL');

wire()->addHookAfter('ProcessGraphQL::getQueryFields', function ($event) {
	$query = $event->return;
 	$query[] = [
		'name' => 'hello',
		'type' => Type::string(),
		'resolve' => function () {
			return 'world!';
		}
	];
	$event->return = $query;
});

echo $processGraphQL->executeGraphQL();

The hook name changed from getQuery to getQueryFields. Also, the new field is now just pushed to the array instead of using the addField() function (from the previous library). 

Link to comment
Share on other sites

  • 2 weeks later...

Hi @dadish,

I played a little bit with the module but can't get my fields into GraphQL. I only use some FieldtypeText and FieldtypeTextLanguage fields but the don't appear in the schema.

Any ideas why? I use the Insomnia client here because on the default GraphiQl I get this "Syntax Error: Unexpected <EOF>" error. 

1743748658_Bildschirmfoto2021-02-11um21_29_46.thumb.png.74e806ab7ec57b20c0aa587813c9ea96.png

992306395_Bildschirmfoto2021-02-11um21_29_24.thumb.png.37ed2931f8d8a36dc1e6404df01f168c.pngAny i

Link to comment
Share on other sites

3 minutes ago, markus_blue_tomato said:

but still not in Insomnia Client...

Make sure you have rights to see it in insomnia. You probably not authenticated in insomnia, which means you're a guest user and those fields are not configured to be accessible by the guest user. Can you check if my assumptions are correct?

Link to comment
Share on other sites

5 minutes ago, dadish said:

Make sure you have rights to see it in insomnia. You probably not authenticated in insomnia, which means you're a guest user and those fields are not configured to be accessible by the guest user. Can you check if my assumptions are correct?

Yes this was the problem. I had this option on "No". I changed it to "yes" and gave the role "guest" view-access.

Thank you! I thought the fields are vissible also to guests if this option is on "No"

image.thumb.png.f4be5dcbf4bfd9d9b211fe0dc9f3aa03.png

Link to comment
Share on other sites

Hi @dadish,

I am struggling now with Page Reference Fields. I don't get my custom Text Fields and also not title. Both of them are in legalFields and having the correct access rights.

Any ideas?

image.thumb.png.2621b5bd2b276d8ad2666e695428a2c4.png

 

If I get this running I will try to make support for $page->references support via PR 😉  https://processwire.com/api/ref/page/references/

Link to comment
Share on other sites

@markus_blue_tomato I assume job_group is a page field. Page fields in GraphQL return Page interface that has only built-in fields (id. name, url...). If you want to get custom fields like (title, job_group_id...) you need to use fragments.

{
  jobDetail {
    list {
      id
      job_name
      job_group {
        list {
          id
          name
          ... on JobGroupPage { // <== you need to use the actual type name here
            title
            job_group_id
          }
        }
      }
    }
  }
}

 

  • Thanks 1
Link to comment
Share on other sites

2 hours ago, dadish said:

@markus_blue_tomato I assume job_group is a page field. Page fields in GraphQL return Page interface that has only built-in fields (id. name, url...). If you want to get custom fields like (title, job_group_id...) you need to use fragments.


{
  jobDetail {
    list {
      id
      job_name
      job_group {
        list {
          id
          name
          ... on JobGroupPage { // <== you need to use the actual type name here
            title
            job_group_id
          }
        }
      }
    }
  }
}

 

Thanks works! 

Link to comment
Share on other sites

  • 4 months later...

This is great! Having a play with it now. I'm still getting my head around things, but I can't figure out why this isn't working:

<script>
  fetch('https://phpstack-389529-2027697.cloudwaysapps.com/graphql/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify({
      query: `{
        venue {
          list {
            title
          }
        }
      }`
    })
  })
    .then(r => r.json())
    .then(data => console.log('data returned:', data));
</script>

I have enabled CORS on the graphql.php file:

<?php namespace ProcessWire;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');

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

But I'm getting the result:

message: "Cannot query field \"venue\" on type \"Query\"."

But I can use GraphiQL to do the same query and it works as intended: 
image.thumb.png.2a91c6c7ff23f7bbc64680ccf66d37ce.png

 

What am I doing wrong here?

 

EDIT:
Figured it out, I needed to give Guest permissions to access. I was wondering how do you do the login flow through JavaScript so I can make requests that only certain users could view, I like the fact that this uses ProcessWires permission system! Very clever. 

Link to comment
Share on other sites

11 hours ago, Tom. said:

Figured it out, I needed to give Guest permissions to access. I was wondering how do you do the login flow through JavaScript so I can make requests that only certain users could view, I like the fact that this uses ProcessWires permission system! Very clever. 

Login should work as regular processwire login flow. Just do a first request as

{
	login(name: "username", pass: "password") {
    	statusCode
    }
}

Then all subsequent requests from the browser will automatically include the processwire cookies.

  • Like 1
Link to comment
Share on other sites

9 hours ago, dadish said:

Login should work as regular processwire login flow. Just do a first request as

{
	login(name: "username", pass: "password") {
    	statusCode
    }
}

Then all subsequent requests from the browser will automatically include the processwire cookies.

That's amazing, thank you. 

Also, I'm logged in as Admin (superuser) and I can't seem to use the mutation to "create" only "update" and I can't seem to find the reason why. How do I add the ability to create pages? Also is there an option to create pages but not edit them. It isn't possible with the permissions on ProcessWire, but I wouldn't want people exploiting the API and editing content, but I would like user submitted content. e.g. storing form submission data. 

Thanks,
Tom

 

EDIT:

Type in the settings part under "me":
"Adds me query field. Allows user to query her credentials."

Should be "Allows user to query their credentials." 

Link to comment
Share on other sites

1 hour ago, Tom. said:

Also, I'm logged in as Admin (superuser) and I can't seem to use the mutation to "create" only "update" and I can't seem to find the reason why. How do I add the ability to create pages?

Probably because there are some conditions that are required. One of those things is that in order for user to be able to create a page they require a `page-create` permission for the template that is going to be created, but also `page-add` permission for the template that will be a parent of the created page.

2 hours ago, Tom. said:

Also is there an option to create pages but not edit them. It isn't possible with the permissions on ProcessWire, but I wouldn't want people exploiting the API and editing content, but I would like user submitted content. e.g. storing form submission data.

You could probably achieve this by just removing some mutation fields with hooks. Should look something like below.

<?php

$wire->addHookAfter("ProcessGraphQL::getMutationFields", function (HookEvent $event) {
  $fields = $event->return;
  $newFields = [];
  foreach ($fields as $field) {
    if (!in_array($field['name'], ['updatePost', 'updateComment'] )) { // list the name of mutation fields you want to disable
      $newFields[] = $field;
    }
  }
  $event->return = $newFields;
});

Make sure this code is run before the module has responded to the query. Before $modules->get('ProcessGraphQL')->executeGraphQL()

4 hours ago, Tom. said:

"Adds me query field. Allows user to query her credentials."

Should be "Allows user to query their credentials." 

Thanks. Will update. 👍

  • Like 1
Link to comment
Share on other sites

On 7/7/2021 at 6:12 PM, dadish said:

Probably because there are some conditions that are required. One of those things is that in order for user to be able to create a page they require a `page-create` permission for the template that is going to be created, but also `page-add` permission for the template that will be a parent of the created page.

I found out the issue, I also needed to add the parent to the list of templates exposed to the GraphQL API. Thank you for your help 🙂 @dadish

I'm currently struggling now with the authentication flow. I'm using JavaScript Fetch API (https://graphql.org/graphql-js/graphql-clients/😞

  function graphQL(query) {
    const url = 'https://phpstack-389529-2027697.cloudwaysapps.com/graphql/';

    return new Promise(resolve => {
      fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ query: query })
      }).then(response => { console.log(response); resolve(response.json()); });
    });
  };

I'm then logging in, passing a query then logging out for user submission:

// Login
graphQL(`{ login(name: "api-user", pass: "api-pass123") { statusCode } }`).then(result => {
  // Submit Data
  graphQL(submitQuery).then(result => {
    // Logout
    graphQL(`{ logout { statusCode } }`);
  });
});

submitQuery is the follow:

mutation {
	createEntry(page: {
		parent: "1044",
		title: "Test",
		name: "Test",
		address: "23 Common",
		link: "",
		manager_name: "twgew gweg gwe",
		manager_email:"wgwe@gwegwe.com",
		phone: "7547037473",
		cards: "20",
		offers: { add: [{ title: "ewwfeefwfwefew" },{ title: "eerefgger" },{ title: "eregrer" },{ title: "ergeregre" }] },
        terms: "fewfewwfe"
	}){
		manager_name
	}
}

Which is returning the error:

message: "Schema is not configured for mutations."

When using GraphiQL I can get that error by not logging in first, if I login then run it it works fine. I've checked the login and it does return 200 login successful. But from what I can tell it's not actually setting any cookie or anything so the second query fails.

Do you know how to get this working @dadish

EDIT:
For now I've just done this on the graphql.php file which works, it's not ideal but I'm a tight deadline 😅

<?php namespace ProcessWire;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
header('Content-Type: application/json');


$session->login("api-user", "api-pass123");
echo json_encode($modules->get('ProcessGraphQL')->executeGraphQL(), true);
$session->logout();

EDIT 2:
Been doing some research and you have to include do the following with the fetch from what I understand:

  function graphQL(query) {
    const url = 'https://phpstack-389529-2027697.cloudwaysapps.com/graphql/';

    return new Promise(resolve => {
      fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
		credentials: 'include', // INCLUDE CREDENTIALS
        body: JSON.stringify({ query: query })
      }).then(response => { console.log(response); resolve(response.json()); });
    });
  };

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. 

Link to comment
Share on other sites

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...