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

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

       
    • By tcnet
      Session Viewer is a module for ProcessWire to list session files and display session data. This module is helpful to display the session data of a specific session or to kick out a logged in user by simply delete his session file. After installation the module is available in the Setup menu.

      The following conditions must be met for the module to work properly:
      Session files
      Session data must be stored in session files, which is the default way in ProcessWire. Sessions stored in the database are not supported by this module. The path to the directory where the session files are stored must be declared in the ProcessWire configuration which is by default: site/assets/sessions.
      Serialize handler
      In order to transform session data easier back to a PHP array, the session data is stored serialized. PHP offers a way to declare a custom serialize handler. This module supports only the default serialize handlers: php, php_binary and php_serialize. WDDX was dropped in PHP 7.4.0 and is therefore not supported by this module as well as any other custom serialize handler. Which serialize handler is actually used you can find out in the module configuration which is available under Modules=>Configure=>SessionViewer.

      Session data
      The session data can be displayed in two different ways. PHP's default output for arrays print_r() or by default for this module nice_r() offered on github: https://github.com/uuf6429/nice_r. There is a setting in the module configuration if someone prefers print_r(). Apart from the better handling and overview of the folded session data the output of nice_r() looks indeed nicer.

      Links
      ProcessWire module directory
      github.com
    • By Robin S
      Repeater Easy Sort
      Adds a compact "easy-sort" mode to Repeater and Repeater Matrix, making those fields easier to sort when there are a large number of items.
      The module also enhances Repeater Matrix by allowing a colour to be set for each matrix type. This colour is used in the item headers and in the "add new" links, to help visually distinguish different matrix types in the inputfield.
      Screencasts
      A Repeater field

      A Repeater Matrix field with custom header colours

      Easy-sort mode
      Each Repeater/Matrix item gets an double-arrow icon in the item header. Click this icon to enter easy-sort mode.
      While in easy-sort mode:
      The items will reduce in width so that more items can be shown on the screen at once. The minimum width is configurable in the field settings. Any items that were in an open state are collapsed, but when you exit easy-sort mode the previously open items will be reopened. You can drag an item left/right/up/down to sort it within the items. The item that you clicked the icon for is shown with a black background. This makes it easier to find the item you want to move in easy-sort mode. You can click an item header to open the item. An "Exit easy-sort mode" button appears at the bottom of the inputfield. Configuration
      In the field settings for Repeater and Repeater Matrix fields you can define a minimum width in pixels for items in easy-sort mode. While in easy-sort mode the items will be sized to neatly fill the available width on any screen size but will never be narrower than the width you set here.
      In the field settings for Repeater Matrix you can define a custom header colour for each matrix type using an HTML "color" type input. The default colour for this type of input is black, so when black is selected in the input it means that no custom colour will be applied to the header.
      Exclusions
      The easy-sort mode is only possible on Repeater/Matrix fields that do not use the "item depth" option.
       
      https://github.com/Toutouwai/RepeaterEasySort
      https://processwire.com/modules/repeater-easy-sort/
×
×
  • Create New...