Skip to content

Commit

Permalink
feat: support cookies on api
Browse files Browse the repository at this point in the history
  • Loading branch information
emersonlaurentino authored and lariciamota committed Nov 29, 2023
1 parent d766a3a commit 4bac95f
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 24 deletions.
50 changes: 39 additions & 11 deletions packages/api/src/platforms/vtex/clients/commerce/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { SalesChannel } from './types/SalesChannel'
import { MasterDataResponse } from './types/Newsletter'
import type { Address, AddressInput } from './types/Address'
import { DeliveryMode, SelectedAddress } from './types/ShippingData'
import getCookieByName from '../../../../utils/get-cookie-by-name'

type ValueOf<T> = T extends Record<string, infer K> ? K : never

Expand All @@ -29,6 +30,18 @@ const BASE_INIT = {
},
}

const setCheckoutOrderFormOwnershipCookie = (
headers: Headers,
ctx: Context
) => {
if (headers) {
ctx.storage.cookies = `CheckoutOrderFormOwnership=${getCookieByName(
'CheckoutOrderFormOwnership',
headers.get('set-cookie') ?? ''
)}`
}
}

export const VtexCommerce = (
{ account, environment, incrementAddress }: Options,
ctx: Context
Expand Down Expand Up @@ -130,7 +143,8 @@ export const VtexCommerce = (
'content-type': 'application/json',
cookie: ctx.headers.cookie,
},
}
},
(headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
)
},

Expand Down Expand Up @@ -160,7 +174,8 @@ export const VtexCommerce = (

return fetchAPI(
`${base}/api/checkout/pub/orderForm/${id}?${params.toString()}`,
requestInit
requestInit,
(headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
)
},

Expand Down Expand Up @@ -216,7 +231,15 @@ export const VtexCommerce = (

return fetchAPI(
`${base}/api/checkout/pub/orderForm/${id}/items?${params}`,
requestInit
{
...requestInit,
body: JSON.stringify({
orderItems,
noSplitItem: !shouldSplitItem,
}),
method: 'PATCH',
},
(headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
)
},
setCustomData: ({
Expand All @@ -236,7 +259,8 @@ export const VtexCommerce = (
...BASE_INIT,
body: JSON.stringify({ value }),
method: 'PUT',
}
},
(headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
)
},
region: async ({
Expand Down Expand Up @@ -276,14 +300,18 @@ export const VtexCommerce = (
'items',
'profile.id,profile.email,profile.firstName,profile.lastName,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol'
)
return fetchAPI(`${base}/api/sessions?${params.toString()}`, {
method: 'POST',
headers: {
'content-type': 'application/json',
cookie: ctx.headers.cookie,
return fetchAPI(
`${base}/api/sessions?${params.toString()}`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
cookie: ctx.headers.cookie,
},
body: '{}',
},
body: '{}',
})
(headers) => setCheckoutOrderFormOwnershipCookie(headers, ctx)
)
},
subscribeToNewsletter: (data: {
name: string
Expand Down
10 changes: 9 additions & 1 deletion packages/api/src/platforms/vtex/clients/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import packageJson from '../../../../package.json'

const USER_AGENT = `${packageJson.name}@${packageJson.version}`

export const fetchAPI = async (info: RequestInfo, init?: RequestInit) => {
export const fetchAPI = async (
info: RequestInfo,
init?: RequestInit,
getHeaders?: (headers: Headers) => void
) => {
const response = await fetch(info, {
...init,
headers: {
Expand All @@ -13,6 +17,10 @@ export const fetchAPI = async (info: RequestInfo, init?: RequestInit) => {
})

if (response.ok) {
if (getHeaders) {
getHeaders(response.headers)
}

return response.status !== 204 ? response.json() : undefined
}

Expand Down
21 changes: 11 additions & 10 deletions packages/api/src/platforms/vtex/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export interface Context {
locale: string
flags: FeatureFlags
searchArgs?: Omit<SearchArgs, 'type'>
cookies?: string | null
}
headers: Record<string, string>
}
Expand Down Expand Up @@ -92,16 +93,16 @@ const Resolvers = {

export const getContextFactory =
(options: Options) =>
(ctx: any): Context => {
ctx.storage = {
channel: ChannelMarshal.parse(options.channel),
flags: options.flags ?? {},
locale: options.locale,
}
ctx.clients = getClients(options, ctx)
ctx.loaders = getLoaders(options, ctx)

return ctx
(ctx: any): Context => {
ctx.storage = {
channel: ChannelMarshal.parse(options.channel),
flags: options.flags ?? {},
locale: options.locale,
}
ctx.clients = getClients(options, ctx)
ctx.loaders = getLoaders(options, ctx)

return ctx
}

export const getResolvers = (_: Options) => Resolvers
1 change: 1 addition & 0 deletions packages/api/src/platforms/vtex/resolvers/validateCart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ export const validateCart = async (
if (equals(order, updatedOrderForm) && equalMessages) {
return null
}

// Step6: There were changes, convert orderForm to StoreCart
return orderFormToCart(updatedOrderForm, skuLoader)
}
6 changes: 6 additions & 0 deletions packages/api/src/utils/get-cookie-by-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default function getCookieByName(cookiename: string, source: string) {
var cookiestring = RegExp(cookiename + '=[^;]+').exec(source)
return decodeURIComponent(
!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, '') : ''
)
}
4 changes: 4 additions & 0 deletions packages/core/src/pages/api/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ const handler: NextApiHandler = async (request, response) => {
? stringifyCacheControl(extensions.cacheControl)
: 'no-cache, no-store'

if (extensions.cookies && !hasErrors) {
response.setHeader('set-cookie', extensions.cookies)
}

response.setHeader('cache-control', cacheControl)
response.setHeader('content-type', 'application/json')
response.send(JSON.stringify({ data, errors }))
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const execute = async <V extends Maybe<{ [key: string]: unknown }>, D>(
): Promise<{
data: D
errors: unknown[]
extensions: { cacheControl?: CacheControl }
extensions: { cacheControl?: CacheControl; cookies: string | null }
}> => {
const { operationName, variables, query: maybeQuery } = options
const query = maybeQuery ?? persistedQueries.get(operationName)
Expand Down Expand Up @@ -114,6 +114,9 @@ export const execute = async <V extends Maybe<{ [key: string]: unknown }>, D>(
return {
data,
errors,
extensions: { cacheControl: contextValue.cacheControl },
extensions: {
cookies: contextValue.storage.cookies,
cacheControl: contextValue.cacheControl,
},
}
}
3 changes: 3 additions & 0 deletions turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
"dependsOn": [
"@faststore/api#build"
]
},
"dev:server": {
"cache": false
}
}
}

0 comments on commit 4bac95f

Please sign in to comment.