Nurguly Ashyrov

GraphQL for ProcessWire

90 posts in this topic

15 minutes ago, Nurguly Ashyrov said:

Now I don't really know how to go on with this thread. Should we abandon it and start new thread in the modules section? Or maybe this thread could be moved to modules section? What @moderators think of this?

Personally I think that this thread already includes so much great content that it'd be a shame to abandon it -- not to mention that it's more than likely that folks looking for details about this module would end up here anyway.

It's your choice obviously, but if you want, I (or any other moderator here) would be more than happy to move this thread to the modules section. Just let us know when you have decided what to do with it :) 

2 people like this

Share this post


Link to post
Share on other sites
2 hours ago, teppo said:

Personally I think that this thread already includes so much great content that it'd be a shame to abandon it -- not to mention that it's more than likely that folks looking for details about this module would end up here anyway.

It's your choice obviously, but if you want, I (or any other moderator here) would be more than happy to move this thread to the modules section. Just let us know when you have decided what to do with it :) 

I agree with you on that. I think it would be best if we move this thread to modules section. So, please move it to the modules section. Then after I will update my first post of this thread a bit and add a module tag I guess :) 

3 people like this

Share this post


Link to post
Share on other sites
On 18/03/2017 at 1:29 PM, Nurguly Ashyrov said:

I agree with you on that. I think it would be best if we move this thread to modules section. So, please move it to the modules section. Then after I will update my first post of this thread a bit and add a module tag I guess :) 

Moved :)

2 people like this

Share this post


Link to post
Share on other sites

I am trying to use this module in the frontend. I added the following code:
 

<button class="graphBtn">Fetch data!</button>
<script src="<?php echo $config->urls->templates?>js/axios.js"></script>
<script>
  var $button = document.querySelector('.graphBtn');
  $button.addEventListener('click', function (e) {
    e.preventDefault();
    axios.post('/graphql/', {
      query: `
      {
        basic_page{
          list{
            title,
            summary,
            url
          }
        }
      }
      `
    })
      .then(response => {
        console.log(response.data);
      });
  });
</script>

And this is what I get back:

{
  "errors": [ { "message": "Must provide an operation." } ]
}

Do you know why? If I try the query in the GraphiQl admin I get the right data back. Do I have the wrong permissions set in the module?
 

Share this post


Link to post
Share on other sites
1 hour ago, microcipcip said:

...

Do you know why? If I try the query in the GraphiQl admin I get the right data back. Do I have the wrong permissions set in the module?

No, it's not the permissions. You're doing everything properly.

I never tried this module with axios before, therefore this error is new to me. It turns out that axios sets the Content-Type header to application/json;charset=UTF-8 instead of application/json. That's where the problem was, because the ProcessGraphQL module would parse json payload only if Content-Type was set to just application/json. I changed the behavior and now it will look to your query in json payload if Content-Type contains application/json string in it. Please grab the latest version of the module and try again. It should work now.

Thank you for taking time to report the issue.

6 people like this

Share this post


Link to post
Share on other sites

Now it works!! This is so cool...I wish I could like this thread twice :). Do you have any plan of adding the RepeaterField?

I don't know if it has been mentioned in this thread yet, but I found this cool GraphQL tutorial that may be useful for someone new to GraphQL. When I learn GraphQL properly I'll test this module more, as I think it has huge potential for introducing FrontEnd devs to ProcessWire.

5 people like this

Share this post


Link to post
Share on other sites
19 minutes ago, microcipcip said:

Now it works!! This is so cool...I wish I could like this thread twice :). Do you have any plan of adding the RepeaterField?

I am happy it works now :). The plan is to add support for all core fieldtypes. That includes RepeaterField also. I will try to keep everyone updated via this thread, and you can also keep with the changelog.

6 people like this

Share this post


Link to post
Share on other sites

Hi, and thanks for this great module :)

Can you provide an example on how to create/update a page from GraphQL API ?

Tried it without success...

 

Thank you !

Share this post


Link to post
Share on other sites
On 3/21/2017 at 7:59 PM, mvdesign said:

Hi, and thanks for this great module :)

Can you provide an example on how to create/update a page from GraphQL API ?

Hi @mvdesign. So sorry that I could not respond earlier. I decided to make an introduction video for this module to help people that are trying to use it. But then, I never made a screencast video before, and on top of that, the last time I spoke english was 2011. So I had to take dozens of try-outs till I got something watchable.

So here is the video. It shows how you would create/update pages with this module. The video is far from OK, so I will probably record another one after I get some feedback. Until then please refer to this video to learn about how the module works.

 

18 people like this

Share this post


Link to post
Share on other sites

Fantastic video @Nurguly Ashyrov - really well put together and great English - I don't know how you come across so clearly given that you haven't spoken it in 6 years!

I am really excited to start using this module. The one thing I noticed which seemed a little weird to me was that by default the skyscraper-editor (or guest) user didn't have access to fields until you enabled field level access control and explicitly gave them view access (~35:10 min mark in video). By default in ProcessWire, anyone can view a field if field level access control is turned off. Only once it is turned on are any restrictions applied. Does that make sense, or did I misinterpret something?

Thanks again - this is going to be so very useful!

 

3 people like this

Share this post


Link to post
Share on other sites

Thanks @adrian! I rerecorded the video many times before I could make it watchable. Trust me, you wouldn't say the same thing for the very first ones :D 

About the field access rules. Yeah that's true. By default the behavior is the opposite to the one in ProcessWire. I think it would be better for security if the module initially treats everything private. But I get what you mean. In cases where you have dozens of fields in one template, it would be too tedious to configure access for each of them. That's why there is an option to reverse the behavior in the advanced section of the module configuration. You can learn more about it here. This option basically makes all fields without Access rules available to the public and you can restrict access by enabling rules only to couple ones.

7 people like this

Share this post


Link to post
Share on other sites

 

3 minutes ago, Nurguly Ashyrov said:

I think it would be better for security if the module initially treats everything private.

+1

Also, normally a public query interface should not serve all data by default, as that would allow for pretty easy data harvesting.

2 people like this

Share this post


Link to post
Share on other sites

awesome screencast, nurguly. easy to follow, well explained and well spoken. it helped me a lot to get a better understanding what your module does and what could be done!

i'm curious what will be built on top of this :)

2 people like this

Share this post


Link to post
Share on other sites
19 minutes ago, Nurguly Ashyrov said:

Thanks @adrian! I rerecorded the video many times before I could make it watchable. Trust me, you wouldn't say the same thing for the very first ones :D 

About the field access rules. Yeah that's true. By default the behavior is the opposite to the one in ProcessWire. I think it would be better for security if the module initially treats everything private. But I get what you mean. In cases where you have dozens of fields in one template, it would be too tedious to configure access for each of them. That's why there is an option to reverse the behavior in the advanced section of the module configuration. You can learn more about it here. This option basically makes all fields without Access rules available to the public and you can restrict access by enabling rules only to couple ones.

Thanks for the explanation and for the "Grant Field Access" config option. I definitely see your logic behind treating access the other way around. I guess I was just considering the situation where you have a regular web site where you want to be able to use the PW API as well as GraphQL. In this situation I would have no problem with all fields being accessible, so great that option is available!

2 people like this

Share this post


Link to post
Share on other sites

Super-useful video and your command of English is really impressive: you are more articulate than many native speakers! :D

It's very slick what the GraphQL devs have done with the GraphiQL tool - so nice having the documentation explorer right there inside the tool.

Thanks for the video, and also a separate thanks for updating the Skyscrapers profile and making the export of that available. Would it be okay to mention your repo of that over in the Skyscrapers Profile thread so people can use it until we have an official profile release by Ryan?

1 person likes this

Share this post


Link to post
Share on other sites

@Nurguly Ashyrov awesome cast! Thanks for making all this and taking your time to make it awesome :) This is really cool stuff and opens up a lot of possibilities.

2 people like this

Share this post


Link to post
Share on other sites
5 hours ago, Robin S said:

Thanks for the video, and also a separate thanks for updating the Skyscrapers profile and making the export of that available. Would it be okay to mention your repo of that over in the Skyscrapers Profile thread so people can use it until we have an official profile release by Ryan?

Sure, by all means.

5 hours ago, Soma said:

@Nurguly Ashyrov awesome cast! Thanks for making all this and taking your time to make it awesome :) This is really cool stuff and opens up a lot of possibilities.

Thanks. I am glad you like it @Soma.

1 person likes this

Share this post


Link to post
Share on other sites

Just playing around a little with it and it's amazing having a blast. 

Just wanted to mention I got caught by a redirect scenario and language stuff. :) If you have multilange installed and configured to have language segments "/en/", "/de/" ...  so trying out ajax requests to "/graphql/" would redirect to "/en/graphql/ " but you get a response:

{"errors":[{"message":"Must provide an operation."}]}

So it took me a while to figure out and was looking at the query instead. Doing the request to "/en/graphql/" works flawless.

I was testing the languages and the graphql pages you create don't have alternative languages active. This also might get you caught, when graphql is installed when there is more than 1 language set up.

Permission so far seem to work. The template access setting seem no to be inherited, I guess that is intentional? I may have missed it and it was mentioned. Then I'm sorry.  – Like in a default install "home" has guest view access enabled, so all pages inherit that (unless you set it no to). But I had to give basic-page explicit guest view access to get querying. I think it's ok to not have all templates inherit access for graphQL. 

Thanks and keep up the good work!

 

5 people like this

Share this post


Link to post
Share on other sites

How does the date field work? I get "Not valid resolved type for field \"datetime\"" datetime being the name of the field in my case.

Edit: Forget it I'm dumb, forgot to allow the field. It's unusual to not have access as superuser. But the error message is a little missleading :)

Edit: Lol hmm I added it to allowed fields and still same error. System fields "created",  "modified" work fine.

Also if you only want to get one specific page is it correct to do for example a

{
  basic_page(s: "id=1001"){ 
    list{ 
      title
    }
  }
}

or are there any other methods?

Edit:

Something else would be image Pageimage is there any support for creating sizes? I see there's something but I don't understand it yet. 

Edit: Ok I got it. I have to enable "size" for image first images the it work nicely:

... images{ size(width: 150, height: 0) { url } } ... 

So we can request a size that doesn't exist and it will create it if we have rights to do so. Thats would be pretty cool. Would be crazy to allow some stranger creating 1million sizes through public API :). But still if one has write access it is possible, but maybe thats no real issue. 

I'm still trying to grasp the concept of graphQL and your implementation in PW. So every new Fieldtype and InputfieldType would have to be implemented to work with graphQL?

1 person likes this

Share this post


Link to post
Share on other sites

I think I have found a possible solution for @bernhard  and @LostKobrakai  concerns about the ability to perform queries in the frontend.

You could use the persisted queries technique, basically you can install this npm package (there's also this webpack plugin) that will scan your code and remove the graphQL client side queries and save them to an external JSON file. Then in the PHP side you could load this JSON file and give GraphQL the right query based on the query id sent from the client side (I think you can also send variables along the query id, so the query is not "static").

I guess that if a malicious user sends a standard graphQL query you could just intercept that, so if it is not a valid id from the generated JSON file you won't execute graphQL.

1 person likes this

Share this post


Link to post
Share on other sites
On 3/31/2017 at 6:31 PM, Soma said:

Just wanted to mention I got caught by a redirect scenario and language stuff. :) If you have multilange installed and configured to have language segments "/en/", "/de/" ...  so trying out ajax requests to "/graphql/" would redirect to "/en/graphql/ " but you get a response:


{"errors":[{"message":"Must provide an operation."}]}

So it took me a while to figure out and was looking at the query instead. Doing the request to "/en/graphql/" works flawless.

Yeah, I had my nightmares with this situation too. There are lots of scenarios when ProcessWire could redirect your ajax requests and the graphql will not receive the query. The ones that I had encountered were:

  • If the url ends without slash: ...website.com/graphql ==> ...website.com/graphql/
  • If there is now www prefix: website.com/graphql/ ==> www.website.com/graphq/

And now I guess when languages are enabled you also gotta make sure ProcessWire is not redirecting you to the respective language url of the graphql api. I haven't tested the module with the languages enabled yet, but I am sure there would be some additional caveats.

On 3/31/2017 at 6:31 PM, Soma said:

Permission so far seem to work. The template access setting seem no to be inherited, I guess that is intentional? I may have missed it and it was mentioned. Then I'm sorry.  – Like in a default install "home" has guest view access enabled, so all pages inherit that (unless you set it no to). But I had to give basic-page explicit guest view access to get querying. I think it's ok to not have all templates inherit access for graphQL. 

Yes, that's the expected behavior. Unfortunately to support permission inheritance would be too expensive. Because it means to check template permissions of each ancestor of each returned page. I think the module is already slow and supporting permission inheritance would make it even slower. I guess I have to mention about not supporting permission inheritance somewhere in the documentation of the module.

23 hours ago, Soma said:

... Lol hmm I added it to allowed fields and still same error. System fields "created",  "modified" work fine.

That's right, it turns out there was a bug. I pushed an update regarding the datetime field. Grab the latest version of the module and it should work properly.

23 hours ago, Soma said:

Also if you only want to get one specific page is it correct to do for example a


{
  basic_page(s: "id=1001"){ 
    list{ 
      title
    }
  }
}

or are there any other methods?

Yep. That's the way. I know, it's ugly. But I can't think of a less verbose way to return a single page from the api. We could, of course introduce an additional field for each template like basic_page_single or something. But I don't think it's worth it, plus it will make the schema bigger for very little gain.

23 hours ago, Soma said:

So we can request a size that doesn't exist and it will create it if we have rights to do so. Thats would be pretty cool. Would be crazy to allow some stranger creating 1million sizes through public API :). But still if one has write access it is possible, but maybe thats no real issue. 

I'm still trying to grasp the concept of graphQL and your implementation in PW. So every new Fieldtype and InputfieldType would have to be implemented to work with graphQL?

I totally agree. We can't allow everyone to create images. The size field of the image type creates images only if the user has an edit permission on that image field. It is still available to the users who do not have edit permission, but only for getting existing variations, and it should return null if there isn't an image variation with the requested size.

Edit: By the way, thanks a lot for the feedback.

4 people like this

Share this post


Link to post
Share on other sites

@Nurguly Ashyrov Thanks for the video ! i'm using your module with Vue.js for a web application, really nice. I'm juste facing a problem right now, i get an error when trying to get checkboxes : Not valid resolved type for field \"checkbox_name\" (the field access is allowed in graphql settings). Any idea ?

 

1 person likes this

Share this post


Link to post
Share on other sites
18 minutes ago, mvdesign said:

@Nurguly Ashyrov Thanks for the video ! i'm using your module with Vue.js for a web application, really nice. I'm juste facing a problem right now, i get an error when trying to get checkboxes : Not valid resolved type for field \"checkbox_name\" (the field access is allowed in graphql settings). Any idea ?

Yes. It was my bad. I did not make sure the FieldtypeCheckbox always returned a boolean. I think it returns 0/1 in ProcessWire. Anyways, just patched it. Update to the latest version and it should work.

Edit: As always, thanks for the feedback.

2 people like this

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bernhard
      Hi,
      just stumbled over a little module that i built for my last project. it helped me to test performance of my rockdatatables module to generate 3000 random json datasets and i want to share it with you. maybe it saves some time for someone.
      https://gitlab.com/baumrock/RockDummyData/
      easy example:
      $rdd = $modules->get('RockDummyData'); for($i=0; $i<15; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); echo date("d.m.Y H:i:s", $dummy->timestamp) . "<br>"; } more advanced:
      $json = new stdClass(); $json->data = array(); $rdd = $modules->get('RockDummyData'); for($i=0; $i<3000; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); $obj = new stdClass(); $obj->name = $dummy->forename . ' ' . $dummy->surname; $obj->position = $dummy->job; $obj->office = $dummy->city; $obj->color = $dummy->color; $obj->start_date = new stdClass(); $obj->start_date->display = date('d.m.Y',$dummy->timestamp); $obj->start_date->sort = $dummy->timestamp; $obj->salary = rand(0,10000); $json->data[] = $obj; } echo json_encode($json); you have to store your random datasets on your own into the /data folder. there are several services for creating all kinds of random data on the web - if you know one service that allows sharing those datasets let me know and i can include common needed data into the module
    • By AndySh
      Hello!
      I need your assistance please. I purchased the module FormBuilder. Unfortunately, the module discontinued delivering customer submissions to e-mail box specified in the module settings. Direct mailing to the e-mail box works OK. The module settings stays the same and are correct, like "Send e-mail to administrator(s) is checked. The last version of FormBuilder 3.0 has been installed. Please advise how to resolve the issue becase I cannot get orders from customers anymore (((
    • By kixe
      As described in this post (https://processwire.com/talk/topic/8551-custom-urls-for-pages/?p=82742) the option 'Name Format Children' under the tab 'Family' in template settings doesn't work properly and also not as expected. I had a look inside the code and made some changes which are working properly, which offers much more options, more consistency and less code too.

      The result is the following. You have 3 Options for generating name and title, which could be combined in endless variations.
      Name is always derived from title, same like creating pages manually.
      type date: if function detects # character anywhere in the string, conversion will be: deletion of # and string will be used as format parameter for PHP date() function type field: if string is a fieldname of the parent page the value of this field will be used type string: if string doesn't fit to the 2 preceeding it will be taken as it is All parts (separated by comma) will be composed in the order of setting. You can use unlimited numbers of parts

      I made a pull request on github: https://github.com/ryancramerdesign/ProcessWire/pull/831

      Example screenshots

      Setting ...


      will result in


       
    • By kongondo
      FieldtypeRuntimeMarkup and InputfieldRuntimeMarkup
       
      Modules Directory: http://modules.processwire.com/modules/fieldtype-runtime-markup/
      GitHub: https://github.com/kongondo/FieldtypeRuntimeMarkup
       
      This module allows for custom markup to be dynamically (PHP) generated and output within a page's edit screen (in Admin).
       
      The value for the fieldtype is generated at runtime. No data is saved in the database. The accompanying InputfieldRuntimeMarkup is only used to render/display the markup in the page edit screen.
       
      The field's value is accessible from the ProcessWire API in the frontend like any other field, i.e. it has access to $page and $pages.
       
      The module was commissioned/sponsored by @Valan. Although there's certainly other ways to achieve what this module does, it offers a dynamic and flexible alternative to generating your own markup in a page's edit screen whilst also allowing access to that markup in the frontend. Thanks Valan!
       
      Warning/Consideration
      Although access to ProcessWire's Fields' admin pages is only available to Superusers, this Fieldtype will evaluate and run the custom PHP Code entered and saved in the field's settings (Details tab). Utmost care should therefore be taken in making sure your code does not perform any CRUD operations!! (unless of course that's intentional) The value for this fieldtype is generated at runtime and thus no data is stored in the database. This means that you cannot directly query a RuntimeMarkup field from $pages->find(). Usage and API
       
      Backend
      Enter your custom PHP snippet in the Details tab of your field (it is RECOMMENDED though that you use wireRenderFile() instead. See example below). Your code can be as simple or as complicated as you want as long as in the end you return a value that is not an array or an object or anything other than a string/integer.
       
      FieldtypeRuntimeMarkup has access to $page (the current page being edited/viewed) and $pages. 
       
      A very simple example.
      return 'Hello'; Simple example.
      return $page->title; Simple example with markup.
      return '<h2>' . $page->title . '</h2>'; Another simple example with markup.
      $out = '<h1>hello '; $out .= $page->title; $out .= '</h1>'; return $out; A more advanced example.
      $p = $pages->get('/about-us/')->child('sort=random'); return '<p>' . $p->title . '</p>'; An even more complex example.
      $str =''; if($page->name == 'about-us') { $p = $page->children->last(); $str = "<h2><a href='{$p->url}'>{$p->title}</a></h2>"; } else { $str = "<h2><a href='{$page->url}'>{$page->title}</a></h2>"; } return $str; Rather than type your code directly in the Details tab of the field, it is highly recommended that you placed all your code in an external file and call that file using the core wireRenderFile() method. Taking this approach means you will be able to edit your code in your favourite text editor. It also means you will be able to type more text without having to scroll. Editing the file is also easier than editing the field. To use this approach, simply do:
      return wireRenderFile('name-of-file');// file will be in /site/templates/ If using ProcessWire 3.x, you will need to use namespace as follows:
      return ProcessWire\wireRenderFile('name-of-file'); How to access the value of RuntimeMarkup in the frontend (our field is called 'runtime_markup')
       
      Access the field on the current page (just like any other field)
      echo $page->runtime_markup; Access the field on another page
      echo $pages->get('/about-us/')->runtime_markup; Screenshots
       
      Backend
       

       

       
      Frontend