Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: store config query #862

Merged
merged 2 commits into from
Apr 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ Then on the `config` folder create a file `dev.json` with your configurations.
}
```


## Store Config
This type contains information about the Magento's Store Configuration which is stored in Pinia `$state.storeConfig`. To avoid over fetch, by default, the amount of data pulled from Magento is minimal but as your application grows you might want to pull more config data for different purposes.

Plugin `plugins/storeConfigPlugin.ts` is responsible for initial population of the Store Config data based on query in `plugins/query/StoreConfig.gql.ts`. To modify the initial Store Configuration state simply adjust the query to your needs.

## Multistore and localization

Each Magento Store View need to have corresponding locale configuration object in `i18n.locales` array in `nuxt.config.js`.
Expand Down
11 changes: 5 additions & 6 deletions packages/theme/components/HeaderLogo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import { SfImage } from '@storefront-ui/vue';
import { computed, defineComponent } from '@nuxtjs/composition-api';
import { useConfig } from '~/composables';
import { storeConfigGetters } from '~/getters';
import SvgImage from '~/components/General/SvgImage.vue';

export default defineComponent({
Expand All @@ -36,22 +35,22 @@ export default defineComponent({
const { config } = useConfig();

const logoSrc = computed(() => {
const baseMediaUrl = storeConfigGetters.getBaseMediaUrl(config.value);
const logo = storeConfigGetters.getLogoSrc(config.value);
const baseMediaUrl = config.value.base_media_url;
const logo = config.value.header_logo_src;

return baseMediaUrl && logo ? `${baseMediaUrl}logo/${logo}` : '';
});

const logoWidth = computed(
() => storeConfigGetters.getLogoWidth(config.value) || '35',
() => config.value.logo_width || '35',
);

const logoHeight = computed(
() => storeConfigGetters.getLogoHeight(config.value) || '34',
() => config.value.logo_height || '34',
);

const logoAlt = computed(
() => storeConfigGetters.getLogoAlt(config.value) || '',
() => config.value.logo_alt || '',
);

return {
Expand Down
9 changes: 2 additions & 7 deletions packages/theme/components/StoreSwitcher.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@
<span class="desktop-only">{{ storeConfig.store_name }}</span>
</template>
<template
v-if="storeConfigGetters.getLocale(storeConfig)"
v-if="storeConfig.locale"
#icon
>
<SfImage
image-tag="nuxt-img"
:src="`/icons/langs/${storeConfigGetters.getLocale(
storeConfig
)}.webp`"
:src="`/icons/langs/${storeConfig.locale}.webp`"
width="20"
height="20"
alt="Flag"
Expand All @@ -42,7 +40,6 @@ import LazyHydrate from 'vue-lazy-hydration';
import { SfButton, SfCharacteristic, SfImage } from '@storefront-ui/vue';

import { ref, defineComponent } from '@nuxtjs/composition-api';
import { storeConfigGetters, storeGetters } from '~/getters';
import StoresModal from '~/components/StoreSwitcher/StoresModal.vue';
import { useConfig } from '~/composables';

Expand All @@ -63,8 +60,6 @@ export default defineComponent({
return {
isLangModalOpen,
storeConfig: config,
storeConfigGetters,
storeGetters,
};
},
});
Expand Down
23 changes: 12 additions & 11 deletions packages/theme/components/StoreSwitcher/StoresModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,20 @@
href="/"
class="container__store--link"
:class="
storeGetters.getSelected(storeConfig, store)
storeConfig.store_code === store.store_code
? 'container__store--selected'
: ''
"
@click.prevent="changeStore(store)"
>
<SfCharacteristic class="language">
<template #title>
<span>{{ storeConfigGetters.getName(store) }}</span>
<span>{{ store.store_name }}</span>
</template>
<template #icon>
<SfImage
image-tag="nuxt-img"
:src="`/icons/langs/${storeConfigGetters.getLocale(
store
)}.webp`"
:src="`/icons/langs/${store.locale}.webp`"
width="20"
height="20"
alt="Flag"
Expand All @@ -41,16 +39,18 @@
</SfList>
</SfBottomModal>
</template>
<script>
import { defineComponent, onMounted, computed } from '@nuxtjs/composition-api';
<script lang="ts">
import {
defineComponent, onMounted, computed, PropType,
} from '@nuxtjs/composition-api';
import {
SfList,
SfBottomModal,
SfCharacteristic,
SfImage,
} from '@storefront-ui/vue';
import { StoreConfig } from '~/modules/GraphQL/types';
import { useStore } from '~/composables';
import { storeGetters, storeConfigGetters } from '~/getters';

export default defineComponent({
name: 'StoresModal',
Expand All @@ -62,7 +62,10 @@ export default defineComponent({
},
props: {
isLangModalOpen: Boolean,
storeConfig: Object,
storeConfig: {
type: Object as PropType<StoreConfig | {}>,
default: () => {},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eh we have the annoying eslint rule where it forces us to provide a default value

would it be possible to use like as PropType<StoreCofnig | null>? The {} doesn't really match StoreConfig

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should remove that rule then?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Anyway, I updated the code.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you push it out? I can't see the updates

},
},
emits: ['closeModal'],
setup() {
Expand All @@ -80,8 +83,6 @@ export default defineComponent({
});

return {
storeGetters,
storeConfigGetters,
availableStores,
changeStore,
};
Expand Down
35 changes: 1 addition & 34 deletions packages/theme/composables/useMagentoConfiguration.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,29 @@
import { computed, ComputedRef, useContext } from '@nuxtjs/composition-api';
import { StoreConfig } from '~/modules/GraphQL/types';
import { storeConfigGetters } from '~/getters';

import { useConfig } from '~/composables';

type UseMagentoConfiguration = () => {
storeConfig: ComputedRef<StoreConfig>;
selectedCurrency: ComputedRef<string | undefined>;
selectedLocale: ComputedRef<string | undefined>;
selectedStore: ComputedRef<string | undefined>;
loadConfiguration: (params: { updateCookies: boolean; updateLocale: boolean; }) => Promise<void>;
};

export const useMagentoConfiguration: UseMagentoConfiguration = () => {
const { app: { i18n, $vsf: { $magento: { config } } } } = useContext();
const { app: { $vsf: { $magento: { config } } } } = useContext();

const {
config: storeConfig,
load: loadConfig,
} = useConfig();

const selectedCurrency = computed<string | undefined>(() => config.state.getCurrency());
const selectedLocale = computed<string | undefined>(() => config.state.getLocale());
const selectedStore = computed<string | undefined>(() => config.state.getStore());

const loadConfiguration: (params: { updateCookies: boolean; updateLocale: boolean; }) => Promise<void> = async (params = {
updateCookies: false,
updateLocale: false,
}) => {
const {
updateCookies,
updateLocale,
} = params;

await loadConfig();
if (config.state.getStore() || updateCookies) {
config.state.setStore(storeConfigGetters.getCode(storeConfig.value));
}

if (!config.state.getLocale() || updateCookies) {
config.state.setLocale(storeConfigGetters.getLocale(storeConfig.value));
}

if (!config.state.getCurrency() || updateCookies) {
config.state.setCurrency(storeConfigGetters.getCurrency(storeConfig.value));
}

// eslint-disable-next-line promise/always-return
if (updateLocale) {
i18n.setLocale(storeConfigGetters.getLocale(storeConfig.value));
}
};

return {
storeConfig,
selectedCurrency,
selectedLocale,
selectedStore,
loadConfiguration,
};
};
9 changes: 4 additions & 5 deletions packages/theme/composables/useStore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
} from '@nuxtjs/composition-api';
import { Logger } from '~/helpers/logger';
import { StoreConfig } from '~/modules/GraphQL/types';
import { storeConfigGetters } from '~/getters';
import { UseStoreInterface, UseStore, UseStoreErrors } from '~/composables/useStore/useStore';
import { useConfigStore } from '~/stores/config';

Expand Down Expand Up @@ -40,10 +39,10 @@ const useStore: UseStore = (): UseStoreInterface => {

try {
loading.value = true;
app.$vsf.$magento.config.state.setStore(storeConfigGetters.getCode(store));
app.$vsf.$magento.config.state.setCurrency(storeConfigGetters.getCurrency(store));
app.$vsf.$magento.config.state.setLocale(storeConfigGetters.getCode(store));
const newStoreUrl = app.switchLocalePath(storeConfigGetters.getCode(store));
app.$vsf.$magento.config.state.setStore(store.store_code);
app.$vsf.$magento.config.state.setCurrency(store.default_display_currency_code);
app.$vsf.$magento.config.state.setLocale(store.store_code);
const newStoreUrl = app.switchLocalePath(store.store_code);
window.location.replace(newStoreUrl);
} catch (err) {
error.value.change = err;
Expand Down
Empty file removed packages/theme/graphqlClient.ts
Empty file.
25 changes: 9 additions & 16 deletions packages/theme/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
} from '@nuxtjs/composition-api';
import { useUiState, useUser } from '~/composables';
import LoadWhenVisible from '~/components/utils/LoadWhenVisible';
import { useMagentoConfiguration } from '~/composables/useMagentoConfiguration';
import AppHeader from '~/components/AppHeader.vue';
import BottomNavigation from '~/components/BottomNavigation.vue';
import IconSprite from '~/components/General/IconSprite.vue';
Expand All @@ -41,29 +40,20 @@ export default defineComponent({
BottomNavigation,
IconSprite,
TopBar,
AppFooter: () =>
import(/* webpackPrefetch: true */ '~/components/AppFooter.vue'),
CartSidebar: () =>
import(/* webpackPrefetch: true */ '~/components/CartSidebar.vue'),
WishlistSidebar: () =>
import(/* webpackPrefetch: true */ '~/components/WishlistSidebar.vue'),
LoginModal: () =>
import(/* webpackPrefetch: true */ '~/components/LoginModal.vue'),
Notification: () =>
import(/* webpackPrefetch: true */ '~/components/Notification'),
},
head: {
link: [{ rel: 'stylesheet', href: '/_nuxt/fonts.css' }],
AppFooter: () => import(/* webpackPrefetch: true */ '~/components/AppFooter.vue'),
CartSidebar: () => import(/* webpackPrefetch: true */ '~/components/CartSidebar.vue'),
WishlistSidebar: () => import(/* webpackPrefetch: true */ '~/components/WishlistSidebar.vue'),
LoginModal: () => import(/* webpackPrefetch: true */ '~/components/LoginModal.vue'),
Notification: () => import(/* webpackPrefetch: true */ '~/components/Notification'),
},

setup() {
const route = useRoute();
const { load: loadUser } = useUser();
const { loadConfiguration } = useMagentoConfiguration();
const { isCartSidebarOpen, isWishlistSidebarOpen, isLoginModalOpen } = useUiState();

useAsync(async () => {
await Promise.all([loadConfiguration(), loadUser()]);
await loadUser();
});

return {
Expand All @@ -73,6 +63,9 @@ export default defineComponent({
route,
};
},
head: {
link: [{ rel: 'stylesheet', href: '/_nuxt/fonts.css' }],
},
});
</script>

Expand Down
1 change: 1 addition & 0 deletions packages/theme/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ export default () => {
'~/plugins/fcPlugin',
'~/plugins/dompurify',
'~/plugins/graphqlClient',
'~/plugins/storeConfigPlugin',
],
serverMiddleware: [
'~/serverMiddleware/body-parser.js',
Expand Down
20 changes: 20 additions & 0 deletions packages/theme/plugins/query/StoreConfig.gql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { gql } from 'graphql-request';

/** GraphQL Query that fetches store configuration from the API */
export const StoreConfigQuery = gql`
query storeConfig {
storeConfig {
store_code,
default_title,
store_name,
default_display_currency_code,
locale,
header_logo_src,
logo_width,
logo_height,
logo_alt
}
}
`;

export default StoreConfigQuery;
22 changes: 22 additions & 0 deletions packages/theme/plugins/storeConfigPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { PiniaPluginContext } from 'pinia';
import { Plugin } from '@nuxt/types';
import { ref, set } from '@nuxtjs/composition-api';
import StoreConfigGql from '~/plugins/query/StoreConfig.gql';

const storeConfigPlugin: Plugin = async ({ $pinia, $graphql }) => {
const configData = await $graphql.query.request(StoreConfigGql);
$pinia.use(({ store }: PiniaPluginContext) => {
if (store.$id !== 'magentoConfig') return;
const storeConfig = ref(configData.storeConfig);

// eslint-disable-next-line no-prototype-builtins
if (!store.$state.hasOwnProperty('storeConfig')) {
set(store.$state, 'storeConfig', storeConfig);
} else {
// eslint-disable-next-line no-param-reassign
store.$state.storeConfig = storeConfig;
}
});
};

export default storeConfigPlugin;