-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathhelpers.ts
More file actions
72 lines (68 loc) · 2.36 KB
/
helpers.ts
File metadata and controls
72 lines (68 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Copyright (c) 2024, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import Auth from '../auth'
import {CommerceApiProviderProps} from '../provider'
import {Logger} from '../types'
import {OptionalCustomEndpointClientConfig, TMutationVariables} from './types'
/**
* A helper function for handling bad responses from SCAPI when an invalid access token is used.
*
* Re-throws the error if it is not caused by an invalid access token
* @param error - the error
* @returns a new guest access token
*/
export const handleInvalidToken = async (error: any, auth: Auth, logger: Logger) => {
if (error?.response?.status !== 401) {
throw error
}
const response = await error?.response?.json()
if (response?.detail !== 'Customer credentials changed after token was issued.') {
throw error
}
logger.info('Login was invalidated. Clearing login state.')
return await auth.logout()
}
/**
* A helper function for preparing a call to the SCAPI custom API endpoint
*/
export const generateCustomEndpointOptions = (
options: OptionalCustomEndpointClientConfig,
config: Omit<CommerceApiProviderProps, 'children'>,
access_token: string,
args?: TMutationVariables
) => {
const globalHeaders = config.headers || {}
const globalClientConfig = {
parameters: {
clientId: config.clientId,
siteId: config.siteId,
organizationId: config.organizationId,
shortCode: config.shortCode
},
proxy: config.proxy,
throwOnBadResponse: true
}
return {
...options,
options: {
...options.options,
method: options.options?.method || 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
// Note the order of the following de-structured objects is important.
// Priority in ascending order: global config < query/mutation config < mutate func args
...globalHeaders,
...options.options?.headers,
...(args?.headers ? args.headers : {})
}
},
clientConfig: {
...globalClientConfig,
...(options.clientConfig || {})
}
}
}