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 Macrura
      PrevNextTabs Module
      Github: https://github.com/outflux3/PrevNextTabs
      Processwire helper modules for adding page navigation within the editor.
      Overview
      This is a very simple module that adds Previous and Next links inline with the tabs on the page editor. Hovering over the tab shows the title of the previous or next page (using the admin's built in jqueryUI tooltips.)
      Usage
      This module is typically used during development where you or your editors need to traverse through pages for the purpose of proofing, flagging and/or commenting. Rather than returning to the page tree or lister, they can navigate with these links.
      Warnings
      If you are using PW version 2.6.1 or later, the system will prevent you from leaving the page if you have unsaved edits.
      For earlier versions, to avoid accidentally losing changes made to a page that might occur if a user accidentally clicks on one of these, make sure to have the Form Save Reminder module installed.
      http://modules.processwire.com/modules/prev-next-tabs/
    • By Gadgetto
      SnipWire - Snipcart integration for ProcessWire
      Snipcart is a powerful 3rd party, developer-first HTML/JavaScript shopping cart platform. SnipWire is the missing link between Snipcart and the content management framework ProcessWire.
      With SnipWire, you can quickly turn any ProcessWire site into a Snipcart online shop. The SnipWire plugin helps you to get your store up and running in no time. Detailed knowledge of the Snipcart system is not required.
      SnipWire is free and open source licensed under Mozilla Public License 2.0! A lot of work and effort has gone into development. It would be nice if you could donate an amount to support further development:

      Status update links (inside this thread) for SnipWire development
      2020-03-21 -- SnipWire 0.8.5 (beta) released! Improves SnipWires webhooks interface and provides some other fixes and additions 2020-03-03 -- SnipWire 0.8.4 (beta) released! Improves compatibility for Windows based Systems. 2020-03-01 -- SnipWire 0.8.3 (beta) released! The installation and uninstallation process has been heavily revised. 2020-02-08 -- SnipWire 0.8.2 (beta) released! Added a feature to change the cart and catalogue currency by GET, POST or SESSION param 2020-02-03 -- SnipWire 0.8.1 (beta) released! All custom classes moved into their own namespaces. 2020-02-01 -- SnipWire is now available via ProcessWire's module directory! 2020-01-30 -- SnipWire 0.8.0 (beta) first public release! (module just submitted to the PW modules directory) 2020-01-28 -- added Custom Order Fields feature (first SnipWire release version is near!) 2020-01-21 -- Snipcart v3 - when will the new cart system be implemented? 2020-01-19 -- integrated taxes provider finished (+ very flexible shipping taxes handling) 2020-01-14 -- new date range picker, discount editor, order notifiactions, order statuses, and more ... 2019-11-15 -- orders filter, order details, download + resend invoices, refunds 2019-10-18 -- list filters, REST API improvements, new docs platform, and more ... 2019-08-08 -- dashboard interface, currency selector, managing Orders, Customers and Products, Added a WireTabs, refinded caching behavior 2019-06-15 -- taxes provider, shop templates update, multiCURL implementation, and more ... 2019-06-02 -- FieldtypeSnipWireTaxSelector 2019-05-25 -- SnipWire will be free and open source Plugin Key Features
      Fast and simple store setup Full integration of the Snipcart dashboard into the ProcessWire backend (no need to leave the ProcessWire admin area) Browse and manage orders, customers, discounts, abandoned carts, and more Multi currency support Custom order and cart fields Process refunds and send customer notifications from within the ProcessWire backend Process Abandoned Carts + sending messages to customers from within the ProcessWire backend Complete Snipcart webhooks integration (all events are hookable via ProcessWire hooks) Integrated taxes provider (which is more flexible then Snipcart own provider) Useful Links
      SnipWire in PW modules directory SnipWire Docs (please note that the documentation is a work in progress) SnipWire @GitHub (feature requests and suggestions for improvement are welcome - I also accept pull requests) Snipcart Website  
      ---- INITIAL POST FROM 2019-05-25 ----
       
    • By horst
      Croppable Image 3
      for PW 3.0.20+
      Module Version 1.2.0
      Sponsored by http://dreikon.de/, many thanks Timo & Niko!
      You can get it in the modules directory!
      Please refer to the readme on github for instructions.
       
      - + - + - + - + - + - + - + - + - + - NEWS - 2020/03/19 - + - + - + - + - + - + - + - + - + - 
      There is a new Version in the pipe, that supports WebP too: 
       
      - + - + - + - + - + - + - + - + - + - NEWS - 2020/03/19 - + - + - + - + - + - + - + - + - + - 
       
       
      -------------------------------------------------------------------------
       
      Updating from prior versions:
       
      Updating from Croppable Image 3 with versions prior to 1.1.7, please do this as a one time step:
      In the PW Admin, go to side -> modules -> new, use "install via ClassName" and use CroppableImage3 for the Module Class Name. This will update your existing CroppableImage3 module sub directory, even if it is called a new install. After that, the module will be recogniced by the PW updater module, what makes it a lot easier on further updates.
      -------------------------------------------------------------------------
       
      For updating from the legacy Thumbnail / CropImage to CroppableImage3 read on here.
       
      -------------------------------------------------------------------------
       
    • By Robin S
      Inspired by a recent question.
      Image Crop Ratios
      Allows preset aspect ratios to be defined per image field for the ProcessWire image crop tool.
      The module adds a select dropdown to the crop tool. Choose an aspect ratio and the crop area will be fixed to that ratio.
      Screencast

      Installation
      Install the Image Crop Ratios module.
      Configuration
      Default aspect ratios for all image fields can be defined in the module config. Aspect ratios for specific image fields can be defined on the Input tab of the field settings. You can override the ratio settings in template context if needed. Insert a hyphen as the first item in the ratio settings unless you want to force a ratio to be applied to the crop tool. The hyphen represents a blank option that allows a free crop area to be drawn. Usage
      Click the "Crop" link on the details view of an image thumbnail. Click the "Crop" icon at the top of the editor window. Choose an option from the "Ratio" select dropdown.  
      https://github.com/Toutouwai/ImageCropRatios
      https://modules.processwire.com/modules/image-crop-ratios/
×
×
  • Create New...