Skip to content

Commit

Permalink
Merge pull request #11 from MaxSouza/graphql-cache
Browse files Browse the repository at this point in the history
Added cache on graphql schema
  • Loading branch information
maria-axe authored Jul 30, 2023
2 parents 9a890da + 6d42ebf commit a6629a9
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 42 deletions.
44 changes: 26 additions & 18 deletions Model/Resolver/HasCustomerPurchasedProduct.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Discorgento\ProductLastOrder\Model\Resolver;

use Exception;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
Expand Down Expand Up @@ -102,10 +103,23 @@ public function __construct(
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$customerId = $args['customerId'];
$productId = $args['productId'];
$customerId = (int)$args['customerId'];
$productId = (int)$args['productId'];
$dataSkeleton = [
'hasPurchased' => false,
'orderLink' => '',
'orderDate' => '',
'customer_id' => '',
'product_id' => ''
];

try {

// Avoid request if there's no customer_id(not logged)
if (empty($customerId)) {
return $dataSkeleton;
}

$customer = $this->customerRepository->getById($customerId);
$customerEmail = $customer->getEmail();

Expand All @@ -117,29 +131,23 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value

foreach ($orders as $order) {
foreach ($order->getAllVisibleItems() as $item) {
if ($item->getProductId() == $productId) {
if ((int)$item->getProductId() === $productId) {

return [
'hasPurchased' => true,
'orderLink' => $this->getOrderLink($order),
'orderDate' => $this->getFormattedOrderDate($order->getCreatedAt())
'orderDate' => $this->getFormattedOrderDate($order->getCreatedAt()),
'customer_id' => $customerId,
'product_id' => $productId
];
}
}
}
} catch (\Exception $e) {
return [
'hasPurchased' => false,
'orderLink' => '',
'orderDate' => ''
];
} catch (Exception) {
return $dataSkeleton;
}

return [
'hasPurchased' => false,
'orderLink' => '',
'orderDate' => ''
];
return $dataSkeleton;
}

/**
Expand Down Expand Up @@ -169,16 +177,16 @@ private function getFormattedOrderDate($createdAt)
$createdAtObject = new \DateTime($createdAt, new \DateTimeZone($this->timezone->getConfigTimezone()));
$userTimezone = $this->timezone->getConfigTimezone();
$format = \IntlDateFormatter::MEDIUM;

return $this->timezone->formatDateTime(
$createdAtObject,
$format,
\IntlDateFormatter::NONE,
null,
$userTimezone
);
} catch (\Exception $e) {

} catch (Exception $e) {
return '';
}
}
Expand Down
32 changes: 32 additions & 0 deletions Model/Resolver/ProductLastOrderIdentity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Discorgento\ProductLastOrder\Model\Resolver;

use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface;

class ProductLastOrderIdentity implements IdentityInterface
{
private string $cacheTag = 'disc_productlastorder';

/**
* @inheritDoc
*/
public function getIdentities(array $resolvedData): array
{
$data["id"] = empty($resolvedData["customer_id"]) && empty($resolvedData["product_id"]) ? [] : [
'customer_id' => $resolvedData["customer_id"],
'product_id' => $resolvedData['product_id']];

return empty($data['id']) ?
[] : array_merge([$this->cacheTag], array_map(function ($item) {
return sprintf('%s_%s_%s', $this->cacheTag, $item['customer_id'], $item['product_id']);
}, $data));
}
}
1 change: 1 addition & 0 deletions etc/schema.graphqls
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ type Query {
@resolver(
class: "Discorgento\\ProductLastOrder\\Model\\Resolver\\HasCustomerPurchasedProduct"
)
@cache(cacheIdentity: "Discorgento\\ProductLastOrder\\Model\\Resolver\\ProductLastOrderIdentity" cacheable: true)
}

type HasPurchasedProduct {
Expand Down
48 changes: 24 additions & 24 deletions view/frontend/web/js/component-msg-last-order.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ define([
*/
initialize: function (config) {
const { customerId, productId } = config;

this._super();
this.makeGraphQLRequest();
},
Expand All @@ -35,30 +35,30 @@ define([
* Makes a GraphQL request to check if a customer has purchased a product.
*/
makeGraphQLRequest: function () {
var self = this;

var urlGraphql = urlBuilder.build('graphql');
let self = this;

var requestConfig = {
url: urlGraphql,
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
query: `
query CheckCustomerProductPurchase($customerId: String!, $productId: String!) {
hasCustomerPurchasedProduct(customerId: $customerId, productId: $productId) {
hasPurchased
orderLink
orderDate
}
}
`,
variables: {
customerId: self.customerId,
productId: self.productId
let urlGraphql = urlBuilder.build('graphql');
let queryGraphqlObject = {
query: `
query CheckCustomerProductPurchase($customerId: String!, $productId: String!) {
hasCustomerPurchasedProduct(customerId: $customerId, productId: $productId) {
hasPurchased
orderLink
orderDate
}
})
}`
};

let variablesGraphql = JSON.stringify({
customerId: self.customerId,
productId: self.productId
});

let queryEncoded = $.param(queryGraphqlObject);
let queryGraphql = queryEncoded+'&variables='+ variablesGraphql;
let requestConfig = {
url: urlGraphql +'?'+queryGraphql,
method: 'GET'
};

$.ajax(requestConfig).done(function (response) {
Expand All @@ -68,7 +68,7 @@ define([
if (hasPurchased) {
self.isVisible(true);
}

self.orderLink(orderLink);
self.orderDate(orderDate);
}).fail(function (error) {
Expand Down

0 comments on commit a6629a9

Please sign in to comment.