Skip to content

Commit

Permalink
34701/productvariants query is missing inventoryitem (gatsbyjs#32450)
Browse files Browse the repository at this point in the history
* add inventoryItem field and subfields, excluding inventoryLevel

* add locations query/processor

* remove console log

* refactor processor to loop once

* fix locations typo
  • Loading branch information
DanielSLew authored Jul 21, 2021
1 parent e1a1396 commit abbb5cd
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 8 deletions.
2 changes: 1 addition & 1 deletion packages/gatsby-source-shopify/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Your Shopify store URL, e.g. some-shop.myshopify.com

An optional array of additional data types to source.

Accepted values: `'orders'`, `'collections'`
Accepted values: `'orders'`, `'collections'`, `'locations'`

`downloadImages: bool`

Expand Down
24 changes: 24 additions & 0 deletions packages/gatsby-source-shopify/src/create-schema-customization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ export function createSchemaCustomization(

const includeOrders = pluginOptions.shopifyConnections?.includes(`orders`)

const includeLocations = pluginOptions.shopifyConnections?.includes(
`locations`
)

const name = (name: string): string =>
`${pluginOptions.typePrefix || ``}${name}`

Expand Down Expand Up @@ -280,6 +284,26 @@ export function createSchemaCustomization(
)
}

if (includeLocations) {
typeDefs.push(
schema.buildObjectType({
name: name(`ShopifyInventoryLevel`),
fields: {
location: {
type: name(`ShopifyLocation`),
extensions: {
link: {
from: `location.id`,
by: `id`,
},
},
},
},
interfaces: [`Node`],
})
)
}

typeDefs.push(
...[
`ShopifyProductFeaturedImage`,
Expand Down
14 changes: 13 additions & 1 deletion packages/gatsby-source-shopify/src/gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function pluginOptionsSchema({
.default(``),
shopifyConnections: Joi.array()
.default([])
.items(Joi.string().valid(`orders`, `collections`)),
.items(Joi.string().valid(`orders`, `collections`, `locations`)),
salesChannel: Joi.string().default(
process.env.GATSBY_SHOPIFY_SALES_CHANNEL || ``
),
Expand All @@ -57,6 +57,7 @@ async function sourceAllNodes(
createProductVariantsOperation,
createOrdersOperation,
createCollectionsOperation,
createLocationsOperation,
finishLastOperation,
completedOperation,
cancelOperationInProgress,
Expand All @@ -71,6 +72,10 @@ async function sourceAllNodes(
operations.push(createCollectionsOperation)
}

if (pluginOptions.shopifyConnections?.includes(`locations`)) {
operations.push(createLocationsOperation)
}

const sourceFromOperation = makeSourceFromOperation(
finishLastOperation,
completedOperation,
Expand All @@ -90,6 +95,8 @@ const shopifyNodeTypes = [
`ShopifyProductVariantMetafield`,
`ShopifyCollectionMetafield`,
`ShopifyOrder`,
`ShopifyLocation`,
`ShopifyInventoryLevel`,
`ShopifyProduct`,
`ShopifyCollection`,
`ShopifyProductImage`,
Expand All @@ -110,6 +117,7 @@ async function sourceChangedNodes(
incrementalProductVariants,
incrementalOrders,
incrementalCollections,
incrementalLocations,
finishLastOperation,
completedOperation,
cancelOperationInProgress,
Expand Down Expand Up @@ -140,6 +148,10 @@ async function sourceChangedNodes(
operations.push(incrementalCollections(lastBuildTime))
}

if (pluginOptions.shopifyConnections?.includes(`locations`)) {
operations.push(incrementalLocations(lastBuildTime))
}

const sourceFromOperation = makeSourceFromOperation(
finishLastOperation,
completedOperation,
Expand Down
15 changes: 15 additions & 0 deletions packages/gatsby-source-shopify/src/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ProductsQuery } from "./query-builders/products-query"
import { ProductVariantsQuery } from "./query-builders/product-variants-query"
import { CollectionsQuery } from "./query-builders/collections-query"
import { OrdersQuery } from "./query-builders/orders-query"
import { LocationsQuery } from "./query-builders/locations-query"
import {
collectionsProcessor,
incrementalProductsProcessor,
Expand Down Expand Up @@ -34,10 +35,12 @@ interface IOperations {
incrementalProductVariants: (date: Date) => IShopifyBulkOperation
incrementalOrders: (date: Date) => IShopifyBulkOperation
incrementalCollections: (date: Date) => IShopifyBulkOperation
incrementalLocations: (date: Date) => IShopifyBulkOperation
createProductsOperation: IShopifyBulkOperation
createProductVariantsOperation: IShopifyBulkOperation
createOrdersOperation: IShopifyBulkOperation
createCollectionsOperation: IShopifyBulkOperation
createLocationsOperation: IShopifyBulkOperation
cancelOperationInProgress: () => Promise<void>
cancelOperation: (id: string) => Promise<BulkOperationCancelResponse>
finishLastOperation: () => Promise<void>
Expand Down Expand Up @@ -243,6 +246,13 @@ export function createOperations(
)
},

incrementalLocations(date: Date): IShopifyBulkOperation {
return createOperation(
new LocationsQuery(options).query(date),
`INCREMENTAL_LOCATIONS`
)
},

createProductsOperation: createOperation(
new ProductsQuery(options).query(),
`PRODUCTS`
Expand All @@ -265,6 +275,11 @@ export function createOperations(
collectionsProcessor
),

createLocationsOperation: createOperation(
new LocationsQuery(options).query(),
`LOCATIONS`
),

cancelOperationInProgress,
cancelOperation,
finishLastOperation,
Expand Down
27 changes: 21 additions & 6 deletions packages/gatsby-source-shopify/src/processors/product-variants.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
import { NodeInput } from "gatsby"
import { pattern as idPattern } from "../node-builder"
import { NodeInput, SourceNodesArgs } from "gatsby"
import { createNodeId, pattern as idPattern } from "../node-builder"

export function productVariantsProcessor(
objects: BulkResults,
builder: NodeBuilder
builder: NodeBuilder,
gatsbyApi: SourceNodesArgs,
pluginOptions: ShopifyPluginOptions
): Array<Promise<NodeInput>> {
const objectsToBuild = objects.filter(obj => {
const objectsToBuild = objects.reduce((objs, obj) => {
const [, remoteType] = obj.id.match(idPattern) || []

return remoteType !== `Product`
})
if (remoteType === `Product`) {
// ProductVariants query also returns products but we already process the products in another processor
} else if (remoteType === `InventoryLevel`) {
objs.push({
...obj,
location: {
id: createNodeId(obj.location.id, gatsbyApi, pluginOptions),
},
})
} else {
objs.push(obj)
}

return objs
}, [])

/**
* We will need to attach presentmentPrices here as a simple array.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { BulkQuery } from "./bulk-query"

export class LocationsQuery extends BulkQuery {
query(date?: Date): string {
const publishedStatus = this.pluginOptions.salesChannel
? encodeURIComponent(`${this.pluginOptions.salesChannel}=visible`)
: `published`

const filters = [`published_status:${publishedStatus}`]
if (date) {
const isoDate = date.toISOString()
filters.push(`created_at:>='${isoDate}' OR updated_at:>='${isoDate}'`)
}

const queryString = filters.map(f => `(${f})`).join(` AND `)

const query = `
{
locations(query: "${queryString}") {
edges {
node {
id
activatable
address {
address1
address2
city
country
countryCode
formatted
latitude
longitude
phone
province
provinceCode
zip
}
addressVerified
deactivatable
deactivatedAt
deletable
fulfillmentService {
callbackUrl
fulfillmentOrdersOptIn
handle
id
inventoryManagement
productBased
serviceName
shippingMethods {
code
label
}
type
}
fulfillsOnlineOrders
hasActiveInventory
hasUnfulfilledOrders
isActive
legacyResourceId
name
shipsInventory
}
}
}
}
`

return this.bulkOperationQuery(query)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,40 @@ export class ProductVariantsQuery extends BulkQuery {
originalSrc
transformedSrc
}
inventoryItem {
id
countryCodeOfOrigin
createdAt
duplicateSkuCount
harmonizedSystemCode
inventoryHistoryUrl
inventoryLevels {
edges {
node {
id
available
location {
id
}
}
}
}
legacyResourceId
locationsCount
provinceCodeOfOrigin
requiresShipping
sku
tracked
trackedEditable {
locked
reason
}
unitCost {
amount
currencyCode
}
updatedAt
}
inventoryPolicy
inventoryQuantity
legacyResourceId
Expand Down

0 comments on commit abbb5cd

Please sign in to comment.