Jump to content
dadish

GraphQL for ProcessWire

Recommended Posts

22 hours ago, dadish said:

Unfortunately I haven't had much time in optimization for this module. I'm very busy so can't promise any timelines when this will happen. The only thing you can do now is to keep your graphql schema as small as possible by unchecking all the unwanted fields and templates in the module config page.

There is supposed to be a way to cache the schema (https://github.com/youshido-php/GraphQL/pull/37) I was planning to look into it. But never had a time for it and thus is not implemented in this module yet.

Haven't looked at the inner workings of this yet, but is this something (caching) that Wire Cache could do?

Share this post


Link to post
Share on other sites
2 minutes ago, patricktsg said:

How would one go about limiting results in the s: selector query and also paginate?

 

Ok I figured that out, just pass limit=x into the s:

I'm trying to build a list of filters from checkboxes and pass them into the s: for example- below how would you pass the pf_shade value into here?
 

{
  product_single (s: "pf_shade=dark,limit=1")  {
    list {
      title
      product_code
      product_primary_thumb {
        httpUrl
      }      
    }
  }
}

 

Share this post


Link to post
Share on other sites

I've figured this out after some trail and error - new to GraphQL in vue so what I did was create a const that looks at this.filters than use that in my query like this:

The important part is using ${yourvar} inside the `` enclosed query
 

	myQuery: function(args) {
		console.log('Build query', args);
		const PARAMS = args;
		console.log('const', PARAMS);
		var data = {
		    query: `
		      query Products {
				  product_single (s: ${PARAMS}) {
				    list {
				      title
				      product_code
				      product_primary_thumb {
				        httpUrl
				      }
				    }
				  }
		
		        }
		      `
		  }  
		  
		  return data;
	},


	// Axios request the products
    fetchProducts: function () {
	  console.log('Get Products...');
      this.loading = true;  
	  var data = this.myQuery(this.filters);
      axios.post("http:/yourendpoint.local/graphql/", data)
      .then((response)  =>  {
        console.log(response);
        this.products = response.data.data.product_single; // dig deep to target the list data make template cleaner
        this.loading = false;
      }, (error)  =>  {
        this.loading = false;
      })
    }
    

I could probably merge this back into the one get function the reason I split it was to try and get an arg passing when I was doing the trial and error.

Share this post


Link to post
Share on other sites

I have httpUrl as a legal field but I get an error when trying to access this field in my page (using Vue) when not logged in


 

Quote

 

TypeError: null is not an object (evaluating 'item.httpUrl')


 

When I am logged in this error does not occur and the page rendering works fine.

 

Is this a bug on the legal field?

Share this post


Link to post
Share on other sites

@patricktsg

As far as I understand, it's not the httpUrl you are having the problem with. It's the "item" in "item.httpUrl". The error "null is not an object" in JS means you're trying to access a property of a null, in this case "item". So whatever the "item" is in your query, you're getting "null" for it from your api. Then in your JS you're trying to access "httpUrl" of the "null" when you do "item.httpUrl". Hence the "null is not an object" error.

 

So make sure your "item" is not null when returned from the api. If the "item" is a page, make sure the user (in this case guest) has access privileges for that page.

  • Like 1

Share this post


Link to post
Share on other sites
5 minutes ago, dadish said:

@patricktsg

As far as I understand, it's not the httpUrl you are having the problem with. It's the "item" in "item.httpUrl". The error "null is not an object" in JS means you're trying to access a property of a null, in this case "item". So whatever the "item" is in your query, you're getting "null" for it from your api. Then in your JS you're trying to access "httpUrl" of the "null" when you do "item.httpUrl". Hence the "null is not an object" error.

 

So make sure your "item" is not null when returned from the api. If the "item" is a page, make sure the user (in this case guest) has access privileges for that page.

 

I think I have the correct fields on / enabled and templates in the module settings but when not logged in I get that item.X related error in console the minute it hits the first item reference in my v-for loop, when I look at the conole where I am logging the response from the GraphQl endpoint it is not showing the data array, 

 

	                    <div v-for="(item,index) in products.list" :key="index">
	                        <div class="uk-card uk-card-default uk-card-small">
	                            <div class="uk-card-media-top uk-animation-toggle">
	                                <div class="uk-overflow-hidden">
	                                    <a :href="item.httpUrl">
		                                    <div v-if="item.product_primary_thumb.length">
	                                        	<img class="uk-animation-kenburns" :src="item.product_primary_thumb[0].size.httpUrl" :alt="item.title">
		                                    </div>
		                                    <div v-else>
			                                    <img class="uk-animation-kenburns" src="<?=$config->urls->templates?>/img/placeholder.jpg" :alt="item.title">
		                                    </div>
	                                    </a>
	                                </div>
	                            </div>
	                            <div class="uk-card-header">
	                                <h4 class="uk-card-title uk-text-small uk-text-uppercase">
	                                    {{item.title}}
	                                </h4>
	                            </div>
	                            <div class="uk-card-body">
	                            	{{item.product_code}}
	                            	<i class="fas fa-info-circle pull-right mimic-link" @click="focusProduct(item)" uk-toggle="target: #quickview"></i>
	                            </div>
	                        </div>
	                    </div>

If I remove the above from my code so the error does not block the rest of the load I get null returned for all the product data from the GraphQL endpoint (in a browser I'm not logged into the admin with), seems that unless logged in it's not permitting the correct response.

 

 

 

Screen Shot 2018-11-01 at 10.37.45.png

Share this post


Link to post
Share on other sites

So it is obviously a permission problem. Can you show me the query you're making to your api please.

  • Like 1

Share this post


Link to post
Share on other sites
	// Build the query passing in the filters
	productQuery: function(args) {
		const PARAMS = args;
		var data = {
		    query: `
		      query Products {
				  product_single (s: ${PARAMS}) {
				    list {
				      title
				      httpUrl
				      product_code
				      body_plain_text
				      body
				      product_primary_thumb {
				        httpUrl
				        size(width: 800, height: 600) {
				          httpUrl
				        }
				      }
				    }
				    getTotal
				  }
		        }
		      `
		  }  
		  return data;
	},

FYI: The {PARAMS} part is where I am taking in some vue object data from checkboxes, I set some default params through PHP.

I then use axios post like so

 

	// Axios request the products
    fetchProducts: function () {
	  console.log('Get Products...');
      this.loading = true;  
	  var data = this.productQuery(this.filters);
      axios.post("someendpoint.dev/graphql/", data)
      .then((response)  =>  {
        console.log(response.data);
        ...
        ...
        ...

 

Share this post


Link to post
Share on other sites
Just now, patricktsg said:

	// Build the query passing in the filters
	productQuery: function(args) {
		const PARAMS = args;
		var data = {
		    query: `
		      query Products {
				  product_single (s: ${PARAMS}) {
				    list {
				      title
				      httpUrl
				      product_code
				      body_plain_text
				      body
				      product_primary_thumb {
				        httpUrl
				        size(width: 800, height: 600) {
				          httpUrl
				        }
				      }
				    }
				    getTotal
				  }
		        }
		      `
		  }  
		  return data;
	},

I was able to reproduce the similar response from your api. Seems like your guest user might not have access to one of the fields of the "product_single" page. You'll have to go to each of the "product_single" page fields that you are querying and make sure Access is enabled and the guest user has a view access to it.

  • Like 1

Share this post


Link to post
Share on other sites

I've turned on nearly every field in the module setting now and still no joy unless I tick those Template and Field access checkboxes

Share this post


Link to post
Share on other sites

Please test your query in a Graphiql. Insert your query in the Graphiql and confirm that the "product_single.list" is an array of nulls. Now remove every field inside the list and leave "id" and confirm that the list now contains objects with single "id" property in it. If that was successful then keep adding your "product_single" fields one by one. Whenever you see that the list is an array of "null"s, it means that exact field is causing this issue.

  • Like 1

Share this post


Link to post
Share on other sites

Hi, I'm new to GraphQl, try to wrap my head around it and I couldn't find it in the docs or here in the forum. So here's my question:

Is there a way to "reverse" find and list pages which reference a page?

For example, I want to get a list of speakers with all the needed fields (name etc.) and their talks at conferences. The problem is, that I don't link the conferences on the speaker template, but reference the speakers on the conference template.

{
  speaker {
    list {
      u_name
      u_forename
      u_vita
    }
  }
}

How can I output the conferences for every speaker, when I'm querying the speakers? Is this possible?

Thanks!

Share this post


Link to post
Share on other sites
59 minutes ago, Torsten Baldes said:

For example, I want to get a list of speakers with all the needed fields (name etc.) and their talks at conferences. The problem is, that I don't link the conferences on the speaker template, but reference the speakers on the conference template.

AFAIK the only way to ask PW to get you conferences that has particular speakers in it, is to pass which speakers exactly you want. The selector looks like

"template=conferences, speaker=1234|1235|1236..."

So, you need get the speakers before you can query the conferences. My only solution is to query all your speakers first. Then make another query of all conferences that has those speakers in it. Query them all at once. And then, in the client when you are listing conferences for each speaker, just filter through them.

I know, it's not a great solution, but I can't think of another way. I haven't used ProccessWire in a while, so there might be some better way.

  • Like 2

Share this post


Link to post
Share on other sites
3 hours ago, Torsten Baldes said:

Is there a way to "reverse" find and list pages which reference a page?

Have a look at the Connect Page Fields module. This will let you simultaneously add conferences to speakers when you add speakers to conferences.

You can also get pages that reference a page via the API with $page->references() since PW 3.0.107.

  • Like 6

Share this post


Link to post
Share on other sites

And you can use RockFinder as the probably most efficient way.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks for all your suggestions!

I thought it would be possible with just one query.

Connect Page Fields seems like a good choice here (because I have no idea, how I would use RockFinder with the GraphQL module 😬 )

Thanks!

  • Like 1

Share this post


Link to post
Share on other sites
8 minutes ago, Torsten Baldes said:

because I have no idea, how I would use RockFinder with the GraphQL module

True 🙂 don't know about the benefits of using graphql over direct SQL (that's what RockFinder does) though, but would be happy to hear.

Share this post


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

don't know about the benefits of using graphql over direct SQL

Graphql is a query language you most often use for frontend/backend interaction or even public apis (kinda an alternative to rest). You wouldn't want to give random users direct access to sql though.

  • Like 2
  • Thanks 1

Share this post


Link to post
Share on other sites
16 hours ago, Torsten Baldes said:

How can I output the conferences for every speaker, when I'm querying the speakers? Is this possible?

Hi, look at  join-monster (Stem) or DataLoader (Facebook)  to solve the N+1 query problem.

 

 

  • Like 2

Share this post


Link to post
Share on other sites
38 minutes ago, LostKobrakai said:

You wouldn't want to give random users direct access to sql though.

Sure, I'm not talking about giving public users access to SQL but executing the query directly via SQL (and not via some php code like regular $pages->find() operations do). Don't know how GraphQL works in this regard. That's what I was interested in.

Because it would also be possible to use RockFinder as some kind of service endpoint quite easily:

w5MG1If.png

I guess I need to try GraphQL and hope to find some time for that soon...

  • Like 2

Share this post


Link to post
Share on other sites
15 minutes ago, bernhard said:

That's what I was interested in.

Because it would also be possible to use RockFinder as some kind of service endpoint

I was exactly thinking about that some days ago but I still can't find the time to do tests.

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By teppo
      Needed a really simple solution to embed audio files within page content and couldn't find a module for that, so here we go. Textformatter Audio Embed works a bit like Textformatter Video Embed, converting this:
      <p>https://www.domain.tld/path/to/file.mp3</p> Into this:
      <audio controls class="TextformatterAudioEmbed"> <source src="https://www.domain.tld/path/to/file.mp3" type="audio/mpeg"> </audio> The audio element has pretty good browser support, so quite often this should be enough to get things rolling 🙂
      GitHub repository: https://github.com/teppokoivula/TextformatterAudioEmbed Modules directory: https://modules.processwire.com/modules/textformatter-audio-embed/
    • By Richard Jedlička
      Tense    
      Tense (Test ENvironment Setup & Execution) is a command-line tool to easily run tests agains multiple versions of ProcessWire CMF.
      Are you building a module, or a template and you need to make sure it works in all supported ProcessWire versions? Then Tense is exactly what you need. Write the tests in any testing framework, tell Tense which ProcessWire versions you are interested in and it will do the rest for you.

      See example or see usage in a real project.
      How to use?
      1. Install it: 
      composer global require uiii/tense 2. Create tense.yml config:
      tense init 3. Run it:
      tense run  
      For detailed instructions see Github page: https://github.com/uiii/tense
       
      This is made possible thanks to the great wireshell tool by @justb3a, @marcus and others.
       
      What do you think about it? Do you find it useful? Do you have some idea? Did you find some bug? Tell me you opinion. Write it here or in the issue tracker.
    • By Chris Bennett
      Hi all, I am going round and round in circles and would greatly appreciate if anyone can point me in the right direction.
      I am sure I am doing something dumb, or missing something I should know, but don't. Story of my life 😉

      Playing round with a module and my basic problem is I want to upload an image and also use InputfieldMarkup and other Inputfields.
      Going back and forth between trying an api generated page defining Fieldgroup, Template, Fields, Page and the InputfieldWrapper method.

      InputfieldWrapper method works great for all the markup stuff, but I just can't wrap my head around what I need to do to save the image to the database.
      Can generate a Field for it (thanks to the api investigations) but not sure what I need to do to link the Inputfield to that. Tried a lot of stuff from various threads, of varying dates without luck.
      Undoubtedly not helped by me not knowing enough.

      Defining Fieldgroup etc through the api seems nice and clean and works great for the images but I can't wrap my head around how/if I can add/append/hook the InputfieldWrapper/InputfieldMarkup stuff I'd like to include on that template as well. Not even sure if it should be where it is on ___install with the Fieldtype stuff or later on . Not getting Tracy errors, just nothing seems to happen.
      If anyone has any ideas or can point me in the right direction, that would be great because at the moment I am stumbling round in the dark.
       
      public function ___install() { parent::___install(); $page = $this->pages->get('name='.self::PAGE_NAME); if (!$page->id) { // Create fieldgroup, template, fields and page // Create new fieldgroup $fmFieldgroup = new Fieldgroup(); $fmFieldgroup->name = MODULE_NAME.'-fieldgroup'; $fmFieldgroup->add($this->fields->get('title')); // needed title field $fmFieldgroup->save(); // Create new template using the fieldgroup $fmTemplate = new Template(); $fmTemplate->name = MODULE_NAME; $fmTemplate->fieldgroup = $fmFieldgroup; $fmTemplate->noSettings = 1; $fmTemplate->noChildren = 1; $fmTemplate->allowNewPages = 0; $fmTemplate->tabContent = MODULE_NAME; $fmTemplate->noChangeTemplate = 1; $fmTemplate->setIcon(ICON); $fmTemplate->save(); // Favicon source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFavicon'; $fmField->label = 'Favicon'; $fmField->focusMode = 'off'; $fmField->gridMode = 'grid'; $fmField->extensions = 'svg png'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Favicon Silhouette source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFaviconSilhouette'; $fmField->label = 'SVG Silhouette'; $fmField->notes = 'When creating a silhouette/mask svg version for Safari Pinned Tabs and Windows Tiles, we recommend setting your viewbox for 0 0 16 16, as this is what Apple requires. In many cases, the easiest way to do this in something like illustrator is a sacrificial rectangle with no fill, and no stroke at 16 x 16. This forces the desired viewbox and can then be discarded easily using something as simple as notepad. Easy is good, especially when you get the result you want without a lot of hassle.'; $fmField->focusMode = 'off'; $fmField->extensions = 'svg'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Create: Open Settings Tab $tabOpener = new Field(); $tabOpener->type = new FieldtypeFieldsetTabOpen(); $tabOpener->name = 'fmTab1'; $tabOpener->label = "Favicon Settings"; $tabOpener->collapsed = Inputfield::collapsedNever; $tabOpener->addTag(MODULE_NAME); $tabOpener->save(); // Create: Close Settings Tab $tabCloser = new Field(); $tabCloser->type = new FieldtypeFieldsetClose; $tabCloser->name = 'fmTab1' . FieldtypeFieldsetTabOpen::fieldsetCloseIdentifier; $tabCloser->label = "Close open tab"; $tabCloser->addTag(MODULE_NAME); $tabCloser->save(); // Create: Opens wrapper for Favicon Folder Name $filesOpener = new Field(); $filesOpener->type = new FieldtypeFieldsetOpen(); $filesOpener->name = 'fmOpenFolderName'; $filesOpener->label = 'Wrap Folder Name'; $filesOpener->class = 'inline'; $filesOpener->collapsed = Inputfield::collapsedNever; $filesOpener->addTag(MODULE_NAME); $filesOpener->save(); // Create: Close wrapper for Favicon Folder Name $filesCloser = new Field(); $filesCloser->type = new FieldtypeFieldsetClose(); $filesCloser->name = 'fmOpenFolderName' . FieldtypeFieldsetOpen::fieldsetCloseIdentifier; $filesCloser->label = "Close open fieldset"; $filesCloser->addTag(MODULE_NAME); $filesCloser->save(); // Create Favicon Folder Name $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeText"); $fmField->name = 'folderName'; $fmField->label = 'Favicon Folder:'; $fmField->description = $this->config->urls->files; $fmField->placeholder = 'Destination Folder for your generated favicons, webmanifest and browserconfig'; $fmField->columnWidth = 100; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon('folder'); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($tabOpener); $fmFieldgroup->add($filesOpener); $fmFieldgroup->add($fmField); $fmFieldgroup->add($filesCloser); $fmFieldgroup->add($tabCloser); $fmFieldgroup->save(); /////////////////////////////////////////////////////////////// // Experimental Markup Tests $wrapperFaviconMagic = new InputfieldWrapper(); $wrapperFaviconMagic->attr('id','faviconMagicWrapper'); $wrapperFaviconMagic->attr('title',$this->_('Favicon Magic')); // field show info what $field = $this->modules->get('InputfieldMarkup'); $field->name = 'use'; $field->label = __('How do I use it?'); $field->collapsed = Inputfield::collapsedNever; $field->icon('info'); $field->attr('value', 'Does this even begin to vaguely work?'); $field->columnWidth = 50; $wrapperFaviconMagic->add($field); $fmTemplate->fields->add($wrapperFaviconMagic); $fmTemplate->fields->save(); ///////////////////////////////////////////////////////////// // Create page $page = $this->wire( new Page() ); $page->template = MODULE_NAME; $page->parent = $this->wire('pages')->get('/'); $page->addStatus(Page::statusHidden); $page->title = 'Favicons'; $page->name = self::PAGE_NAME; $page->process = $this; $page->save(); } }  
    • By Sebi
      Since it's featured in ProcessWire Weekly #310, now is the time to make it official:
      Here is Twack!
      I really like the following introduction from ProcessWire Weekly, so I hope it is ok if I use it here, too. Look at the project's README for more details!
      Twack is a new — or rather newish — third party module for ProcessWire that provides support for reusable components in an Angular-inspired way. Twack is implemented as an installable module, and a collection of helper and base classes. Key concepts introduced by this module are:
      Components, which have separate views and controllers. Views are simple PHP files that handle the output for the component, whereas controllers extend the TwackComponent base class and provide additional data handling capabilities. Services, which are singletons that provide a shared service where components can request data. The README for Twack uses a NewsService, which returns data related to news items, as an example of a service. Twack components are designed for reusability and encapsulating a set of features for easy maintainability, can handle hierarchical or recursive use (child components), and are simple to integrate with an existing site — even when said site wasn't originally developed with Twack.
      A very basic Twack component view could look something like this:
      <?php namespace ProcessWire; ?> <h1>Hello World!</h1> And here's how you could render it via the API:
      <?php namespace Processwire; $twack = $modules->get('Twack'); $hello = $twack->getNewComponent('HelloWorld'); ?> <html> <head> <title>Hello World</title> </head> <body> <?= $hello->render() ?> </body> </html> Now, just to add a bit more context, here's a simple component controller:
      <?php namespace ProcessWire; class HelloWorld extends TwackComponent { public function __construct($args) { parent::__construct($args); $this->title = 'Hello World!'; if(isset($args['title'])) { $this->title = $args['title']; } } } As you can see, there's not a whole lot new stuff to learn here if you'd like to give Twack a try in one of your projects. The Twack README provides a really informative and easy to follow introduction to all the key concepts (as well as some additional examples) so be sure to check that out before getting started. 
      Twack is in development for several years and I use it for every new project I build. Also integrated is an easy to handle workflow to make outputs as JSON, so it can be used to build responses for a REST-api as well. I will work that out in one section in the readme as well. 
      If you want to see the module in an actual project, I have published the code of www.musical-fabrik.de in a repository. It runs completely with Twack and has an app-endpoint with ajax-output as well.
      I really look forward to hear, what you think of Twack🥳!
      Features Installation Usage Quickstart: Creating a component Naming conventions & component variants Component Parameters directory page parameters viewname Asset handling Services Named components Global components Ajax-Output Configuration Versioning License Changelog
    • By Robin S
      Page Reference Default Value
      Most ProcessWire core inputfield types that can be used with a Page Reference field support a "Default value" setting. This module extends support for default values to the following core inputfield types:
      Page List Select Page List Select Multiple Page Autocomplete (single and multiple) Seeing as these inputfield types only support the selection of pages a Page List Select / Page List Select Multiple is used for defining the default value instead of the Text / Textarea field used by the core for other inputfield types. This makes defining a default value a bit more user-friendly.
      Note that as per the core "Default value" setting, the Page Reference field must be set to "required" in order for the default value to be used.
      Screenshot

       
      https://github.com/Toutouwai/PageReferenceDefaultValue
      https://modules.processwire.com/modules/page-reference-default-value/
×
×
  • Create New...