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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      This module lets you add some custom menu items to the main admin menu, and you can set the dropdown links dynamically in a hook if needed.
      Sidenote: the module config uses some repeatable/sortable rows for the child link settings, similar to the ProFields Table interface. The data gets saved as JSON in a hidden textarea field. Might be interesting to other module developers?
      Custom Admin Menus
      Adds up to three custom menu items with optional dropdowns to the main admin menu.
      The menu items can link to admin pages, front-end pages, or pages on external websites.
      The links can be set to open in a new browser tab, and child links in the dropdown can be given an icon.
      Requires ProcessWire v3.0.178 or newer.
      Screenshots
      Example of menu items

      Module config for the menus

      Link list shown when parent menu item is not given a URL

      Advanced
      Setting child menu items dynamically
      If needed you can set the child menu items dynamically using a hook.
      Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $colours = $event->wire()->pages->findRaw('template=colour', ['title', 'url', 'page_icon']); $children = []; foreach($colours as $colour) { // Each child item should be an array with the following keys $children[] = [ 'icon' => $colour['page_icon'], 'label' => $colour['title'], 'url' => $colour['url'], 'newtab' => false, ]; } $event->return = $children; } }); Create multiple levels of flyout menus
      It's also possible to create multiple levels of flyout submenus using a hook.

      For each level a submenu can be defined in a "children" item. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $children = [ [ 'icon' => 'adjust', 'label' => 'One', 'url' => '/one/', 'newtab' => false, ], [ 'icon' => 'anchor', 'label' => 'Two', 'url' => '/two/', 'newtab' => false, 'children' => [ [ 'icon' => 'child', 'label' => 'Red', 'url' => '/red/', 'newtab' => false, ], [ 'icon' => 'bullhorn', 'label' => 'Green', 'url' => '/green/', 'newtab' => false, 'children' => [ [ 'icon' => 'wifi', 'label' => 'Small', 'url' => '/small/', 'newtab' => true, ], [ 'icon' => 'codepen', 'label' => 'Medium', 'url' => '/medium/', 'newtab' => false, ], [ 'icon' => 'cogs', 'label' => 'Large', 'url' => '/large/', 'newtab' => false, ], ] ], [ 'icon' => 'futbol-o', 'label' => 'Blue', 'url' => '/blue/', 'newtab' => true, ], ] ], [ 'icon' => 'hand-o-left', 'label' => 'Three', 'url' => '/three/', 'newtab' => false, ], ]; $event->return = $children; } }); Showing/hiding menus according to user role
      You can determine which menu items can be seen by a role by checking the user's role in the hook.
      For example, if a user has or lacks a role you could include different child menu items in the hook return value. Or if you want to conditionally hide a custom menu altogether you can set the return value to false. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); $user = $event->wire()->user; // For custom menu number 1... if($menu_number === 1) { // ...if user does not have some particular role... if(!$user->hasRole('foo')) { // ...do not show the menu $event->return = false; } } });  
      https://github.com/Toutouwai/CustomAdminMenus
      https://processwire.com/modules/custom-admin-menus/
    • By tcnet
      This module for ProcessWire sends a notification email for each failed login attempt. Similar modules exists already in the module directory of ProcessWire. However, this module is designed to notify, even if specified user doesn't exist.
      Settings
      The settings for this module are located in the menu Modules=>Configure=>LoginFailNotifier.
      Notification email
      Specifies the email address to which the notification emails should be sent.
        Email subject
      Specifies the subject line for the notification email.
        Post variables
      Specifies the $_POST variables to be included in the notification email. Each variable must be separated by a comma. For example: login_name,login_pass
        Server variables
      Specifies the $_SERVER variables to be included in the notification email. Each variable must be separated by a comma. For example: REMOTE_ADDR,HTTP_USER_AGENT
      Link to ProcessWire module directory:
      https://processwire.com/modules/login-fail-notifier/
      Link to github.com:
      https://github.com/techcnet/LoginFailNotifier
    • By Fokke
      ProcessWire 3.x markup module for rendering meta tags in HTML document head section. Note that this module is not a full-blown SEO solution, but rather a simple tool for rendering meta tags based on module configuration. Adding custom meta tags is also supported.
      Built-in meta tags
      The following meta tags are supported out-of-the-box:
      Document title consisting of page title and site name Character set Canonical Viewport Description Keywords Hreflang tags Open Graph og:title og:site_name og:type og:url og:description og:image og:image:width og:image:height Twitter meta tags twitter:card twitter:site twitter:creator twitter:title twitter:description twitter:image Facebook meta tags fb:app_id The full documentation with configurable options can be found here: https://github.com/Fokke-/MarkupMetadata
       
      Requirements:
      ProcessWire>=3.0.0 PHP >=7.1 Installation using Composer
      composer require fokke/markup-metadata Manual installation
      Download latest version from https://github.com/Fokke-/MarkupMetadata/archive/master.zip Extract module files to site/modules/MarkupMetadata directory.
    • By m.sieber
      ITRK-Service for ProcessWire
      Module for the automated transfer of imprint, data protection declaration and terms and conditions from IT-Recht Kanzlei to your ProcessWire installation
      What is ITRK Service for ProcessWire?
      ITRK-Service for ProcessWire is a free module for ProcessWire CMS. It provides an interface to the update service of IT-Recht Kanzlei, via which the legal texts of your online presence are automatically updated. In this way, the texts remain legally secure and warning-proof in the long term. Imprint, data protection declaration, revocation and general terms and conditions are currently supported.
      You can find our documentation (in german language) here: https://www.pupit.de/itrk-service-for-processwire/dokumentation/

      Download: https://www.pupit.de/itrk-service-for-processwire/
      Github: https://github.com/pupit-de/pwItrkServiceConnector
    • By LuisM
      Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Service-Provider
      It acts as a Drop-In Replacement Module to handle the Request/Response outside the ProcessWire Admin. Even tough Symfony or any other mature MVC Framework could be intimidating at first, Symprowire tries to abstract Configuration and Symfony Internals away as much as possible to give you a quick start and lift the heavy work for you.
      The main Goal is to give an easy path to follow an MVC Approach during development with ProcessWire and open up the available eco-system.
      You can find the GitHub Repo and more Information here: https://github.com/Luis85/symprowire
      Documentation
      The Symprowire Wiki https://github.com/Luis85/symprowire/wiki How to create a simple Blog with Symprowire https://github.com/Luis85/symprowire/wiki/Symprowire-Blog-Tutorial Last Update
      16.07.2021 // RC 1 v0.6.0 centralized ProcessWire access trough out the Application by wrapping to a Service https://github.com/Luis85/symprowire/releases/tag/v0.6.0-rc-1 Requirements
      PHP ^7.4 Fresh ProcessWire ^3.0.181 with a Blank Profile Composer 2 (v1 should work, not recommended) The usual Symfony Requirements Features
      Twig Dependency Injection Monolog for Symprowire Support for .env YAML Configuration Symfony Console and Console Commands Symfony Webprofiler Full ProcessWire access inside your Controller and Services Webpack Encore support Caveats
      Symfony is no small Framework and will come with a price in terms of Memory Usage and added Overhead. To give you a taste I installed Tracy Debugger alongside to compare ProcessWire profiling with the included Symfony Webprofiler

      So in a fresh install Symprowire would atleast add another 2MB of Memory usage and around 40ms in response time, should be less in production due to the added overhead of the Webprofiler in dev env
       
×
×
  • Create New...