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

On 7/23/2021 at 11:24 AM, 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.

@dadish could you please get back to me on this?

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

Hello, 

I'm revisiting a project using this and I'm having some issues. 

image.png.749dc109033c366530fc515e037f9e76.png

image.thumb.png.62c63333ea1830ab6faf89eceb7ffbb4.png

image.png

In this example I'm using "job_title". From what I can tell everything is in place. For what reason am I receiving this error?

 

@dadish

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

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
      (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.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.
      https://github.com/techcnet/ProcessFileManager

      Warning
      This module is probably the most powerful module. You might destroy your processwire installation if you don't exactly know what you doing. Be careful and use it at your own risk!
      ACE code editor
      This module uses ACE code editor available from: https://github.com/ajaxorg/ace

      Dragscroll
      This module uses the JavaScript dragscroll available from: http://github.com/asvd/dragscroll. Dragscroll adds the ability to drag the table horizontally with the mouse pointer.
      PHP File Manager
      This module uses a modified version of PHP File Manager available from: https://github.com/alexantr/filemanager
       
    • By tcnet
      This module implements the website live chat service from tawk.to. Actually the module doesn't have to do much. It just need to inserted a few lines of JavaScript just before the closing body tag </body> on each side. However, the module offers additional options to display the widget only on certain pages.
      Create an account
      Visit https://www.tawk.to and create an account. It's free! At some point you will reach a page where you can copy the required JavaScript-code.

      Open the module settings and paste the JavaScript-code into the field as shown below. Click "Submit" and that's all.

      Open the module settings
      The settings for this module are located int the menu Modules=>Configure=>LiveChatTawkTo.

       
×
×
  • Create New...