1
1
import type {
2
+ AppModuleName ,
3
+ ListPaymentsParams ,
2
4
ListPaymentsResponse ,
5
+ CalculateShippingParams ,
3
6
CalculateShippingResponse ,
7
+ ApplyDiscountParams ,
4
8
ApplyDiscountResponse ,
5
9
} from '@cloudcommerce/types' ;
6
10
import { reactive , computed } from 'vue' ;
@@ -32,6 +36,36 @@ loadingGlobalInfoPreset.then((modulesInfoPreset) => {
32
36
Object . assign ( modulesInfo , modulesInfoPreset ) ;
33
37
} ) ;
34
38
39
+ export type ModuleName = Exclude < AppModuleName , 'create_transaction' > ;
40
+
41
+ export type ModulePayload < M extends ModuleName > =
42
+ M extends 'list_payments' ? ListPaymentsParams :
43
+ M extends 'calculate_shipping' ? CalculateShippingParams :
44
+ M extends 'apply_discount' ? ApplyDiscountParams :
45
+ Record < string , any > ;
46
+
47
+ type FetchModule = < M extends ModuleName > (
48
+ modName : M ,
49
+ reqOptions ?: {
50
+ method : 'get' ,
51
+ params ?: Record < string , string > ,
52
+ } | {
53
+ method : 'post' ,
54
+ body : ModulePayload < M > ,
55
+ } ,
56
+ ) => Promise < Response & {
57
+ json < P = ModulePayload < M > > ( ) : Promise < P > ,
58
+ } > ;
59
+
60
+ export const fetchModule : FetchModule = ( modName , reqOptions ) => {
61
+ const { hostname } = window . location ;
62
+ const { domain } = globalThis . $storefront . settings ;
63
+ const modulesBaseUri = hostname !== 'localhost' && hostname !== '127.0.0.1'
64
+ ? `https://${ domain } /_api/modules/`
65
+ : '/_api/modules/' ;
66
+ return afetch ( `${ modulesBaseUri } ${ modName } ` , reqOptions ) ;
67
+ } ;
68
+
35
69
if ( ! import . meta. env . SSR ) {
36
70
const storageKey = 'MODULES_INFO' ;
37
71
const sessionJson = sessionStorage . getItem ( storageKey ) ;
@@ -50,8 +84,8 @@ if (!import.meta.env.SSR) {
50
84
}
51
85
52
86
const fetchInfo = ( ) => {
53
- const modulesToFetch : { modName : string , reqOptions ?: Record < string , any > } [ ] = [ ] ;
54
- [ 'list_payments' , 'calculate_shipping' ] . forEach ( ( modName ) => {
87
+ const modulesToFetch : { modName : ModuleName , reqOptions ?: any } [ ] = [ ] ;
88
+ ( [ 'list_payments' , 'calculate_shipping' ] as const ) . forEach ( ( modName ) => {
55
89
if ( ! Object . keys ( modulesInfo [ modName ] ) . length ) {
56
90
modulesToFetch . push ( { modName } ) ;
57
91
}
@@ -67,12 +101,7 @@ if (!import.meta.env.SSR) {
67
101
}
68
102
69
103
modulesToFetch . forEach ( ( { modName, reqOptions } ) => {
70
- const { hostname } = window . location ;
71
- const { domain } = globalThis . $storefront . settings ;
72
- const modulesBaseUri = hostname !== 'localhost' && hostname !== '127.0.0.1'
73
- ? `https://${ domain } /_api/modules/`
74
- : '/_api/modules/' ;
75
- afetch ( `${ modulesBaseUri } ${ modName } ` , reqOptions )
104
+ fetchModule ( modName , reqOptions )
76
105
. then ( async ( response ) => {
77
106
if ( response . ok ) {
78
107
const modInfo = { } ;
0 commit comments