@myparcel-dev/pdk-admin 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/actions/composables/mutations/orders/useExportOrdersMutation.d.ts +1 -1
- package/dist/composables/language/useLanguage.d.ts +6 -0
- package/dist/pdk/PdkAdmin.d.ts +26 -2
- package/dist/pdk/boot.d.ts +5 -0
- package/dist/sdk/index.d.ts +1 -0
- package/dist/sdk/requestHeaders.d.ts +10 -0
- package/dist/services/mutations/getModalMutationOptions.d.ts +7 -1
- package/dist/services/mutations/index.d.ts +1 -0
- package/dist/services/mutations/modalMutationToken.d.ts +16 -0
- package/dist/stores/useModalStore.d.ts +9 -1
- package/dist/types/admin.types.d.ts +10 -0
- package/dist/types/configuration.types.d.ts +12 -0
- package/package.json +2 -2
- package/src/actions/composables/mutations/orders/useExportOrdersMutation.spec.ts +75 -0
- package/src/actions/composables/mutations/orders/useExportOrdersMutation.ts +17 -6
- package/src/components/common/TabNavigation.spec.ts +78 -0
- package/src/components/common/TabNavigation.vue +7 -5
- package/src/composables/language/resetLanguageCache.spec.ts +24 -0
- package/src/composables/language/useLanguage.ts +13 -0
- package/src/pdk/PdkAdmin.spec.ts +97 -0
- package/src/pdk/PdkAdmin.ts +63 -7
- package/src/pdk/boot.ts +13 -3
- package/src/pdk/createPdkAdmin.spec.ts +75 -0
- package/src/pdk/createPdkAdmin.ts +2 -0
- package/src/pdk/instance/plugins/createStorePlugin.spec.ts +44 -0
- package/src/pdk/instance/plugins/createStorePlugin.ts +12 -7
- package/src/pdk/instance/plugins/createVueQueryPlugin.spec.ts +29 -0
- package/src/pdk/instance/plugins/createVueQueryPlugin.ts +7 -7
- package/src/pdk/setupAdminApp.ts +3 -0
- package/src/sdk/composables/usePdkAdminApi.ts +3 -0
- package/src/sdk/index.ts +1 -0
- package/src/sdk/requestHeaders.spec.ts +54 -0
- package/src/sdk/requestHeaders.ts +36 -0
- package/src/services/mutations/getModalMutationOptions.spec.ts +59 -0
- package/src/services/mutations/getModalMutationOptions.ts +23 -15
- package/src/services/mutations/index.ts +1 -0
- package/src/services/mutations/modalMutationToken.ts +27 -0
- package/src/stores/useModalStore.spec.ts +33 -0
- package/src/stores/useModalStore.ts +13 -1
- package/src/types/admin.types.ts +12 -0
- package/src/types/configuration.types.ts +14 -0
package/src/pdk/PdkAdmin.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/naming-convention */
|
|
2
2
|
|
|
3
3
|
import {type App, createApp} from 'vue';
|
|
4
|
+
import {createPinia} from 'pinia';
|
|
4
5
|
import {type AdminAppConfig, type AdminConfiguration, type AdminContextObject} from '../types';
|
|
5
6
|
import {INJECT_GLOBAL_PDK_ADMIN} from '../symbols';
|
|
6
7
|
import {createLogger, getElementContext} from '../services';
|
|
7
8
|
import {AdminView} from '../data';
|
|
8
9
|
import {setupAdminApp} from './setupAdminApp';
|
|
9
10
|
import {renderViewComponent} from './renderMap';
|
|
11
|
+
import {createQueryClient} from './instance/createQueryClient';
|
|
10
12
|
|
|
11
13
|
export class PdkAdmin {
|
|
12
14
|
public readonly config: AdminConfiguration;
|
|
@@ -14,6 +16,16 @@ export class PdkAdmin {
|
|
|
14
16
|
|
|
15
17
|
public readonly renderedComponents: string[] = [];
|
|
16
18
|
|
|
19
|
+
/**
|
|
20
|
+
* One store and one query client per instance, shared by its apps. A page that
|
|
21
|
+
* creates a new instance after unmounting the apps of the previous one (for
|
|
22
|
+
* example a single-page admin) then starts without stale queries.
|
|
23
|
+
*/
|
|
24
|
+
protected readonly store = createPinia();
|
|
25
|
+
protected readonly queryClient = createQueryClient();
|
|
26
|
+
|
|
27
|
+
private readonly disposers: (() => void)[] = [];
|
|
28
|
+
|
|
17
29
|
public constructor(config: AdminConfiguration, context: AdminContextObject) {
|
|
18
30
|
config.beforeInitialize?.(config, context);
|
|
19
31
|
|
|
@@ -24,9 +36,32 @@ export class PdkAdmin {
|
|
|
24
36
|
}
|
|
25
37
|
|
|
26
38
|
/**
|
|
27
|
-
*
|
|
39
|
+
* Register cleanup work for dispose().
|
|
28
40
|
*/
|
|
29
|
-
public
|
|
41
|
+
public onDispose(disposer: () => void): void {
|
|
42
|
+
this.disposers.push(disposer);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Stop this instance, for example when a single-page app leaves the page.
|
|
47
|
+
* Unmount the apps that render() returned first. Safe to call twice.
|
|
48
|
+
*
|
|
49
|
+
* createPdkAdmin() reads the context from the boot element once. To create
|
|
50
|
+
* the next instance, render a new boot element.
|
|
51
|
+
*
|
|
52
|
+
* The cached queries go at once. A request that is still running reports to
|
|
53
|
+
* the admin on screen when it finishes.
|
|
54
|
+
*/
|
|
55
|
+
public dispose(): void {
|
|
56
|
+
this.disposers.splice(0).forEach((disposer) => disposer());
|
|
57
|
+
this.queryClient.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Render a view in the given selector. Returns the app, so the caller can
|
|
62
|
+
* unmount it, or undefined when mounting failed.
|
|
63
|
+
*/
|
|
64
|
+
public async render(view: AdminView, selector: string): Promise<App | undefined> {
|
|
30
65
|
const config: AdminConfiguration = {...this.config};
|
|
31
66
|
const context: AdminContextObject = {...this.context, ...getElementContext(selector)};
|
|
32
67
|
|
|
@@ -35,16 +70,37 @@ export class PdkAdmin {
|
|
|
35
70
|
|
|
36
71
|
logger.debug(`Rendering "${view}" in "${selector}"`);
|
|
37
72
|
|
|
38
|
-
const app = await this.createApp(view, {
|
|
73
|
+
const app = await this.createApp(view, {
|
|
74
|
+
appName,
|
|
75
|
+
config,
|
|
76
|
+
context,
|
|
77
|
+
logger,
|
|
78
|
+
view,
|
|
79
|
+
store: this.store,
|
|
80
|
+
queryClient: this.queryClient,
|
|
81
|
+
});
|
|
39
82
|
|
|
40
83
|
try {
|
|
41
|
-
app.mount(selector)
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
84
|
+
if (!app.mount(selector)) {
|
|
85
|
+
logger.error(`Element "${selector}" not found`);
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
45
88
|
} catch (e) {
|
|
46
89
|
logger.error('Error mounting app', e);
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
this.renderedComponents.push(view);
|
|
94
|
+
logger.debug(`Rendered in ${selector}`);
|
|
95
|
+
|
|
96
|
+
// The app is mounted now, so return it even when the hook fails: the caller needs it to unmount.
|
|
97
|
+
try {
|
|
98
|
+
config?.onRendered?.(config);
|
|
99
|
+
} catch (e) {
|
|
100
|
+
logger.error('Error in the onRendered hook', e);
|
|
47
101
|
}
|
|
102
|
+
|
|
103
|
+
return app;
|
|
48
104
|
}
|
|
49
105
|
|
|
50
106
|
protected async createApp(view: AdminView, appConfig: AdminAppConfig): Promise<App> {
|
package/src/pdk/boot.ts
CHANGED
|
@@ -3,12 +3,22 @@ import {globalLogger} from '../services';
|
|
|
3
3
|
import {sendBootEvent} from './sendBootEvent';
|
|
4
4
|
import {type PdkAdmin} from './PdkAdmin';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Sends the boot event now and again on every ping, until the instance is
|
|
8
|
+
* disposed. The listener and its cleanup exist before the first event, so a
|
|
9
|
+
* handler of that event can already dispose the instance.
|
|
10
|
+
*/
|
|
6
11
|
export const boot = (pdkAdmin: PdkAdmin, context: AdminContextObject): void => {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
document.addEventListener(context.global.eventPing, () => {
|
|
12
|
+
const onPing = () => {
|
|
10
13
|
sendBootEvent(pdkAdmin, context);
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
document.addEventListener(context.global.eventPing, onPing);
|
|
17
|
+
pdkAdmin.onDispose(() => {
|
|
18
|
+
document.removeEventListener(context.global.eventPing, onPing);
|
|
11
19
|
});
|
|
12
20
|
|
|
21
|
+
sendBootEvent(pdkAdmin, context);
|
|
22
|
+
|
|
13
23
|
globalLogger.debug('Created PDK admin!', {context});
|
|
14
24
|
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
|
|
3
|
+
import {afterEach, describe, expect, it, vi} from 'vitest';
|
|
4
|
+
import {useLanguage} from '../composables/language/useLanguage';
|
|
5
|
+
import {createPdkAdmin} from './createPdkAdmin';
|
|
6
|
+
|
|
7
|
+
const PING = 'test_pdk_ping';
|
|
8
|
+
const PONG = 'test_pdk_pong';
|
|
9
|
+
|
|
10
|
+
const addBootElement = () => {
|
|
11
|
+
const element = document.createElement('span');
|
|
12
|
+
|
|
13
|
+
element.id = 'myparcel-pdk-boot';
|
|
14
|
+
element.dataset.pdkContext = JSON.stringify({global: {eventPing: PING, eventPong: PONG, mode: 'production'}});
|
|
15
|
+
document.body.append(element);
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe('createPdkAdmin', () => {
|
|
19
|
+
afterEach(() => {
|
|
20
|
+
document.body.innerHTML = '';
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('answers a ping with its instance until it is disposed', () => {
|
|
24
|
+
addBootElement();
|
|
25
|
+
const pong = vi.fn();
|
|
26
|
+
document.addEventListener(PONG, pong);
|
|
27
|
+
|
|
28
|
+
const pdkAdmin = createPdkAdmin({components: {}} as never);
|
|
29
|
+
pong.mockClear();
|
|
30
|
+
|
|
31
|
+
document.dispatchEvent(new Event(PING));
|
|
32
|
+
expect(pong).toHaveBeenCalledTimes(1);
|
|
33
|
+
|
|
34
|
+
pdkAdmin?.dispose();
|
|
35
|
+
document.dispatchEvent(new Event(PING));
|
|
36
|
+
expect(pong).toHaveBeenCalledTimes(1);
|
|
37
|
+
|
|
38
|
+
document.removeEventListener(PONG, pong);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('can be disposed twice', () => {
|
|
42
|
+
addBootElement();
|
|
43
|
+
const pdkAdmin = createPdkAdmin({components: {}} as never);
|
|
44
|
+
|
|
45
|
+
pdkAdmin?.dispose();
|
|
46
|
+
|
|
47
|
+
expect(() => pdkAdmin?.dispose()).not.toThrow();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('stops answering pings when a pong handler disposes it right away', () => {
|
|
51
|
+
addBootElement();
|
|
52
|
+
const disposeOnPong = (event: Event) => (event as CustomEvent).detail.dispose();
|
|
53
|
+
document.addEventListener(PONG, disposeOnPong, {once: true});
|
|
54
|
+
|
|
55
|
+
createPdkAdmin({components: {}} as never);
|
|
56
|
+
|
|
57
|
+
const pong = vi.fn();
|
|
58
|
+
document.addEventListener(PONG, pong);
|
|
59
|
+
document.dispatchEvent(new Event(PING));
|
|
60
|
+
|
|
61
|
+
expect(pong).not.toHaveBeenCalled();
|
|
62
|
+
|
|
63
|
+
document.removeEventListener(PONG, pong);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('starts without the translation cache of a previous instance', () => {
|
|
67
|
+
addBootElement();
|
|
68
|
+
const {missingKeys} = useLanguage();
|
|
69
|
+
missingKeys.value = ['key_from_the_previous_instance'];
|
|
70
|
+
|
|
71
|
+
createPdkAdmin({components: {}} as never);
|
|
72
|
+
|
|
73
|
+
expect(missingKeys.value).toEqual([]);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {type InputAdminConfiguration} from '../types';
|
|
2
2
|
import {getElementContext, globalLogger} from '../services';
|
|
3
|
+
import {resetLanguageCache} from '../composables/language/useLanguage';
|
|
3
4
|
import {createAdminConfig} from './createAdminConfig';
|
|
4
5
|
import {boot} from './boot';
|
|
5
6
|
import {PdkAdmin} from './PdkAdmin';
|
|
@@ -22,6 +23,7 @@ export const createPdkAdmin: CreatePdkAdmin = (configuration?) => {
|
|
|
22
23
|
const config = createAdminConfig(configuration);
|
|
23
24
|
|
|
24
25
|
globalLogger.level = config.logLevel;
|
|
26
|
+
resetLanguageCache();
|
|
25
27
|
|
|
26
28
|
const context = getElementContext(BOOTSTRAP_CONTAINER_SELECTOR);
|
|
27
29
|
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {createApp} from 'vue';
|
|
2
|
+
import {describe, expect, it, vi} from 'vitest';
|
|
3
|
+
import {createPinia, defineStore, type Pinia} from 'pinia';
|
|
4
|
+
import {type AdminAppConfig} from '../../../types';
|
|
5
|
+
import {createStorePlugin} from './createStorePlugin';
|
|
6
|
+
|
|
7
|
+
const createAppConfig = (overrides: Partial<AdminAppConfig> = {}): AdminAppConfig =>
|
|
8
|
+
({
|
|
9
|
+
appName: 'test',
|
|
10
|
+
config: {},
|
|
11
|
+
context: {},
|
|
12
|
+
logger: {debug: () => undefined},
|
|
13
|
+
...overrides,
|
|
14
|
+
} as unknown as AdminAppConfig);
|
|
15
|
+
|
|
16
|
+
describe('createStorePlugin', () => {
|
|
17
|
+
it('uses the store of the pdk admin instance', () => {
|
|
18
|
+
const store = createPinia();
|
|
19
|
+
|
|
20
|
+
expect(createStorePlugin(createAppConfig({store}))).toBe(store);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('shares one store between apps without an instance store', () => {
|
|
24
|
+
expect(createStorePlugin(createAppConfig())).toBe(createStorePlugin(createAppConfig()));
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('calls onCreateStore once for every pdk admin instance store', () => {
|
|
28
|
+
const onCreateStore = vi.fn();
|
|
29
|
+
const useTestStore = defineStore('test', {state: () => ({value: 1})});
|
|
30
|
+
|
|
31
|
+
const useStoreIn = (store: Pinia) => {
|
|
32
|
+
const app = createApp({render: () => null});
|
|
33
|
+
|
|
34
|
+
app.use(createStorePlugin(createAppConfig({store, config: {onCreateStore} as never})));
|
|
35
|
+
app.use(createStorePlugin(createAppConfig({store, config: {onCreateStore} as never})));
|
|
36
|
+
app.runWithContext(() => useTestStore(store));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
useStoreIn(createPinia());
|
|
40
|
+
useStoreIn(createPinia());
|
|
41
|
+
|
|
42
|
+
expect(onCreateStore).toHaveBeenCalledTimes(2);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -2,22 +2,27 @@ import {createPinia, type Pinia} from 'pinia';
|
|
|
2
2
|
import {type PdkAppPlugin} from './plugins.types';
|
|
3
3
|
|
|
4
4
|
let store: Pinia;
|
|
5
|
-
let initialized = false;
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The stores that ran the onCreateStore hook. Per store, because every PdkAdmin
|
|
8
|
+
* instance has its own.
|
|
9
|
+
*/
|
|
10
|
+
const initializedStores = new WeakSet<Pinia>();
|
|
11
|
+
|
|
12
|
+
export const createStorePlugin: PdkAppPlugin = ({config, logger, store: instanceStore}) => {
|
|
13
|
+
const pinia = instanceStore ?? (store ??= createPinia());
|
|
9
14
|
|
|
10
15
|
logger.debug('Preparing store plugin');
|
|
11
16
|
|
|
12
|
-
|
|
13
|
-
if (
|
|
17
|
+
pinia.use((storeContext) => {
|
|
18
|
+
if (initializedStores.has(pinia) || !config.onCreateStore) {
|
|
14
19
|
return;
|
|
15
20
|
}
|
|
16
21
|
|
|
17
|
-
|
|
22
|
+
initializedStores.add(pinia);
|
|
18
23
|
logger.debug('Calling store renderer hook');
|
|
19
24
|
config.onCreateStore(storeContext);
|
|
20
25
|
});
|
|
21
26
|
|
|
22
|
-
return
|
|
27
|
+
return pinia;
|
|
23
28
|
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import {createApp} from 'vue';
|
|
2
|
+
import {describe, expect, it} from 'vitest';
|
|
3
|
+
import {QueryClient, useQueryClient} from '@tanstack/vue-query';
|
|
4
|
+
import {AdminContextKey, BackendEndpoint} from '@myparcel-dev/pdk-common';
|
|
5
|
+
import {type AdminAppConfig} from '../../../types';
|
|
6
|
+
import {createVueQueryPlugin} from './createVueQueryPlugin';
|
|
7
|
+
|
|
8
|
+
const createAppConfig = (overrides: Partial<AdminAppConfig> = {}): AdminAppConfig =>
|
|
9
|
+
({
|
|
10
|
+
appName: 'test',
|
|
11
|
+
config: {},
|
|
12
|
+
context: {[AdminContextKey.Global]: {mode: 'production'}},
|
|
13
|
+
logger: {debug: () => undefined},
|
|
14
|
+
...overrides,
|
|
15
|
+
} as unknown as AdminAppConfig);
|
|
16
|
+
|
|
17
|
+
describe('createVueQueryPlugin', () => {
|
|
18
|
+
it('provides the query client of the pdk admin instance, filled with the context', () => {
|
|
19
|
+
const queryClient = new QueryClient();
|
|
20
|
+
const app = createApp({render: () => null});
|
|
21
|
+
|
|
22
|
+
app.use(createVueQueryPlugin(createAppConfig({queryClient})));
|
|
23
|
+
|
|
24
|
+
expect(app.runWithContext(() => useQueryClient())).toBe(queryClient);
|
|
25
|
+
expect(queryClient.getQueryData([BackendEndpoint.FetchContext, AdminContextKey.Global])).toEqual({
|
|
26
|
+
mode: 'production',
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -10,12 +10,12 @@ let queryClient: QueryClient;
|
|
|
10
10
|
/**
|
|
11
11
|
* Instantiate vue query client if it does not exist yet and provide it to the app.
|
|
12
12
|
*/
|
|
13
|
-
export const createVueQueryPlugin: PdkAppPlugin = ({context, logger}) => {
|
|
13
|
+
export const createVueQueryPlugin: PdkAppPlugin = ({context, logger, queryClient: instanceQueryClient}) => {
|
|
14
14
|
return {
|
|
15
15
|
install: (app) => {
|
|
16
16
|
logger.debug('Installing vue-query plugin');
|
|
17
17
|
|
|
18
|
-
queryClient ??= createQueryClient();
|
|
18
|
+
const client = instanceQueryClient ?? (queryClient ??= createQueryClient());
|
|
19
19
|
|
|
20
20
|
// Fill the query client with the context data
|
|
21
21
|
Object.entries(context).forEach(([contextKey, value]) => {
|
|
@@ -23,26 +23,26 @@ export const createVueQueryPlugin: PdkAppPlugin = ({context, logger}) => {
|
|
|
23
23
|
return;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
client.setQueryData([BackendEndpoint.FetchContext, contextKey], value);
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
const instanceContext = createInstanceContext(context);
|
|
30
|
-
|
|
30
|
+
client.setQueryData([BackendEndpoint.FetchContext, AdminContextKey.Instance], instanceContext);
|
|
31
31
|
|
|
32
32
|
// Add each order and its shipments to the query client
|
|
33
33
|
if (context.orderData) {
|
|
34
34
|
context.orderData.forEach((order) => {
|
|
35
|
-
fillShipmentsQueryData(
|
|
35
|
+
fillShipmentsQueryData(client, order.shipments, order);
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
if (context.productData) {
|
|
40
40
|
context.productData.forEach((product) => {
|
|
41
|
-
|
|
41
|
+
client.setQueryData([BackendEndpoint.FetchProducts, {id: product.externalIdentifier}], product);
|
|
42
42
|
});
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
app.use(VueQueryPlugin, {queryClient});
|
|
45
|
+
app.use(VueQueryPlugin, {queryClient: client});
|
|
46
46
|
},
|
|
47
47
|
};
|
|
48
48
|
};
|
package/src/pdk/setupAdminApp.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {type App} from 'vue';
|
|
2
2
|
import {type AdminAppConfig} from '../types';
|
|
3
|
+
import {setRequestHeadersProvider} from '../sdk/requestHeaders';
|
|
3
4
|
import {testIdDirective} from './testIdDirective';
|
|
4
5
|
import {
|
|
5
6
|
createContextPlugin,
|
|
@@ -10,6 +11,8 @@ import {
|
|
|
10
11
|
} from './instance';
|
|
11
12
|
|
|
12
13
|
export const setupAdminApp = (app: App<Element>, appConfig: AdminAppConfig): void => {
|
|
14
|
+
setRequestHeadersProvider(appConfig.config.getRequestHeaders);
|
|
15
|
+
|
|
13
16
|
app.use(createStorePlugin(appConfig));
|
|
14
17
|
app.use(createVueQueryPlugin(appConfig));
|
|
15
18
|
app.use(createContextPlugin(appConfig));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {createGlobalState} from '@vueuse/core';
|
|
2
2
|
import {createMyParcelSdk, type HttpMethod, type MyParcelSdk} from '@myparcel-dev/sdk';
|
|
3
3
|
import {type BackendEndpoint} from '@myparcel-dev/pdk-common';
|
|
4
|
+
import {addRequestHeaders} from '../requestHeaders';
|
|
4
5
|
import {AbstractPdkEndpoint} from '../endpoints';
|
|
5
6
|
import {PdkFetchClient} from '../PdkFetchClient';
|
|
6
7
|
import {useGlobalContext} from '../../composables';
|
|
@@ -15,6 +16,8 @@ export const usePdkAdminApi = createGlobalState((): MyParcelSdk<AbstractPdkEndpo
|
|
|
15
16
|
baseUrl: globalContext.baseUrl,
|
|
16
17
|
});
|
|
17
18
|
|
|
19
|
+
client.interceptors.request.use(addRequestHeaders);
|
|
20
|
+
|
|
18
21
|
const pdkEndpoints = Object.entries(globalContext.endpoints).map(([endpointName, options]) => {
|
|
19
22
|
// Effectively cast null as 'undefined' to prevent the SDK casting the prefix property to the string 'null'.
|
|
20
23
|
const property = typeof options.property === 'string' ? options.property : undefined;
|
package/src/sdk/index.ts
CHANGED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {afterEach, describe, expect, it} from 'vitest';
|
|
2
|
+
import {addRequestHeaders, setRequestHeadersProvider} from './requestHeaders';
|
|
3
|
+
|
|
4
|
+
describe('addRequestHeaders', () => {
|
|
5
|
+
afterEach(() => {
|
|
6
|
+
setRequestHeadersProvider(undefined);
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it('returns the options unchanged without a provider', async () => {
|
|
10
|
+
const options = {headers: {Accept: 'application/json'}};
|
|
11
|
+
|
|
12
|
+
expect(await addRequestHeaders(options)).toEqual({headers: {Accept: 'application/json'}});
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('merges the headers of a synchronous provider', async () => {
|
|
16
|
+
setRequestHeadersProvider(() => ({Authorization: 'Bearer one'}));
|
|
17
|
+
|
|
18
|
+
expect(await addRequestHeaders({headers: {Accept: 'application/json'}})).toEqual({
|
|
19
|
+
headers: {Accept: 'application/json', Authorization: 'Bearer one'},
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('merges the headers of an asynchronous provider', async () => {
|
|
24
|
+
setRequestHeadersProvider(() => Promise.resolve({Authorization: 'Bearer two'}));
|
|
25
|
+
|
|
26
|
+
expect(await addRequestHeaders({})).toEqual({headers: {Authorization: 'Bearer two'}});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('calls the provider for every request', async () => {
|
|
30
|
+
let token = 0;
|
|
31
|
+
setRequestHeadersProvider(() => ({Authorization: `Bearer ${++token}`}));
|
|
32
|
+
|
|
33
|
+
await addRequestHeaders({});
|
|
34
|
+
const second = await addRequestHeaders({});
|
|
35
|
+
|
|
36
|
+
expect(second.headers).toEqual({Authorization: 'Bearer 2'});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('lets the provider override a static header', async () => {
|
|
40
|
+
setRequestHeadersProvider(() => ({Authorization: 'Bearer new'}));
|
|
41
|
+
|
|
42
|
+
expect(await addRequestHeaders({headers: {Authorization: 'Bearer old'}})).toEqual({
|
|
43
|
+
headers: {Authorization: 'Bearer new'},
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('replaces a header with the same name in another casing', async () => {
|
|
48
|
+
setRequestHeadersProvider(() => ({Authorization: 'Bearer fresh'}));
|
|
49
|
+
|
|
50
|
+
expect(await addRequestHeaders({headers: {Accept: 'application/json', authorization: 'Bearer expired'}})).toEqual({
|
|
51
|
+
headers: {Accept: 'application/json', Authorization: 'Bearer fresh'},
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type RequestHeaders = Record<string, string>;
|
|
2
|
+
|
|
3
|
+
export type RequestHeadersProvider = () => RequestHeaders | Promise<RequestHeaders>;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Module level, because the PDK API client is a global state that is often
|
|
7
|
+
* created inside a query function, where inject() is not available.
|
|
8
|
+
*/
|
|
9
|
+
let provider: RequestHeadersProvider | undefined;
|
|
10
|
+
|
|
11
|
+
export const setRequestHeadersProvider = (newProvider: RequestHeadersProvider | undefined): void => {
|
|
12
|
+
provider = newProvider;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Header names are case-insensitive: drop an existing header that the provider
|
|
17
|
+
* sets in another casing, so fetch does not send both values.
|
|
18
|
+
*/
|
|
19
|
+
const mergeHeaders = (headers: RequestHeaders, extraHeaders: RequestHeaders): RequestHeaders => {
|
|
20
|
+
const extraNames = Object.keys(extraHeaders).map((name) => name.toLowerCase());
|
|
21
|
+
const kept = Object.entries(headers).filter(([name]) => !extraNames.includes(name.toLowerCase()));
|
|
22
|
+
|
|
23
|
+
return {...Object.fromEntries(kept), ...extraHeaders};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Request interceptor. Calls the provider for every request, so a short-lived
|
|
28
|
+
* token is always current.
|
|
29
|
+
*/
|
|
30
|
+
export const addRequestHeaders = async <T extends {headers?: RequestHeaders}>(options: T): Promise<T> => {
|
|
31
|
+
if (!provider) {
|
|
32
|
+
return options;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {...options, headers: mergeHeaders(options.headers ?? {}, await provider())};
|
|
36
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
|
|
3
|
+
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
|
4
|
+
import {createPinia, setActivePinia} from 'pinia';
|
|
5
|
+
import {useModalStore, useNotificationStore} from '../../stores';
|
|
6
|
+
import {AdminModalKey} from '../../data';
|
|
7
|
+
import {getModalMutationOptions} from './getModalMutationOptions';
|
|
8
|
+
|
|
9
|
+
describe('getModalMutationOptions', () => {
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
setActivePinia(createPinia());
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('changes the modal that started the mutation', () => {
|
|
15
|
+
const modalStore = useModalStore();
|
|
16
|
+
const options = getModalMutationOptions();
|
|
17
|
+
|
|
18
|
+
modalStore.open(AdminModalKey.ShipmentOptions);
|
|
19
|
+
modalStore.loading = true;
|
|
20
|
+
const context = options.onMutate?.(undefined);
|
|
21
|
+
|
|
22
|
+
options.onError?.(new Error('failed'), undefined, context);
|
|
23
|
+
options.onSettled?.(undefined, null, undefined, context);
|
|
24
|
+
options.onSuccess?.(undefined, undefined, context);
|
|
25
|
+
|
|
26
|
+
expect(useNotificationStore().notifications).toHaveLength(1);
|
|
27
|
+
expect(modalStore.loading).toBe(false);
|
|
28
|
+
expect(modalStore.opened).toBeNull();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('leaves a modal alone that the user opened after the mutation started', () => {
|
|
32
|
+
const modalStore = useModalStore();
|
|
33
|
+
const options = getModalMutationOptions();
|
|
34
|
+
|
|
35
|
+
modalStore.open(AdminModalKey.ShipmentOptions);
|
|
36
|
+
const context = options.onMutate?.(undefined);
|
|
37
|
+
|
|
38
|
+
// The user closes the modal with Escape and opens the modal of another order.
|
|
39
|
+
modalStore.close();
|
|
40
|
+
modalStore.open(AdminModalKey.ShipmentOptions, {orderIds: ['2']});
|
|
41
|
+
modalStore.loading = true;
|
|
42
|
+
|
|
43
|
+
options.onError?.(new Error('failed'), undefined, context);
|
|
44
|
+
options.onSettled?.(undefined, null, undefined, context);
|
|
45
|
+
options.onSuccess?.(undefined, undefined, context);
|
|
46
|
+
|
|
47
|
+
expect(useNotificationStore().notifications).toHaveLength(0);
|
|
48
|
+
expect(modalStore.loading).toBe(true);
|
|
49
|
+
expect(modalStore.opened).toBe(AdminModalKey.ShipmentOptions);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('still runs the onMutate it replaces', () => {
|
|
53
|
+
const onMutate = vi.fn();
|
|
54
|
+
|
|
55
|
+
void getModalMutationOptions({onMutate}).onMutate?.(undefined);
|
|
56
|
+
|
|
57
|
+
expect(onMutate).toHaveBeenCalledOnce();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -3,22 +3,30 @@ import {type MutationOptions} from '@tanstack/vue-query';
|
|
|
3
3
|
import {addErrorToNotifications} from '../addErrorToNotifications';
|
|
4
4
|
import {useModalStore} from '../../stores';
|
|
5
5
|
import {NotificationCategory} from '../../data';
|
|
6
|
+
import {isSameModal, keepModalToken, type ModalMutationContext} from './modalMutationToken';
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Options for a mutation that a modal starts. The callbacks only change the
|
|
10
|
+
* modal when it is still the modal that started the mutation. Pass the default
|
|
11
|
+
* mutation options, so their onMutate still runs.
|
|
12
|
+
*/
|
|
13
|
+
export const getModalMutationOptions = <TData = unknown, TError = unknown, TVariables = void>(
|
|
14
|
+
defaultOptions: MutationOptions<TData, TError, TVariables> = {},
|
|
15
|
+
): MutationOptions<TData, TError, TVariables, ModalMutationContext> => ({
|
|
16
|
+
onMutate: keepModalToken(defaultOptions.onMutate),
|
|
17
|
+
onSuccess(data, variables, context) {
|
|
18
|
+
if (isSameModal(context)) {
|
|
15
19
|
useModalStore().close();
|
|
16
|
-
}
|
|
17
|
-
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
onSettled(data, error, variables, context) {
|
|
23
|
+
if (isSameModal(context)) {
|
|
18
24
|
useModalStore().loading = false;
|
|
19
|
-
}
|
|
20
|
-
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
onError(error, variables, context) {
|
|
28
|
+
if (isSameModal(context)) {
|
|
21
29
|
addErrorToNotifications(error, NotificationCategory.Modal);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
};
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {type ModalToken, useModalStore} from '../../stores';
|
|
2
|
+
|
|
3
|
+
export type ModalMutationContext = {modalToken: ModalToken | null};
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Creates an onMutate that keeps the token of the modal that is open when the
|
|
7
|
+
* mutation starts. Pass the onMutate it replaces, for example the default one
|
|
8
|
+
* of the query client, so that one still runs.
|
|
9
|
+
*/
|
|
10
|
+
export const keepModalToken =
|
|
11
|
+
<TVariables>(onMutate?: (variables: TVariables) => unknown) =>
|
|
12
|
+
(variables: TVariables): ModalMutationContext => {
|
|
13
|
+
void onMutate?.(variables);
|
|
14
|
+
|
|
15
|
+
return {modalToken: useModalStore().token};
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Tells if the modal that was open when the mutation started is still open.
|
|
20
|
+
* Use it in late mutation callbacks, so they do not change a modal that the
|
|
21
|
+
* user opened in the meantime.
|
|
22
|
+
*/
|
|
23
|
+
export const isSameModal = (context: ModalMutationContext | undefined): boolean => {
|
|
24
|
+
const modalToken = context?.modalToken;
|
|
25
|
+
|
|
26
|
+
return Boolean(modalToken) && modalToken === useModalStore().token;
|
|
27
|
+
};
|