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 monollonom
      PageMjmlToHtml
      Github: https://github.com/romaincazier/PageMjmlToHtml
      Modules directory: https://processwire.com/modules/page-mjml-to-html/
      A module allowing you to write your Processwire template using MJML and get a converted HTML output using MJML API.
      This is considered to be in alpha and as such needs some testing before being used in production!

      About
      Created by Mailjet, MJML is a markup language making it a breeze to create newsletters displayed consistently across all email clients.
      Write your template using MJML combined with Processwire’s API and this module will automatically convert your code into a working newsletter thanks to their free-to-use Rest API.
      Prerequisite
      For this module to work you will need to get an API key and paste it in the module’s configuration.
      Usage
      Once your credentials are validated, select the template(s) in which you’re using the MJML syntax, save and go visualize your page(s) to see if everything’s good. You will either get error/warning messages or your email properly formatted and ready-to-go.
      From there you can copy/paste the raw generated code in an external mailing service or distribute your newsletter using ProMailer.
      Features
      The MJML output is cached to avoid repetitive API calls Not cached if there are errors/warnings Cleared if the page is saved Cleared if the template file has been modified A simple (dumb?) code viewer highlights lines with errors/warnings A button is added to quickly copy the raw code of the generated newsletter Not added if the page is rendered outside of a PageView Only visible to users with the page’s edit permission A shortcut is also added under “View” in the edit page to open the raw code in a new tab Multi-languages support
      Notes
      The code viewer is only shown to superusers. If there’s an error the page will display:
      Only its title for guests Its title and a message inviting to contact the administrator for editors If you are using the markup regions output strategy, it might be best to not append files to preserve your MJML markup before calling the MJML API. This option is available in the module’s settings.
    • By Marco Ro
      Hi guys!
      I'm a bit anxious because this is the first module I present! (beta modulo) But I will finally be able to share something with the community too! :)
      This is a BETA version of the PayPal payment system called: PayPal Commerce Platform.
      It is an advanced system (Business Pro account is needed) that brings various benefits in terms of fees and above all integrates direct payment with credit/debit cards. 
      The module integrates with Padloper 0.0.2, which is the current installation I'm using.
      This system integrates the classic PayPal buy button, the alternative or local payment method and the new payment system: credit/debit cards that doesn't go through the PayPal account. It is a Stripe-style payment, it connects directly with the bank and integrates 3D security validation.
      I say that it is a BETA because this module currently only works with Sandbox account, to put it live you need to change API url manually (manually for the moment).
      Because this module is not ready for live:
      I would like to have your opinion on how I built the module (is the first one I do). I don't want to share something that is not fish but I need a comparison with someone more experienced than me, for be sure that this is the best way to code the module.
      If you want to try this I created a git, you will find all the instructions for installation and correct operation. (Git has a MIT licensed)
      https://github.com/MarcooRo/processwire-PayPal-Commerce-Platform I hope I did something that you guys can like :)
    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      FieldtypeQRCode
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      Options
      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Formatting
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      Examples
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      Features
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
×
×
  • Create New...