Jump to content

GraphQL for ProcessWire


dadish

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?

Link to comment
Share on other sites

  • 2 weeks later...
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
      }      
    }
  }
}

 

Link to comment
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.

Link to comment
Share on other sites

  • 4 weeks later...

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?

Link to comment
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
Link to comment
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

Link to comment
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);
        ...
        ...
        ...

 

Link to comment
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
Link to comment
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
Link to comment
Share on other sites

  • 1 month later...

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!

Link to comment
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
Link to comment
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
Link to comment
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.

Link to comment
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
Link to comment
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
Link to comment
Share on other sites

Create an account or sign in to comment

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

Create an account

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

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      FieldtypeQRCode
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      Options
      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Formatting
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      Examples
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      Features
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.
      https://github.com/techcnet/ProcessFileManager

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

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

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

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

       
×
×
  • Create New...