Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat(api): add attachments #1304

Merged
merged 5 commits into from
May 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions packages/api/src/__generated__/schema.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ export interface OrderFormInputItem {
quantity: number
seller: string
index?: number
attachments?: Attachment[]
}

export interface Attachment {
name: string
content: Record<string, string>
}

export interface OrderFormItem {
Expand Down Expand Up @@ -48,6 +54,7 @@ export interface OrderFormItem {
sellingPrices: SellingPrice[]
total: number
}
attachments: Attachment[]
}

export interface SKUSpecification {
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/platforms/vtex/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Query } from './resolvers/query'
import { StoreReview } from './resolvers/review'
import { StoreSearchResult } from './resolvers/searchResult'
import { StoreSeo } from './resolvers/seo'
import { ObjectOrString } from './resolvers/objectOrString'
import type { Loaders } from './loaders'
import type { Clients } from './clients'
import type { Channel } from './utils/channel'
Expand Down Expand Up @@ -67,6 +68,7 @@ const Resolvers = {
StoreReview,
StoreProductGroup,
StoreSearchResult,
ObjectOrString,
Query,
Mutation,
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { inStock } from '../utils/productStock'
import type { EnhancedCommercialOffer } from '../utils/enhanceCommercialOffer'
import type { StoreProduct } from './product'
import type { PromiseType } from '../../../typings'
import type { Resolver } from '..'

type Root = PromiseType<ReturnType<typeof StoreProduct.offers>>

export const StoreAggregateOffer: Record<string, Resolver<Root>> & {
offers: Resolver<Root, any, EnhancedCommercialOffer[]>
offers: Resolver<Root, any, Root>
} = {
highPrice: (offers) => {
const availableOffers = offers.filter(inStock)
Expand Down
46 changes: 46 additions & 0 deletions packages/api/src/platforms/vtex/resolvers/objectOrString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { GraphQLScalarSerializer } from 'graphql'
import { GraphQLScalarType } from 'graphql'
import { Kind } from 'graphql/language'

export const ObjectOrString = new GraphQLScalarType({
name: 'ObjectOrString',
description:
'A string or the string representation of an object (a stringified object).',
parseValue: toObjectOrString,
serialize: stringify,
Comment on lines +9 to +10
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't get it, does the ouptut will be always a string, either a string or a stringified object?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is always a string, but it can be a regular string eg. "hello world" or and stringified object "{"key": "value"}"

parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return getValueAsObjectOrString(ast.value)
}

return null
},
})

function toObjectOrString(value: GraphQLScalarSerializer<any>) {
if (typeof value === 'string') {
return getValueAsObjectOrString(value)
}

return null
}

function getValueAsObjectOrString(value: string) {
try {
return JSON.parse(value)
} catch (e) {
return value
}
}

function stringify(value: GraphQLScalarSerializer<any>) {
if (typeof value === 'object') {
return JSON.stringify(value)
}

if (typeof value === 'string') {
return value
}

return null
}
12 changes: 11 additions & 1 deletion packages/api/src/platforms/vtex/resolvers/offer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,17 @@ export const StoreOffer: Record<string, Resolver<Root>> = {

return null
},
itemOffered: ({ product }) => product,
itemOffered: async (root) => {
if (isSearchItem(root)) {
return root.product
}

if (isOrderFormItem(root)) {
return { ...(await root.product), attachmentsValues: root.attachments }
}

return null
},
quantity: (root) => {
if (isSearchItem(root)) {
return root.AvailableQuantity ?? 0
Expand Down
35 changes: 30 additions & 5 deletions packages/api/src/platforms/vtex/resolvers/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import type { EnhancedCommercialOffer } from '../utils/enhanceCommercialOffer'
import type { Resolver } from '..'
import type { PromiseType } from '../../../typings'
import type { Query } from './query'
import { VALUE_REFERENCES } from '../utils/propertyValue'
import type { Attachment } from '../clients/commerce/types/OrderForm'

type Root = PromiseType<ReturnType<typeof Query.product>>
type QueryProduct = PromiseType<ReturnType<typeof Query.product>>

type Root = QueryProduct & {
attachmentsValues?: Attachment[]
}

const DEFAULT_IMAGE = {
imageText: 'image',
Expand All @@ -19,7 +25,12 @@ const nonEmptyArray = <T>(array: T[] | null | undefined) =>
Array.isArray(array) && array.length > 0 ? array : null

export const StoreProduct: Record<string, Resolver<Root>> & {
offers: Resolver<Root, any, EnhancedCommercialOffer[]>
offers: Resolver<
Root,
any,
Array<EnhancedCommercialOffer<Root['sellers'][number], Root>>
>

isVariantOf: Resolver<Root, any, Root>
} = {
productID: ({ itemId }) => itemId,
Expand Down Expand Up @@ -77,9 +88,23 @@ export const StoreProduct: Record<string, Resolver<Root>> & {
)
.sort(bestOfferFirst),
isVariantOf: (root) => root,
additionalProperty: ({ variations = [] }) => {
return variations.flatMap(({ name, values }) =>
values.map((value) => ({ name, value }))
additionalProperty: ({ variations = [], attachmentsValues }) => {
const propertyValueVariations = variations.flatMap(({ name, values }) =>
values.map((value) => ({
name,
value,
valueReference: VALUE_REFERENCES.variation,
}))
)

const propertyValueAttachments = (attachmentsValues ?? []).map(
(attachment) => ({
name: attachment.name,
value: attachment.content,
valueReference: VALUE_REFERENCES.attachment,
})
)

return [...propertyValueVariations, ...propertyValueAttachments]
},
}
7 changes: 6 additions & 1 deletion packages/api/src/platforms/vtex/resolvers/productGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { enhanceSku } from '../utils/enhanceSku'
import type { Resolver } from '..'
import type { PromiseType } from '../../../typings'
import type { StoreProduct } from './product'
import { VALUE_REFERENCES } from '../utils/propertyValue'

type Root = PromiseType<ReturnType<typeof StoreProduct.isVariantOf>>

Expand All @@ -22,7 +23,11 @@ export const StoreProductGroup: Record<string, Resolver<Root>> = {
// Transform specs back into product specs
.flatMap(({ specifications }) =>
specifications.flatMap(({ name, values }) =>
values.map((value) => ({ name, value }))
values.map((value) => ({
name,
value,
valueReference: VALUE_REFERENCES.specification,
}))
)
),
}
33 changes: 32 additions & 1 deletion packages/api/src/platforms/vtex/resolvers/validateCart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,38 @@ import type {
OrderFormItem,
} from '../clients/commerce/types/OrderForm'
import type { Context } from '..'
import { VALUE_REFERENCES } from '../utils/propertyValue'

type Indexed<T> = T & { index?: number }

const getAttachments = (item: IStoreOffer) =>
item.itemOffered.additionalProperty?.filter(
(i) => i.valueReference === VALUE_REFERENCES.attachment
)

const serializeAttachment = (item: IStoreOffer) => {
const attachments = getAttachments(item)

if (attachments?.length === 0) {
return null
}

return attachments
?.map(
(attachment) => `${attachment.name}:${JSON.stringify(attachment.value)}`
)
.join('-')
}

const getId = (item: IStoreOffer) =>
[item.itemOffered.sku, item.seller.identifier, item.price].join('::')
[
item.itemOffered.sku,
item.seller.identifier,
item.price,
serializeAttachment(item),
]
.filter(Boolean)
.join('::')

const orderFormItemToOffer = (
item: OrderFormItem,
Expand All @@ -41,6 +68,10 @@ const offerToOrderItemInput = (
seller: offer.seller.identifier,
id: offer.itemOffered.sku,
index: offer.index,
attachments: getAttachments(offer)?.map((attachment) => ({
name: attachment.name,
content: attachment.value,
})),
})

const groupById = (offers: IStoreOffer[]): Map<string, IStoreOffer> =>
Expand Down
20 changes: 8 additions & 12 deletions packages/api/src/platforms/vtex/utils/enhanceCommercialOffer.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import type {
CommertialOffer,
Seller,
} from '../clients/search/types/ProductSearchResult'
import type { EnhancedSku } from './enhanceSku'
import type { CommertialOffer } from '../clients/search/types/ProductSearchResult'

export type EnhancedCommercialOffer = CommertialOffer & {
seller: Seller
product: EnhancedSku
export type EnhancedCommercialOffer<S, P> = CommertialOffer & {
seller: S
product: P
}

export const enhanceCommercialOffer = ({
export const enhanceCommercialOffer = <S, P>({
offer,
seller,
product,
}: {
offer: CommertialOffer
seller: Seller
product: EnhancedSku
}): EnhancedCommercialOffer => ({
seller: S
product: P
}): EnhancedCommercialOffer<S, P> => ({
...offer,
product,
seller,
Expand Down
5 changes: 5 additions & 0 deletions packages/api/src/platforms/vtex/utils/propertyValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const VALUE_REFERENCES = {
variation: 'VARIATION',
attachment: 'ATTACHMENT',
specification: 'SPECIFICATION',
} as const
2 changes: 2 additions & 0 deletions packages/api/src/typeDefs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import Cart from './cart.graphql'
import Status from './status.graphql'
import PropertyValue from './propertyValue.graphql'
import Person from './person.graphql'
import ObjectOrString from './objectOrString.graphql'

export const typeDefs = [
Query,
Expand All @@ -46,6 +47,7 @@ export const typeDefs = [
Status,
PropertyValue,
Person,
ObjectOrString,
]
.map(print)
.join('\n')
1 change: 1 addition & 0 deletions packages/api/src/typeDefs/objectOrString.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
scalar ObjectOrString
4 changes: 4 additions & 0 deletions packages/api/src/typeDefs/product.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,8 @@ input IStoreProduct {
Array of product images.
"""
image: [IStoreImage!]!
"""
Custom Product Additional Properties.
"""
additionalProperty: [IStorePropertyValue!]
}
23 changes: 21 additions & 2 deletions packages/api/src/typeDefs/propertyValue.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,30 @@ Properties that can be associated with products and products groups.
"""
type StorePropertyValue {
"""
Property value.
Property value. May hold a string or the string representation of an object.
"""
value: String!
value: ObjectOrString!
"""
Property name.
"""
name: String!
"""
Specifies the nature of the value
"""
valueReference: String!
}

input IStorePropertyValue {
"""
Property value. May hold a string or the string representation of an object.
"""
value: ObjectOrString!
"""
Property name.
"""
name: String!
"""
Specifies the nature of the value
"""
valueReference: String!
}