Skip to content

Commit

Permalink
feat: fetching pwa settings (plentymarkets#544)
Browse files Browse the repository at this point in the history
* WIP

* refactor: use async config method

* fix: resolve data

* Fetching PWA settings before build.

* Applying code review changes.

* Creating build directory for fetching script. + Trying to fix pipeline.

* Fix import.

* Fixing pipelines.

* Fixing pipelines.

* Fixing pipelines.

* Removing console logs.

* Changelog edit

* refactor: remove duplicate env setup

* chore: revert eol change

* refactor: remove unnecessary variable

* refactor: fetch script

* Fixing lint error + code adjustment.

---------

Co-authored-by: clincu-plenty <[email protected]>
Co-authored-by: Maximilian Röll <[email protected]>
Co-authored-by: ksted <[email protected]>
  • Loading branch information
4 people authored Jul 5, 2024
1 parent 24d2df6 commit dd9fab6
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 6 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/conventional-pr-name.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Create .env file
run: touch apps/web/.env

- name: Install Dependencies
run: yarn --frozen-lockfile

Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/lighthouse-mobile-audit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Install Dependencies
run: yarn --immutable

- name: Set environment
run: |
touch apps/web/.env
Expand All @@ -53,6 +50,9 @@ jobs:
${{ vars.CONFIG }}
EOT
- name: Install Dependencies
run: yarn --immutable

- name: Build application
run: yarn build

Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Create .env file
run: touch apps/web/.env

- name: Install Dependencies
run: yarn --frozen-lockfile

Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: Install Dependencies
run: yarn --immutable

- name: Set environment
run: |
touch apps/web/.env
Expand All @@ -53,6 +50,9 @@ jobs:
${{ vars.CONFIG }}
EOT
- name: Install Dependencies
run: yarn --immutable

- name: Unit tests
run: |
pushd ${{ github.workspace }}/apps/server/
Expand Down
86 changes: 86 additions & 0 deletions apps/web/build/fetchConfiguration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import axios from 'axios';
import https from 'node:https';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const environmentFilePath = path.resolve(__dirname, '../.env');
const environmentTemporaryFilePath = path.resolve(__dirname, '../.env.tmp');

const environmentMap = {
DISABLE_SETTINGS_FETCH: process.env.DISABLE_SETTINGS_FETCH,
API_ENDPOINT: process.env.API_ENDPOINT,
API_SECURITY_TOKEN: process.env.API_SECURITY_TOKEN,
CONFIG_ID: process.env.CONFIG_ID,
};

const setupTemporaryEnvironment = () => {
let requiredEnvironmentData = '';

for (const [key, value] of Object.entries(environmentMap)) {
if (key === 'DISABLE_SETTINGS_FETCH') continue;
if (!value) {
console.error(`Missing or invalid required environment variable: ${key}`);
return;
}

requiredEnvironmentData += `${key}=${value}\n`;
}

fs.writeFile(environmentTemporaryFilePath, requiredEnvironmentData, () => {});
};

const writeConfigurationToTemporaryEnvironment = (data: Array<Array<{ [key: string]: string }>>) => {
const environmentVariables = fs.readFileSync(environmentTemporaryFilePath, 'utf8').split(os.EOL);

for (const category in data) {
if (Array.isArray(data[category])) {
data[category].forEach((item: { [key: string]: string }) => {
environmentVariables.push(`${item.key.toUpperCase()}="${item.value}"`);
});
}
}

fs.writeFileSync(environmentTemporaryFilePath, environmentVariables.join(os.EOL));
};

const fetchAndWriteRemoteConfiguration = async () => {
const instance = axios.create({
withCredentials: true,
baseURL: environmentMap.API_ENDPOINT,
headers: {
'X-Security-Token': environmentMap.API_SECURITY_TOKEN,
},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
});

try {
const { data } = await instance.get(`/storefront/settings/${environmentMap.CONFIG_ID}`);
writeConfigurationToTemporaryEnvironment(data);
} catch (error: any) {

Check warning on line 62 in apps/web/build/fetchConfiguration.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (axios.isAxiosError(error)) {
console.error('PWA settings error:', error.response?.data.error);
return;
}
}
};

const convertTemporaryToPermanentEnvironment = () => {
fs.copyFile(environmentTemporaryFilePath, environmentFilePath, () => {});
fs.unlink(environmentTemporaryFilePath, () => {});
};

const fetchConfiguration = async () => {
if (environmentMap.DISABLE_SETTINGS_FETCH === undefined || environmentMap.DISABLE_SETTINGS_FETCH === '1') {
console.warn(`Fetching PWA settings is disabled! Check DISABLE_SETTINGS_FETCH in .env file.`);
return;
}

setupTemporaryEnvironment();
await fetchAndWriteRemoteConfiguration();
convertTemporaryToPermanentEnvironment();
};

export default fetchConfiguration;
4 changes: 4 additions & 0 deletions apps/web/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { validateApiUrl } from './utils/pathHelper';
import cookieConfig from './cookie.config';
import { nuxtI18nOptions } from './i18n.config';
import fetchConfiguration from './build/fetchConfiguration';

export default defineNuxtConfig({
telemetry: false,
Expand Down Expand Up @@ -60,6 +61,9 @@ export default defineNuxtConfig({
file: __dirname + '/pages/product/[slug].vue',
});
},
'build:before': async () => {
await fetchConfiguration();
},
},
runtimeConfig: {
public: {
Expand Down
1 change: 1 addition & 0 deletions docs/changelog/changelog_de.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- Hochgeladene Dateien als Produktattribut können jetzt wieder heruntergeladen werden
- Platzhaltertext für fehlende Adressen hinzugefügt
- Dieselbe benutzerdefinierte Kopfzeile in „Mein Konto“ hinzugefügt
- Hook hinzugefügt, um Systemkonfigurationen zu laden

### Behoben

Expand Down
1 change: 1 addition & 0 deletions docs/changelog/changelog_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
- Moved Lighthouse Test into its own GitHub action
- Demo for changing app settings at runtime
- Uploaded files as a product attribute can now be downloaded again
- Added hook to load system configuration

### Fixed

Expand Down

0 comments on commit dd9fab6

Please sign in to comment.