mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 07:26:59 +00:00
refactor: add useCustomer and refactor Auth
This commit is contained in:
parent
ce0bcfe33d
commit
8f2b7695e6
@ -7,16 +7,20 @@ const checkout: CheckoutEndpoint['handlers']['checkout'] = async ({
|
|||||||
res,
|
res,
|
||||||
}) => {
|
}) => {
|
||||||
let { orderId, accessToken } = req.query
|
let { orderId, accessToken } = req.query
|
||||||
accessToken =
|
|
||||||
typeof accessToken === 'string' ? accessToken.split('; CL_TOKEN=') : ''
|
const name = 'CL_TOKEN' + "=";
|
||||||
accessToken = accessToken[accessToken.length - 1]
|
const cookiesArr = decodeURIComponent(accessToken = typeof accessToken === 'string' ? accessToken : '').split('; ');
|
||||||
|
accessToken = typeof accessToken
|
||||||
|
cookiesArr.forEach(val => {
|
||||||
|
if (val.indexOf(name) === 0) accessToken = val.substring(name.length)
|
||||||
|
})
|
||||||
|
|
||||||
const { endpoint } = getCredentials()
|
const { endpoint } = getCredentials()
|
||||||
if (orderId && accessToken) {
|
if (orderId && accessToken) {
|
||||||
const clOrder = await Order.withCredentials({ endpoint, accessToken })
|
const clOrder = await Order.withCredentials({ endpoint, accessToken })
|
||||||
.includes('lineItems')
|
.includes('lineItems')
|
||||||
.find(orderId as string, { rawResponse: true })
|
.find(orderId as string, { rawResponse: true })
|
||||||
const checkoutUrl = clOrder.data.attributes.checkout_url
|
const checkoutUrl = clOrder.data.attributes.checkout_url
|
||||||
console.log(checkoutUrl)
|
|
||||||
|
|
||||||
if (checkoutUrl) {
|
if (checkoutUrl) {
|
||||||
res.redirect(checkoutUrl)
|
res.redirect(checkoutUrl)
|
||||||
|
@ -9,7 +9,7 @@ export default function getPageOperation() {
|
|||||||
function getPage(): Promise<GetPageResult> {
|
function getPage(): Promise<GetPageResult> {
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
page: {
|
page: {
|
||||||
body: `<script>location.href = '/api/checkout/?orderId=' + localStorage.getItem('CL_ORDER') + '&accessToken=' + document.cookie</script>`,
|
body: `<script>location.href = '/api/checkout/?orderId=' + localStorage.getItem('CL_ORDER_ID') + '&accessToken=' + document.cookie</script>`,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import { FetcherError } from '@commerce/utils/errors'
|
import { FetcherError } from '@commerce/utils/errors'
|
||||||
import type { GraphQLFetcher } from '@commerce/api'
|
import type { GraphQLFetcher } from '@commerce/api'
|
||||||
import type { LocalConfig } from '../index'
|
import type { CommercelayerConfig } from '../index'
|
||||||
import fetch from './fetch'
|
import fetch from './fetch'
|
||||||
|
|
||||||
const fetchGraphqlApi: (getConfig: () => LocalConfig) => GraphQLFetcher =
|
const fetchGraphqlApi: (getConfig: () => CommercelayerConfig) => GraphQLFetcher =
|
||||||
(getConfig) =>
|
(getConfig) =>
|
||||||
async (query: string, { variables, preview } = {}, fetchOptions) => {
|
async (query: string, { variables, preview } = {}, fetchOptions) => {
|
||||||
debugger
|
debugger
|
||||||
|
@ -1,15 +1,18 @@
|
|||||||
|
import { useCallback } from 'react'
|
||||||
|
import useCustomer from '../customer/use-customer'
|
||||||
import { MutationHook } from '@commerce/utils/types'
|
import { MutationHook } from '@commerce/utils/types'
|
||||||
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
||||||
import { CommerceError } from '@commerce/utils/errors'
|
import { CommerceError } from '@commerce/utils/errors'
|
||||||
import { getCustomerToken } from '@commercelayer/js-auth'
|
import { getCustomerToken } from '@commercelayer/js-auth'
|
||||||
import { ENDPOINT, CLIENTID, SCOPE } from '../const'
|
|
||||||
import setCookie from '@framework/api/utils/cookies'
|
import setCookie from '@framework/api/utils/cookies'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
|
import { ENDPOINT, CLIENTID, SCOPE } from '../const'
|
||||||
|
|
||||||
export default useLogin as UseLogin<typeof handler>
|
export default useLogin as UseLogin<typeof handler>
|
||||||
|
|
||||||
export const handler: MutationHook<any> = {
|
export const handler: MutationHook<any> = {
|
||||||
fetchOptions: {
|
fetchOptions: {
|
||||||
url: `${ENDPOINT}/api/customers`,
|
url: '',
|
||||||
},
|
},
|
||||||
async fetcher({ input: { email, password }, options, fetch }) {
|
async fetcher({ input: { email, password }, options, fetch }) {
|
||||||
if (!(email && password)) {
|
if (!(email && password)) {
|
||||||
@ -24,10 +27,11 @@ export const handler: MutationHook<any> = {
|
|||||||
clientId: CLIENTID,
|
clientId: CLIENTID,
|
||||||
scope: SCOPE,
|
scope: SCOPE,
|
||||||
},
|
},
|
||||||
{ username: email, password }
|
{ username: email, password: password }
|
||||||
)
|
)
|
||||||
token &&
|
token &&
|
||||||
setCookie('CL_TOKEN', token.accessToken, { expires: token.expires })
|
setCookie('CL_CUSTOMER_TOKEN', token.accessToken, { expires: token.expires })
|
||||||
|
Cookies.set('CL_CUSTOMER_ID', token.data.owner_id as string)
|
||||||
alert(`User "${email}" has successfully been logged in.`)
|
alert(`User "${email}" has successfully been logged in.`)
|
||||||
return token
|
return token
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -39,9 +43,15 @@ export const handler: MutationHook<any> = {
|
|||||||
useHook:
|
useHook:
|
||||||
({ fetch }) =>
|
({ fetch }) =>
|
||||||
() => {
|
() => {
|
||||||
return async function login(input) {
|
const { revalidate } = useCustomer()
|
||||||
|
|
||||||
|
return useCallback(
|
||||||
|
async function login(input) {
|
||||||
const data = await fetch({ input })
|
const data = await fetch({ input })
|
||||||
|
await revalidate()
|
||||||
return data
|
return data
|
||||||
}
|
},
|
||||||
|
[fetch, revalidate]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,10 @@ import useCustomer from '../customer/use-customer'
|
|||||||
import { MutationHook } from '@commerce/utils/types'
|
import { MutationHook } from '@commerce/utils/types'
|
||||||
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
||||||
import { CommerceError } from '@commerce/utils/errors'
|
import { CommerceError } from '@commerce/utils/errors'
|
||||||
import {ENDPOINT} from '../const'
|
import { getCustomerToken } from '@commercelayer/js-auth'
|
||||||
|
import setCookie from '@framework/api/utils/cookies'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
|
import { ENDPOINT, CLIENTID, SCOPE } from '../const'
|
||||||
|
|
||||||
export default useSignup as UseSignup<typeof handler>
|
export default useSignup as UseSignup<typeof handler>
|
||||||
|
|
||||||
@ -11,7 +14,7 @@ export const handler: MutationHook<any> = {
|
|||||||
fetchOptions: {
|
fetchOptions: {
|
||||||
query: 'customers',
|
query: 'customers',
|
||||||
url: `${ENDPOINT}/api/customers`,
|
url: `${ENDPOINT}/api/customers`,
|
||||||
method: 'POST'
|
method: 'POST',
|
||||||
},
|
},
|
||||||
async fetcher({ input: { email, password }, options, fetch }) {
|
async fetcher({ input: { email, password }, options, fetch }) {
|
||||||
if (!(email && password)) {
|
if (!(email && password)) {
|
||||||
@ -28,6 +31,17 @@ export const handler: MutationHook<any> = {
|
|||||||
password,
|
password,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
const token = await getCustomerToken(
|
||||||
|
{
|
||||||
|
endpoint: ENDPOINT,
|
||||||
|
clientId: CLIENTID,
|
||||||
|
scope: SCOPE,
|
||||||
|
},
|
||||||
|
{ username: email, password: password }
|
||||||
|
)
|
||||||
|
token &&
|
||||||
|
setCookie('CL_CUSTOMER_TOKEN', token.accessToken, { expires: token.expires })
|
||||||
|
Cookies.set('CL_CUSTOMER_ID', data.id)
|
||||||
alert(`User "${email}" has successfully been created.`)
|
alert(`User "${email}" has successfully been created.`)
|
||||||
return data
|
return data
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -39,9 +53,15 @@ export const handler: MutationHook<any> = {
|
|||||||
useHook:
|
useHook:
|
||||||
({ fetch }) =>
|
({ fetch }) =>
|
||||||
() => {
|
() => {
|
||||||
return async function signup(input) {
|
const { revalidate } = useCustomer()
|
||||||
|
|
||||||
|
return useCallback(
|
||||||
|
async function signup(input) {
|
||||||
const data = await fetch({ input })
|
const data = await fetch({ input })
|
||||||
|
await revalidate()
|
||||||
return data
|
return data
|
||||||
}
|
},
|
||||||
|
[fetch, revalidate]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -11,14 +11,14 @@ export const handler: MutationHook<any> = {
|
|||||||
query: '',
|
query: '',
|
||||||
},
|
},
|
||||||
async fetcher({ input, options, fetch }) {
|
async fetcher({ input, options, fetch }) {
|
||||||
const localOrderId = localStorage.getItem('CL_ORDER')
|
const localOrderId = localStorage.getItem('CL_ORDER_ID')
|
||||||
const credentials = getCredentials()
|
const credentials = getCredentials()
|
||||||
const orderId =
|
const orderId =
|
||||||
localOrderId ||
|
localOrderId ||
|
||||||
(credentials.accessToken &&
|
(credentials.accessToken &&
|
||||||
(await Order.withCredentials(credentials).create({})).id)
|
(await Order.withCredentials(credentials).create({})).id)
|
||||||
if (orderId && input.sizeId) {
|
if (orderId && input.sizeId) {
|
||||||
!localOrderId && localStorage.setItem('CL_ORDER', orderId)
|
!localOrderId && localStorage.setItem('CL_ORDER_ID', orderId)
|
||||||
const lineItem = await LineItem.withCredentials(credentials).create(
|
const lineItem = await LineItem.withCredentials(credentials).create(
|
||||||
{
|
{
|
||||||
skuCode: input.sizeId,
|
skuCode: input.sizeId,
|
||||||
|
@ -12,7 +12,7 @@ export const handler: SWRHook<any> = {
|
|||||||
query: '',
|
query: '',
|
||||||
},
|
},
|
||||||
async fetcher() {
|
async fetcher() {
|
||||||
const id = localStorage.getItem('CL_ORDER') || ''
|
const id = localStorage.getItem('CL_ORDER_ID') || ''
|
||||||
const credentials = getCredentials()
|
const credentials = getCredentials()
|
||||||
if (id && credentials.accessToken) {
|
if (id && credentials.accessToken) {
|
||||||
const clOrder = await Order.withCredentials(credentials)
|
const clOrder = await Order.withCredentials(credentials)
|
||||||
|
@ -12,7 +12,7 @@ export const handler: MutationHook<any> = {
|
|||||||
},
|
},
|
||||||
async fetcher({ input: { id } }) {
|
async fetcher({ input: { id } }) {
|
||||||
const credentials = getCredentials()
|
const credentials = getCredentials()
|
||||||
const orderId = localStorage.getItem('CL_ORDER')
|
const orderId = localStorage.getItem('CL_ORDER_ID')
|
||||||
if (orderId && id) {
|
if (orderId && id) {
|
||||||
await LineItem.build({ id }).withCredentials(credentials).destroy()
|
await LineItem.build({ id }).withCredentials(credentials).destroy()
|
||||||
return {}
|
return {}
|
||||||
|
@ -12,7 +12,7 @@ export const handler: MutationHook<any> = {
|
|||||||
},
|
},
|
||||||
async fetcher({ input: { item, quantity } }) {
|
async fetcher({ input: { item, quantity } }) {
|
||||||
const credentials = getCredentials()
|
const credentials = getCredentials()
|
||||||
const orderId = localStorage.getItem('CL_ORDER')
|
const orderId = localStorage.getItem('CL_ORDER_ID')
|
||||||
if (orderId && item.id) {
|
if (orderId && item.id) {
|
||||||
const lineItem = (await LineItem.build({
|
const lineItem = (await LineItem.build({
|
||||||
id: item.id,
|
id: item.id,
|
||||||
|
@ -1,15 +1,37 @@
|
|||||||
import { SWRHook } from '@commerce/utils/types'
|
import { SWRHook } from '@commerce/utils/types'
|
||||||
|
import { CustomerHook } from '@commerce/types/customer'
|
||||||
import useCustomer, { UseCustomer } from '@commerce/customer/use-customer'
|
import useCustomer, { UseCustomer } from '@commerce/customer/use-customer'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
|
import { ENDPOINT } from '../const'
|
||||||
|
|
||||||
export default useCustomer as UseCustomer<typeof handler>
|
export default useCustomer as UseCustomer<typeof handler>
|
||||||
export const handler: SWRHook<any> = {
|
|
||||||
|
const customerId = Cookies.get('CL_CUSTOMER_ID')
|
||||||
|
|
||||||
|
export const handler: SWRHook<CustomerHook> = {
|
||||||
fetchOptions: {
|
fetchOptions: {
|
||||||
query: '',
|
url: `${ENDPOINT}/api/customers/${customerId}`,
|
||||||
|
method: 'GET',
|
||||||
},
|
},
|
||||||
async fetcher({ input, options, fetch }) {},
|
async fetcher({ input, options, fetch }) {
|
||||||
useHook: () => () => {
|
const data = await fetch({...options})
|
||||||
return async function addItem() {
|
|
||||||
return {}
|
return data ? ({
|
||||||
}
|
firstName: '',
|
||||||
|
lastName: '',
|
||||||
|
email: data.attributes.email ?? '',
|
||||||
|
} as any)
|
||||||
|
: null
|
||||||
|
},
|
||||||
|
|
||||||
|
useHook:
|
||||||
|
({ useData }) =>
|
||||||
|
(input) => {
|
||||||
|
return useData({
|
||||||
|
swrOptions: {
|
||||||
|
revalidateOnFocus: false,
|
||||||
|
...input?.swrOptions,
|
||||||
|
},
|
||||||
|
})
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
import { Fetcher } from '@commerce/utils/types'
|
import { Fetcher } from '@commerce/utils/types'
|
||||||
import handleFetchResponse from './utils/handle-fetch-response'
|
import handleFetchResponse from './utils/handle-fetch-response'
|
||||||
import { ENDPOINT, CLIENTID, SCOPE } from './const'
|
|
||||||
import { getSalesChannelToken } from '@commercelayer/js-auth'
|
import { getSalesChannelToken } from '@commercelayer/js-auth'
|
||||||
|
import Cookies from 'js-cookie'
|
||||||
|
import { ENDPOINT, CLIENTID, SCOPE } from './const'
|
||||||
|
|
||||||
export const fetcher: Fetcher = async ({ url, method, variables, query }) => {
|
export const fetcher: Fetcher = async ({ url, method, variables, query }) => {
|
||||||
const token = await getSalesChannelToken({
|
const token = await getSalesChannelToken({
|
||||||
@ -9,7 +10,9 @@ export const fetcher: Fetcher = async ({ url, method, variables, query }) => {
|
|||||||
clientId: CLIENTID,
|
clientId: CLIENTID,
|
||||||
scope: SCOPE,
|
scope: SCOPE,
|
||||||
})
|
})
|
||||||
|
const customerToken = Cookies.get('CL_CUSTOMER_TOKEN')
|
||||||
|
|
||||||
|
if (method == 'POST') {
|
||||||
return handleFetchResponse(
|
return handleFetchResponse(
|
||||||
await fetch(url!, {
|
await fetch(url!, {
|
||||||
method,
|
method,
|
||||||
@ -27,3 +30,17 @@ export const fetcher: Fetcher = async ({ url, method, variables, query }) => {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (method == 'GET') {
|
||||||
|
return handleFetchResponse(
|
||||||
|
await fetch(url!, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/vnd.api+json',
|
||||||
|
Authorization: `Bearer ${customerToken}`,
|
||||||
|
'Content-Type': 'application/vnd.api+json',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user