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 MoritzLost
      This is a new module that provides a simple solution to clearing all your cache layers at once, and an extensible interface to perform various cache-related actions.
      The simple motivation behind this module was that I was tired of manually clearing caches in several places after deploying a change on a live site. The basic purpose of this module is a simple Clear all caches link in the Setup menu which clears out all caches, no matter where they hide. You can customize what exactly the module does through it's configuration menu:
      Expire or delete all cache entries in the database, or selectively clear caches by namespace ($cache API) Clear the the template render cache. Clear out specific folders inside your site's cache directory (/site/assets/cache) Refresh version strings for static assets to bust client-side browser caches (this requires some setup, see the full documentation for details). This is the basic function of the module. However, you can also add different cache management action through the API and execute them through the module's interface. For this advanced usage, the module provides:
      An interface to see all available cache actions and execute them. A system log and logging output on the module page to see verify what the module is doing. A CacheControlTools class with utility functions to clear out different caches. An API to add cache actions, execute them programmatically and even modify the default action. Permission management, allowing you granular control over which user roles can execute which actions. The complete documentation can be found in the module's README.
      Beta release
      Note that I consider this a Beta release. Since the module is relatively aggressive in deleting some caches, I would advise you to install in on a test environment before using it on a live site.
      Let me know if you're getting any errors, have trouble using the module or if you have suggestions for improvement!
      In particular, can someone let me know if this module causes any problems with the ProCache module? I don't own or use it, so I can't check. As far as I can tell, ProCache uses a folder inside the cache directory to cache static pages, so my module should be able to clear the ProCache site cache as well, I'd appreciate it if someone can test that for me.
      Future plans
      If there is some interest in this, I plan to expand this to a more general cache management solution. I particular, I would like to add additional cache actions. Some ideas that came to mind:
      Warming up the template render cache for publicly accessible pages. Removing all active user sessions. Let me know if you have more suggestions!
      Links
      https://github.com/MoritzLost/ProcessCacheControl ProcessCacheControl in the Module directory

    • By joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="optin" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="optin" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: https://github.com/blaueQuelle/privacywire/tree/master
      Download: https://github.com/blaueQuelle/privacywire/archive/master.zip
      I would love to hear your feedback 🙂
      Edit: Updated URLs to master tree of git repo
       
    • By David Karich
      Admin Page Tree Multiple Sorting
      ClassName: ProcessPageListMultipleSorting
      Extend the ordinary sort of children of a template in the admin page tree with multiple properties. For each template, you can define your own rule. Write each template (template-name) in a row, followed by a colon and then the additional field names for sorting.
      Example: All children of the template "blog" to be sorted in descending order according to the date of creation, then descending by modification date, and then by title. Type:
      blog: -created, -modified, title  Installation
      Copy the files for this module to /site/modules/ProcessPageListMultipleSorting/ In admin: Modules > Check for new modules. Install Module "Admin Page Tree Multible Sorting". Alternative in ProcessWire 2.4+
      Login to ProcessWire backend and go to Modules Click tab "New" and enter Module Class Name: "ProcessPageListMultipleSorting" Click "Download and Install"   Compatibility   I have currently tested the module only under PW 2.6+, but think that it works on older versions too. Maybe someone can give a feedback.     Download   PW-Repo: http://modules.processwire.com/modules/process-page-list-multiple-sorting/ GitHub: https://github.com/FlipZoomMedia/Processwire-ProcessPageListMultipleSorting     I hope someone can use the module. Have fun and best regards, David
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version (has been tested up to v3.3), add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "https://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


×
×
  • Create New...