Skip to content

Commit

Permalink
feat: strf-9087 stencil localhost only shows default storefront data (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jairo-bc authored Jun 8, 2021
1 parent 3fc8e62 commit 85d7733
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 12 deletions.
17 changes: 15 additions & 2 deletions bin/stencil-start.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node

require('colors');
const { PACKAGE_INFO } = require('../constants');
const { PACKAGE_INFO, API_HOST } = require('../constants');
const program = require('../lib/commander');
const StencilStart = require('../lib/stencil-start');
const { printCliResultErrorAndExit } = require('../lib/cliCommon');
Expand All @@ -10,6 +10,8 @@ program
.version(PACKAGE_INFO.version)
.option('-o, --open', 'Automatically open default browser')
.option('-v, --variation [name]', 'Set which theme variation to use while developing')
.option('-c, --channelId [channelId]', 'Set the channel id for the storefront')
.option('--host [hostname]', 'specify the api host')
.option(
'--tunnel [name]',
'Create a tunnel URL which points to your local server that anyone can use.',
Expand All @@ -20,4 +22,15 @@ program
)
.parse(process.argv);

new StencilStart().run(program.opts()).catch(printCliResultErrorAndExit);
const cliOptions = program.opts();

const options = {
open: cliOptions.open,
variation: cliOptions.variation,
channelId: cliOptions.channelId,
apiHost: cliOptions.host || API_HOST,
tunnel: cliOptions.tunnel,
cache: cliOptions.cache,
};

new StencilStart().run(options).catch(printCliResultErrorAndExit);
11 changes: 8 additions & 3 deletions lib/stencil-push.utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,13 @@ utils.promptUserForChannel = async (options) => {
return options;
}

const selectedChannelId = await utils.promptUserToSelectChannel(channels);
return { ...options, channelId: selectedChannelId };
};

utils.promptUserToSelectChannel = async (channels) => {
if (channels.length < 2) {
return { ...options, channelId: channels[0].channel_id };
return channels[0].channel_id;
}

const questions = [
Expand All @@ -354,9 +359,9 @@ utils.promptUserForChannel = async (options) => {
})),
},
];
const answers = await Inquirer.prompt(questions);

return { ...options, channelId: answers.channelId };
const answer = await Inquirer.prompt(questions);
return answer.channelId;
};

utils.promptUserForVariation = async (options) => {
Expand Down
30 changes: 28 additions & 2 deletions lib/stencil-start.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const StencilConfigManager = require('./StencilConfigManager');
const ThemeConfig = require('./theme-config');
const BuildConfigManager = require('./BuildConfigManager');
const fsUtilsModule = require('./utils/fsUtils');
const stencilPushUtilsModule = require('./stencil-push.utils');
const cliCommonModule = require('./cliCommon');
const themeApiClientModule = require('./theme-api-client');

Expand All @@ -25,6 +26,7 @@ class StencilStart {
buildConfigManger = new BuildConfigManager(),
templateAssembler = templateAssemblerModule,
CyclesDetector = Cycles,
stencilPushUtils = stencilPushUtilsModule,
logger = console,
} = {}) {
this._browserSync = browserSync;
Expand All @@ -36,6 +38,7 @@ class StencilStart {
this._buildConfigManger = buildConfigManger;
this._templateAssembler = templateAssembler;
this._CyclesDetector = CyclesDetector;
this._stencilPushUtils = stencilPushUtils;
this._logger = logger;
}

Expand All @@ -45,13 +48,14 @@ class StencilStart {
if (cliOptions.variation) {
await this._themeConfigManager.setVariationByName(cliOptions.variation);
}

const initialStencilConfig = await this._stencilConfigManager.read();
// Use initial (before updates) port for BrowserSync
const browserSyncPort = initialStencilConfig.port;

const channelUrl = await this.getChannelUrl(initialStencilConfig, cliOptions);

const storeInfoFromAPI = await this._themeApiClient.checkCliVersion({
storeUrl: initialStencilConfig.normalStoreUrl,
storeUrl: channelUrl,
});
const updatedStencilConfig = this.updateStencilConfig(
initialStencilConfig,
Expand All @@ -65,6 +69,28 @@ class StencilStart {
await this.startBrowserSync(cliOptions, updatedStencilConfig, browserSyncPort);
}

async getChannelUrl(stencilConfig, cliOptions) {
const { accessToken } = stencilConfig;
const { apiHost } = cliOptions;
const storeHash = await this._themeApiClient.getStoreHash({
storeUrl: stencilConfig.normalStoreUrl,
});
const channels = await this._themeApiClient.getStoreChannels({
storeHash,
accessToken,
apiHost,
});

const channelId = cliOptions.channelId
? cliOptions.channelId
: await this._stencilPushUtils.promptUserToSelectChannel(channels);

const foundChannel = channels.find(
(channel) => channel.channel_id === parseInt(channelId, 10),
);
return foundChannel ? foundChannel.url : null;
}

/**
* @param {Object} cliOptions
*/
Expand Down
29 changes: 29 additions & 0 deletions lib/stencil-start.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const path = require('path');

const StencilStart = require('./stencil-start');
const stencilPushUtilsModule = require('./stencil-push.utils');

afterAll(() => jest.restoreAllMocks());

Expand All @@ -25,6 +26,9 @@ describe('StencilStart unit tests', () => {
const getBuildConfigMangerStub = () => ({});
const getTemplateAssemblerStub = () => ({});
const getCyclesDetectorConstructorStub = () => jest.fn();
const getStencilPushUtilsStub = () => ({
promptUserToSelectChannel: jest.fn(),
});
const getLoggerStub = () => ({
log: jest.fn(),
error: jest.fn(),
Expand All @@ -40,6 +44,7 @@ describe('StencilStart unit tests', () => {
buildConfigManger,
templateAssembler,
CyclesDetector,
stencilPushUtils,
logger,
} = {}) => {
const passedArgs = {
Expand All @@ -52,6 +57,7 @@ describe('StencilStart unit tests', () => {
buildConfigManger: buildConfigManger || getBuildConfigMangerStub(),
templateAssembler: templateAssembler || getTemplateAssemblerStub(),
CyclesDetector: CyclesDetector || getCyclesDetectorConstructorStub(),
stencilPushUtils: stencilPushUtils || getStencilPushUtilsStub(),
logger: logger || getLoggerStub(),
};
const instance = new StencilStart(passedArgs);
Expand Down Expand Up @@ -120,4 +126,27 @@ describe('StencilStart unit tests', () => {
expect(result).toStrictEqual(templateAssemblerResults);
});
});

describe('getChannelUrl method', () => {
const accessToken = 'accessToken_value';
const apiHost = 'apiHost_value';
const storeHash = 'storeHash_value';
const channelId = 5;
const storeUrl = 'https://www.example.com';

it('should obtain channel id from the api', async () => {
const channels = [{ channel_id: channelId, url: storeUrl }];
const themeApiClientStub = {
checkCliVersion: jest.fn(),
getStoreHash: jest.fn().mockResolvedValue(storeHash),
getStoreChannels: jest.fn().mockResolvedValue(channels),
};
const { instance } = createStencilStartInstance({
themeApiClient: themeApiClientStub,
stencilPushUtils: stencilPushUtilsModule,
});
const result = await instance.getChannelUrl({ accessToken }, { apiHost });
expect(result).toEqual(storeUrl);
});
});
});
1 change: 0 additions & 1 deletion lib/utils/NetworkUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ class NetworkUtils {
...restOpts,
headers: {
'x-auth-client': 'stencil-cli',
'x-bc-upstream': 'storefront',
'stencil-cli': this._packageInfo.version,
'stencil-version': this._packageInfo.config.stencil_version,
...(restOpts.headers || {}),
Expand Down
4 changes: 0 additions & 4 deletions lib/utils/NetworkUtils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ describe('NetworkUtils', () => {
maxBodyLength: Infinity,
headers: {
'x-auth-client': 'stencil-cli',
'x-bc-upstream': 'storefront',
'stencil-cli': packageInfoMock.version,
'stencil-version': packageInfoMock.config.stencil_version,
},
Expand Down Expand Up @@ -71,7 +70,6 @@ describe('NetworkUtils', () => {
headers: {
'content-type': extraHeaders['content-type'],
'x-auth-client': 'stencil-cli',
'x-bc-upstream': 'storefront',
'stencil-cli': packageInfoMock.version,
'stencil-version': packageInfoMock.config.stencil_version,
},
Expand Down Expand Up @@ -112,7 +110,6 @@ describe('NetworkUtils', () => {
'content-type': extraHeaders['content-type'],
'x-auth-client': extraHeaders['x-auth-client'],
'stencil-cli': extraHeaders['stencil-cli'],
'x-bc-upstream': 'storefront',
'stencil-version': packageInfoMock.config.stencil_version,
},
});
Expand Down Expand Up @@ -147,7 +144,6 @@ describe('NetworkUtils', () => {
headers: {
'x-auth-token': accessToken,
'x-auth-client': 'stencil-cli',
'x-bc-upstream': 'storefront',
'stencil-cli': packageInfoMock.version,
'stencil-version': packageInfoMock.config.stencil_version,
},
Expand Down
26 changes: 26 additions & 0 deletions server/plugins/renderer/renderer.module.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,32 @@ describe('Renderer Plugin', () => {
expect(localServerResponse.statusCode).toEqual(500);
});

describe('when the channel url is set it should be used to proxy calls to API', () => {
it('should proxy browser requests with host = secondStoreUrl', async () => {
const browserRequest = {
method: 'GET',
url: '/',
};

axiosMock.onGet().reply(200, {});

await server.inject(browserRequest);
expect(axiosMock.history.get[0].url).toEqual(`${storeUrl}${browserRequest.url}`);
});

it('should proxy storefront requests with host = secondStoreUrl', async () => {
const browserRequest = {
method: 'GET',
url: '/account.php',
};

axiosMock.onGet().reply(200, {});

await server.inject(browserRequest);
expect(axiosMock.history.get[0].url).toEqual(`${storeUrl}${browserRequest.url}`);
});
});

describe('when the storefront server response is Redirect', () => {
const browserRequest = {
method: 'post',
Expand Down
1 change: 1 addition & 0 deletions server/plugins/router/router.module.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const internals = {
storeUrl: '',
apiKey: '',
port: '',
channelId: null,
},
paths: {
renderer: '/{url*}',
Expand Down

0 comments on commit 85d7733

Please sign in to comment.