Vendure provider: split out gql operations, remove unused files

This commit is contained in:
Michael Bromley 2021-03-10 21:28:46 +01:00
parent 23c3412c17
commit 36303dddd5
32 changed files with 217 additions and 400 deletions

View File

@ -4,21 +4,7 @@ import useLogin, { UseLogin } from '@commerce/auth/use-login'
import { CommerceError, ValidationError } from '@commerce/utils/errors'
import useCustomer from '../customer/use-customer'
import { LoginMutation, LoginMutationVariables } from '../schema'
export const loginMutation = /* GraphQL */ `
mutation login($username: String!, $password: String!) {
login(username: $username, password: $password) {
__typename
... on CurrentUser {
id
}
... on ErrorResult {
errorCode
message
}
}
}
`
import { loginMutation } from '../lib/mutations/log-in-mutation'
export default useLogin as UseLogin<typeof handler>

View File

@ -3,14 +3,7 @@ import { MutationHook } from '@commerce/utils/types'
import useLogout, { UseLogout } from '@commerce/auth/use-logout'
import useCustomer from '../customer/use-customer'
import { LogoutMutation } from '../schema'
export const logoutMutation = /* GraphQL */ `
mutation logout {
logout {
success
}
}
`
import { logoutMutation } from '../lib/mutations/log-out-mutation'
export default useLogout as UseLogout<typeof handler>

View File

@ -8,21 +8,7 @@ import {
SignupMutation,
SignupMutationVariables,
} from '../schema'
export const signupMutation = /* GraphQL */ `
mutation signup($input: RegisterCustomerInput!) {
registerCustomerAccount(input: $input) {
__typename
... on Success {
success
}
... on ErrorResult {
errorCode
message
}
}
}
`
import { signupMutation } from '../lib/mutations/sign-up-mutation'
export default useSignup as UseSignup<typeof handler>

View File

@ -4,23 +4,9 @@ import { CommerceError } from '@commerce/utils/errors'
import { MutationHook } from '@commerce/utils/types'
import { useCallback } from 'react'
import useCart from './use-cart'
import { cartFragment } from '../api/fragments/cart'
import { AddItemToOrderMutation } from '../schema'
import { normalizeCart } from '../lib/normalize'
export const addItemToOrderMutation = /* GraphQL */ `
mutation addItemToOrder($variantId: ID!, $quantity: Int!) {
addItemToOrder(productVariantId: $variantId, quantity: $quantity) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`
import { addItemToOrderMutation } from '../lib/mutations/add-item-to-order-mutation'
export default useAddItem as UseAddItem<typeof handler>

View File

@ -1,19 +1,10 @@
import { Cart } from '@commerce/types'
import { SWRHook } from '@commerce/utils/types'
import useCart, { FetchCartInput, UseCart } from '@commerce/cart/use-cart'
import { cartFragment } from '../api/fragments/cart'
import { ActiveOrderQuery, CartFragment } from '../schema'
import { normalizeCart } from '../lib/normalize'
import { useMemo } from 'react'
export const getCartQuery = /* GraphQL */ `
query activeOrder {
activeOrder {
...Cart
}
}
${cartFragment}
`
import { getCartQuery } from '../lib/queries/get-cart-query'
export type CartResult = {
activeOrder?: CartFragment

View File

@ -3,27 +3,13 @@ import { HookFetcherContext, MutationHookContext } from '@commerce/utils/types'
import useRemoveItem, { UseRemoveItem } from '@commerce/cart/use-remove-item'
import { CommerceError } from '@commerce/utils/errors'
import useCart from './use-cart'
import { cartFragment } from '../api/fragments/cart'
import {
RemoveOrderLineMutation,
RemoveOrderLineMutationVariables,
} from '../schema'
import { Cart, LineItem, RemoveCartItemBody } from '@commerce/types'
import { normalizeCart } from '../lib/normalize'
export const removeOrderLineMutation = /* GraphQL */ `
mutation removeOrderLine($orderLineId: ID!) {
removeOrderLine(orderLineId: $orderLineId) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`
import { removeOrderLineMutation } from '../lib/mutations/remove-order-line-mutation'
export default useRemoveItem as UseRemoveItem<typeof handler>

View File

@ -13,22 +13,8 @@ import {
AdjustOrderLineMutation,
AdjustOrderLineMutationVariables,
} from '../schema'
import { cartFragment } from '../api/fragments/cart'
import { normalizeCart } from '../lib/normalize'
export const adjustOrderLineMutation = /* GraphQL */ `
mutation adjustOrderLine($orderLineId: ID!, $quantity: Int!) {
adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`
import { adjustOrderLineMutation } from '../lib/mutations/adjust-order-line-mutation'
export default useUpdateItem as UseUpdateItem<typeof handler>

View File

@ -1,28 +1,7 @@
import { VendureConfig, getConfig } from '../api'
import { getConfig, VendureConfig } from '../api'
import { GetCollectionsQuery } from '../schema'
import { arrayToTree } from '../lib/array-to-tree'
export const getCollectionsQuery = /* GraphQL */ `
query getCollections {
collections {
items {
id
name
description
slug
productVariants {
totalItems
}
parent {
id
}
children {
id
}
}
}
}
`
import { getCollectionsQuery } from '../lib/queries/get-collections-query'
async function getSiteInfo({
query = getCollectionsQuery,

View File

@ -1,34 +0,0 @@
import { GetCustomerIdQuery } from '../schema'
import { VendureConfig, getConfig } from '../api'
export const getCustomerIdQuery = /* */ `
query getCustomerId {
customer {
entityId
}
}
`
async function getCustomerId({
customerToken,
config,
}: {
customerToken: string
config?: VendureConfig
}): Promise<number | undefined> {
config = getConfig(config)
const { data } = await config.fetch<GetCustomerIdQuery>(
getCustomerIdQuery,
undefined,
{
headers: {
cookie: `${config.customerCookie}=${customerToken}`,
},
}
)
return data?.customer?.entityId
}
export default getCustomerId

View File

@ -1,41 +1,4 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { definitions } from '../api/definitions/wishlist'
import { VendureConfig, getConfig } from '../api'
import getAllProducts, { ProductEdge } from '../product/get-all-products'
export type Wishlist = Omit<definitions['wishlist_Full'], 'items'> & {
items?: WishlistItem[]
}
export type WishlistItem = NonNullable<
definitions['wishlist_Full']['items']
>[0] & {
product?: ProductEdge['node']
}
export type GetCustomerWishlistResult<
T extends { wishlist?: any } = { wishlist?: Wishlist }
> = T
export type GetCustomerWishlistVariables = {
customerId: number
}
async function getCustomerWishlist(opts: {
variables: GetCustomerWishlistVariables
config?: VendureConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult>
async function getCustomerWishlist<
T extends { wishlist?: any },
V = any
>(opts: {
url: string
variables: V
config?: VendureConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult<T>>
import { getConfig, VendureConfig } from '../api'
async function getCustomerWishlist({
config,
@ -43,45 +6,13 @@ async function getCustomerWishlist({
includeProducts,
}: {
url?: string
variables: GetCustomerWishlistVariables
variables: any
config?: VendureConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult> {
}): Promise<any> {
// Not implemented as Vendure does not ship with wishlist functionality at present
config = getConfig(config)
const { data = [] } = await config.storeApiFetch<
RecursivePartial<{ data: Wishlist[] }>
>(`/v3/wishlists?customer_id=${variables.customerId}`)
const wishlist = data[0]
if (includeProducts && wishlist?.items?.length) {
const entityIds = wishlist.items
?.map((item) => item?.product_id)
.filter((id): id is number => !!id)
if (entityIds?.length) {
const graphqlData = await getAllProducts({
variables: { first: 100, entityIds },
config,
})
// Put the products in an object that we can use to get them by id
const productsById = graphqlData.products.reduce<{
[k: number]: ProductEdge
}>((prods, p) => {
prods[p.node.entityId] = p
return prods
}, {})
// Populate the wishlist items with the graphql products
wishlist.items.forEach((item) => {
const product = item && productsById[item.product_id!]
if (item && product) {
item.product = product.node
}
})
}
}
return { wishlist: wishlist as RecursiveRequired<typeof wishlist> }
return { wishlist: {} }
}
export default getCustomerWishlist

View File

@ -2,17 +2,7 @@ import { SWRHook } from '@commerce/utils/types'
import useCustomer, { UseCustomer } from '@commerce/customer/use-customer'
import { Customer } from '@commerce/types'
import { ActiveCustomerQuery } from '../schema'
export const activeCustomerQuery = /* GraphQL */ `
query activeCustomer {
activeCustomer {
id
firstName
lastName
emailAddress
}
}
`
import { activeCustomerQuery } from '../lib/queries/active-customer-query'
export default useCustomer as UseCustomer<typeof handler>

View File

@ -1,18 +0,0 @@
import update, { Context } from 'immutability-helper';
const c = new Context();
c.extend('$auto', function(value, object) {
return object ?
c.update(object, value):
c.update({}, value);
});
c.extend('$autoArray', function(value, object) {
return object ?
c.update(object, value):
c.update([], value);
});
export default c.update

View File

@ -0,0 +1,15 @@
import { cartFragment } from '../fragments/cart-fragment'
export const addItemToOrderMutation = /* GraphQL */ `
mutation addItemToOrder($variantId: ID!, $quantity: Int!) {
addItemToOrder(productVariantId: $variantId, quantity: $quantity) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`

View File

@ -0,0 +1,15 @@
import { cartFragment } from '../fragments/cart-fragment'
export const adjustOrderLineMutation = /* GraphQL */ `
mutation adjustOrderLine($orderLineId: ID!, $quantity: Int!) {
adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`

View File

@ -0,0 +1,14 @@
export const loginMutation = /* GraphQL */ `
mutation login($username: String!, $password: String!) {
login(username: $username, password: $password) {
__typename
... on CurrentUser {
id
}
... on ErrorResult {
errorCode
message
}
}
}
`

View File

@ -0,0 +1,7 @@
export const logoutMutation = /* GraphQL */ `
mutation logout {
logout {
success
}
}
`

View File

@ -0,0 +1,15 @@
import { cartFragment } from '../fragments/cart-fragment'
export const removeOrderLineMutation = /* GraphQL */ `
mutation removeOrderLine($orderLineId: ID!) {
removeOrderLine(orderLineId: $orderLineId) {
__typename
...Cart
... on ErrorResult {
errorCode
message
}
}
}
${cartFragment}
`

View File

@ -0,0 +1,14 @@
export const signupMutation = /* GraphQL */ `
mutation signup($input: RegisterCustomerInput!) {
registerCustomerAccount(input: $input) {
__typename
... on Success {
success
}
... on ErrorResult {
errorCode
message
}
}
}
`

View File

@ -1,74 +1,6 @@
import { Cart, Product } from '@commerce/types'
import update from '../lib/immutability'
import { CartFragment, SearchResultFragment } from '../schema'
function normalizeProductOption(productOption: any) {
const {
node: {
entityId,
values: { edges },
...rest
},
} = productOption
return {
id: entityId,
values: edges?.map(({ node }: any) => node),
...rest,
}
}
export function normalizeProduct(productNode: any): Product {
const {
entityId: id,
productOptions,
prices,
path,
id: _,
options: _0,
} = productNode
return update(productNode, {
id: { $set: String(id) },
images: {
$apply: ({ edges }: any) =>
edges?.map(({ node: { urlOriginal, altText, ...rest } }: any) => ({
url: urlOriginal,
alt: altText,
...rest,
})),
},
variants: {
$apply: ({ edges }: any) =>
edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({
id: entityId,
options: productOptions?.edges
? productOptions.edges.map(normalizeProductOption)
: [],
...rest,
})),
},
options: {
$set: productOptions.edges
? productOptions?.edges.map(normalizeProductOption)
: [],
},
brand: {
$apply: (brand: any) => (brand?.entityId ? brand?.entityId : null),
},
slug: {
$set: path?.replace(/^\/+|\/+$/g, ''),
},
price: {
$set: {
value: prices?.price.value,
currencyCode: prices?.price.currencyCode,
},
},
$unset: ['entityId'],
})
}
export function normalizeSearchResult(item: SearchResultFragment): Product {
return {
id: item.productId,

View File

@ -0,0 +1,10 @@
export const activeCustomerQuery = /* GraphQL */ `
query activeCustomer {
activeCustomer {
id
firstName
lastName
emailAddress
}
}
`

View File

@ -0,0 +1,9 @@
export const getAllProductPathsQuery = /* GraphQL */ `
query getAllProductPaths($first: Int = 100) {
products(options: { take: $first }) {
items {
slug
}
}
}
`

View File

@ -0,0 +1,12 @@
import { searchResultFragment } from '../fragments/search-result-fragment'
export const getAllProductsQuery = /* GraphQL */ `
query getAllProducts($input: SearchInput!) {
search(input: $input) {
items {
...SearchResult
}
}
}
${searchResultFragment}
`

View File

@ -0,0 +1,10 @@
import { cartFragment } from '../fragments/cart-fragment'
export const getCartQuery = /* GraphQL */ `
query activeOrder {
activeOrder {
...Cart
}
}
${cartFragment}
`

View File

@ -0,0 +1,21 @@
export const getCollectionsQuery = /* GraphQL */ `
query getCollections {
collections {
items {
id
name
description
slug
productVariants {
totalItems
}
parent {
id
}
children {
id
}
}
}
}
`

View File

@ -0,0 +1,41 @@
export const getProductQuery = /* GraphQL */ `
query getProduct($slug: String!) {
product(slug: $slug) {
id
name
slug
description
assets {
id
preview
name
}
variants {
id
priceWithTax
currencyCode
options {
id
name
code
groupId
group {
id
options {
name
}
}
}
}
optionGroups {
id
code
name
options {
id
name
}
}
}
}
`

View File

@ -0,0 +1,13 @@
import { searchResultFragment } from '../fragments/search-result-fragment'
export const searchQuery = /* GraphQL */ `
query search($input: SearchInput!) {
search(input: $input) {
items {
...SearchResult
}
totalItems
}
}
${searchResultFragment}
`

View File

@ -2,17 +2,8 @@ import type {
GetAllProductPathsQuery,
GetAllProductPathsQueryVariables,
} from '../schema'
import { VendureConfig, getConfig } from '../api'
export const getAllProductPathsQuery = /* GraphQL */ `
query getAllProductPaths($first: Int = 100) {
products(options: { take: $first }) {
items {
slug
}
}
}
`
import { getConfig, VendureConfig } from '../api'
import { getAllProductPathsQuery } from '../lib/queries/get-all-product-paths-query'
export type GetAllProductPathsResult = {
products: Array<{ node: { path: string } }>

View File

@ -1,19 +1,8 @@
import { Product } from '@commerce/types'
import { getConfig, VendureConfig } from '../api'
import { searchResultFragment } from '../api/fragments/search-result'
import { GetAllProductsQuery } from '../schema'
import { normalizeSearchResult } from '../lib/normalize'
export const getAllProductsQuery = /* GraphQL */ `
query getAllProducts($input: SearchInput!) {
search(input: $input) {
items {
...SearchResult
}
}
}
${searchResultFragment}
`
import { getAllProductsQuery } from '../lib/queries/get-all-products-query'
export type ProductVariables = { first?: number }

View File

@ -1,48 +1,7 @@
import { Product } from '@commerce/types'
import { getConfig, VendureConfig } from '../api'
import { GetProductQuery } from '@framework/schema'
export const getProductQuery = /* GraphQL */ `
query getProduct($slug: String!) {
product(slug: $slug) {
id
name
slug
description
assets {
id
preview
name
}
variants {
id
priceWithTax
currencyCode
options {
id
name
code
groupId
group {
id
options {
name
}
}
}
}
optionGroups {
id
code
name
options {
id
name
}
}
}
}
`
import { GetProductQuery } from '../schema'
import { getProductQuery } from '../lib/queries/get-product-query'
async function getProduct({
query = getProductQuery,

View File

@ -2,20 +2,8 @@ import { SWRHook } from '@commerce/utils/types'
import useSearch, { UseSearch } from '@commerce/product/use-search'
import { Product } from '@commerce/types'
import { SearchQuery, SearchQueryVariables } from '../schema'
import { searchResultFragment } from '../api/fragments/search-result'
import { normalizeSearchResult } from '../lib/normalize'
export const searchQuery = /* GraphQL */ `
query search($input: SearchInput!) {
search(input: $input) {
items {
...SearchResult
}
totalItems
}
}
${searchResultFragment}
`
import { searchQuery } from '../lib/queries/search-query'
export default useSearch as UseSearch<typeof handler>