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,
|
||||
}) => {
|
||||
let { orderId, accessToken } = req.query
|
||||
accessToken =
|
||||
typeof accessToken === 'string' ? accessToken.split('; CL_TOKEN=') : ''
|
||||
accessToken = accessToken[accessToken.length - 1]
|
||||
|
||||
const name = 'CL_TOKEN' + "=";
|
||||
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()
|
||||
if (orderId && accessToken) {
|
||||
const clOrder = await Order.withCredentials({ endpoint, accessToken })
|
||||
.includes('lineItems')
|
||||
.find(orderId as string, { rawResponse: true })
|
||||
const checkoutUrl = clOrder.data.attributes.checkout_url
|
||||
console.log(checkoutUrl)
|
||||
|
||||
if (checkoutUrl) {
|
||||
res.redirect(checkoutUrl)
|
||||
|
@ -9,7 +9,7 @@ export default function getPageOperation() {
|
||||
function getPage(): Promise<GetPageResult> {
|
||||
return Promise.resolve({
|
||||
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 type { GraphQLFetcher } from '@commerce/api'
|
||||
import type { LocalConfig } from '../index'
|
||||
import type { CommercelayerConfig } from '../index'
|
||||
import fetch from './fetch'
|
||||
|
||||
const fetchGraphqlApi: (getConfig: () => LocalConfig) => GraphQLFetcher =
|
||||
const fetchGraphqlApi: (getConfig: () => CommercelayerConfig) => GraphQLFetcher =
|
||||
(getConfig) =>
|
||||
async (query: string, { variables, preview } = {}, fetchOptions) => {
|
||||
debugger
|
||||
|
@ -1,15 +1,18 @@
|
||||
import { useCallback } from 'react'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import { MutationHook } from '@commerce/utils/types'
|
||||
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
||||
import { CommerceError } from '@commerce/utils/errors'
|
||||
import { getCustomerToken } from '@commercelayer/js-auth'
|
||||
import { ENDPOINT, CLIENTID, SCOPE } from '../const'
|
||||
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 const handler: MutationHook<any> = {
|
||||
fetchOptions: {
|
||||
url: `${ENDPOINT}/api/customers`,
|
||||
url: '',
|
||||
},
|
||||
async fetcher({ input: { email, password }, options, fetch }) {
|
||||
if (!(email && password)) {
|
||||
@ -24,10 +27,11 @@ export const handler: MutationHook<any> = {
|
||||
clientId: CLIENTID,
|
||||
scope: SCOPE,
|
||||
},
|
||||
{ username: email, password }
|
||||
{ username: email, password: password }
|
||||
)
|
||||
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.`)
|
||||
return token
|
||||
} catch (error) {
|
||||
@ -37,11 +41,17 @@ export const handler: MutationHook<any> = {
|
||||
}
|
||||
},
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
return async function login(input) {
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
const { revalidate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function login(input) {
|
||||
const data = await fetch({ input })
|
||||
await revalidate()
|
||||
return data
|
||||
}
|
||||
},
|
||||
},
|
||||
[fetch, revalidate]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -3,7 +3,10 @@ import useCustomer from '../customer/use-customer'
|
||||
import { MutationHook } from '@commerce/utils/types'
|
||||
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
||||
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>
|
||||
|
||||
@ -11,7 +14,7 @@ export const handler: MutationHook<any> = {
|
||||
fetchOptions: {
|
||||
query: 'customers',
|
||||
url: `${ENDPOINT}/api/customers`,
|
||||
method: 'POST'
|
||||
method: 'POST',
|
||||
},
|
||||
async fetcher({ input: { email, password }, options, fetch }) {
|
||||
if (!(email && password)) {
|
||||
@ -28,6 +31,17 @@ export const handler: MutationHook<any> = {
|
||||
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.`)
|
||||
return data
|
||||
} catch (error) {
|
||||
@ -39,9 +53,15 @@ export const handler: MutationHook<any> = {
|
||||
useHook:
|
||||
({ fetch }) =>
|
||||
() => {
|
||||
return async function signup(input) {
|
||||
const data = await fetch({ input })
|
||||
return data
|
||||
}
|
||||
const { revalidate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function signup(input) {
|
||||
const data = await fetch({ input })
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fetch, revalidate]
|
||||
)
|
||||
},
|
||||
}
|
||||
|
@ -11,14 +11,14 @@ export const handler: MutationHook<any> = {
|
||||
query: '',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {
|
||||
const localOrderId = localStorage.getItem('CL_ORDER')
|
||||
const localOrderId = localStorage.getItem('CL_ORDER_ID')
|
||||
const credentials = getCredentials()
|
||||
const orderId =
|
||||
localOrderId ||
|
||||
(credentials.accessToken &&
|
||||
(await Order.withCredentials(credentials).create({})).id)
|
||||
if (orderId && input.sizeId) {
|
||||
!localOrderId && localStorage.setItem('CL_ORDER', orderId)
|
||||
!localOrderId && localStorage.setItem('CL_ORDER_ID', orderId)
|
||||
const lineItem = await LineItem.withCredentials(credentials).create(
|
||||
{
|
||||
skuCode: input.sizeId,
|
||||
|
@ -12,7 +12,7 @@ export const handler: SWRHook<any> = {
|
||||
query: '',
|
||||
},
|
||||
async fetcher() {
|
||||
const id = localStorage.getItem('CL_ORDER') || ''
|
||||
const id = localStorage.getItem('CL_ORDER_ID') || ''
|
||||
const credentials = getCredentials()
|
||||
if (id && credentials.accessToken) {
|
||||
const clOrder = await Order.withCredentials(credentials)
|
||||
|
@ -12,7 +12,7 @@ export const handler: MutationHook<any> = {
|
||||
},
|
||||
async fetcher({ input: { id } }) {
|
||||
const credentials = getCredentials()
|
||||
const orderId = localStorage.getItem('CL_ORDER')
|
||||
const orderId = localStorage.getItem('CL_ORDER_ID')
|
||||
if (orderId && id) {
|
||||
await LineItem.build({ id }).withCredentials(credentials).destroy()
|
||||
return {}
|
||||
|
@ -12,7 +12,7 @@ export const handler: MutationHook<any> = {
|
||||
},
|
||||
async fetcher({ input: { item, quantity } }) {
|
||||
const credentials = getCredentials()
|
||||
const orderId = localStorage.getItem('CL_ORDER')
|
||||
const orderId = localStorage.getItem('CL_ORDER_ID')
|
||||
if (orderId && item.id) {
|
||||
const lineItem = (await LineItem.build({
|
||||
id: item.id,
|
||||
|
@ -1,15 +1,37 @@
|
||||
import { SWRHook } from '@commerce/utils/types'
|
||||
import { CustomerHook } from '@commerce/types/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 const handler: SWRHook<any> = {
|
||||
|
||||
const customerId = Cookies.get('CL_CUSTOMER_ID')
|
||||
|
||||
export const handler: SWRHook<CustomerHook> = {
|
||||
fetchOptions: {
|
||||
query: '',
|
||||
url: `${ENDPOINT}/api/customers/${customerId}`,
|
||||
method: 'GET',
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {},
|
||||
useHook: () => () => {
|
||||
return async function addItem() {
|
||||
return {}
|
||||
}
|
||||
async fetcher({ input, options, fetch }) {
|
||||
const data = await fetch({...options})
|
||||
|
||||
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 handleFetchResponse from './utils/handle-fetch-response'
|
||||
import { ENDPOINT, CLIENTID, SCOPE } from './const'
|
||||
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 }) => {
|
||||
const token = await getSalesChannelToken({
|
||||
@ -9,21 +10,37 @@ export const fetcher: Fetcher = async ({ url, method, variables, query }) => {
|
||||
clientId: CLIENTID,
|
||||
scope: SCOPE,
|
||||
})
|
||||
const customerToken = Cookies.get('CL_CUSTOMER_TOKEN')
|
||||
|
||||
return handleFetchResponse(
|
||||
await fetch(url!, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/vnd.api+json',
|
||||
Authorization: `Bearer ${token.accessToken}`,
|
||||
'Content-Type': 'application/vnd.api+json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
data: {
|
||||
type: query,
|
||||
attributes: variables,
|
||||
if (method == 'POST') {
|
||||
return handleFetchResponse(
|
||||
await fetch(url!, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/vnd.api+json',
|
||||
Authorization: `Bearer ${token.accessToken}`,
|
||||
'Content-Type': 'application/vnd.api+json',
|
||||
},
|
||||
}),
|
||||
})
|
||||
)
|
||||
body: JSON.stringify({
|
||||
data: {
|
||||
type: query,
|
||||
attributes: variables,
|
||||
},
|
||||
}),
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
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