Skip to content

Commit

Permalink
feat: basic execution of controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
vysinsky committed May 16, 2022
1 parent 52adf8e commit 1b5ef5d
Show file tree
Hide file tree
Showing 25 changed files with 5,482 additions and 3 deletions.
37 changes: 34 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,40 @@
name: CI
on: [push]
jobs:
build:
name: Test
test:
name: Lint, and test
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Use Node 14.x
uses: actions/setup-node@v1
with:
node-version: '14.x'

- name: Install deps and build (with cache)
uses: bahmutov/npm-install@v1

- name: Lint
run: echo "Hello"
run: yarn lint
release:
name: Release
runs-on: ubuntu-latest
needs: test
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '14.x'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.log
.DS_Store
node_modules
dist
sfcc-playground.config.js
sfra
1 change: 1 addition & 0 deletions .husky/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
_
4 changes: 4 additions & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn commitlint --edit $1
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged
22 changes: 22 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"useTabs": false,
"singleQuote": true,
"overrides": [
{
"files": "*.md",
"options": {
"printWidth": 70,
"useTabs": false,
"trailingComma": "none",
"arrowParens": "avoid",
"proseWrap": "never"
}
},
{
"files": "*.{json,babelrc,eslintrc,remarkrc,prettierrc}",
"options": {
"useTabs": false
}
}
]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Michal Vyšinský

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Salesforce Commerce Cloud Playground
1 change: 1 addition & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = { extends: ['@commitlint/config-conventional'] };
51 changes: 51 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"version": "0.0.0-development",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"src"
],
"engines": {
"node": ">=14"
},
"bin": {
"sfcc-playground": "src/index.js"
},
"scripts": {
"start": "node src/index.js",
"dev": "nodemon -q src/index.js",
"lint": "prettier --check src",
"test": "echo \"Error: no test specified\" && exit 1",
"posttest": "npm run format",
"format": "prettier --loglevel warn --write src",
"semantic-release": "semantic-release",
"prepare": "husky install"
},
"name": "sfcc-playground",
"author": "Michal Vyšinský",
"module": "dist/sfcc-playground.esm.js",
"devDependencies": {
"@commitlint/cli": "^16.2.4",
"@commitlint/config-conventional": "^16.2.4",
"husky": "^8.0.1",
"lint-staged": ">=10",
"nodemon": "^2.0.16",
"prettier": "^2.6.2",
"semantic-release": "^19.0.2"
},
"repository": {
"type": "git",
"url": "https://github.com/vysinsky/sfcc-playground.git"
},
"dependencies": {
"cosmiconfig": "^7.0.1",
"deepmerge": "^4.2.2",
"dw-api-mock": "git+https://github.com/SalesforceCommerceCloud/dw-api-mock.git",
"express": "^4.18.1",
"module-alias": "^2.2.2"
},
"lint-staged": {
"src/*": "prettier --write"
}
}
74 changes: 74 additions & 0 deletions src/aliases.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const { existsSync } = require('fs');
const moduleAlias = require('module-alias');

require('dw-api-mock/demandware-globals');
const { rootDir } = require('../sfcc-playground.config');

/**
* @param cartridgesDir {string}
* @param cartridgePath {string}
* @param modulesDir {string}
*/
function setupAliases(cartridgesDir, cartridgePath, modulesDir) {
moduleAlias.addAlias('server', `${__dirname}/server`);

moduleAlias.addAlias('*/cartridge', (fromTarget, request, alias) => {
console.debug(
`[PLAYGROUND] [ALIAS="${alias}"] Aliasing module "${request}" for "${fromTarget}"`
);

const requestedModule = request.replace('*/cartridge', 'cartridge');

for (const cartridge of cartridgePath.split(':')) {
const modulePath = `${cartridgesDir}/${cartridge}/${requestedModule}`;
console.debug(`[PLAYGROUND] Searching for module "${modulePath}"`);
if (existsSync(`${modulePath}.js`) || existsSync(`${modulePath}.json`)) {
console.debug(
`[PLAYGROUND] Alias found (${cartridgesDir}/${cartridge}/cartridge)`
);
return `${cartridgesDir}/${cartridge}/cartridge`;
}
}
});

moduleAlias.addAlias('*/modules', (fromTarget, request, alias) => {
console.debug(
`[PLAYGROUND] [ALIAS="${alias}"] Aliasing module "${request}" for "${fromTarget}"`
);

const requestedModule = request.replace('*/modules/', '');

const modulePath = `${modulesDir}/${requestedModule}`;
console.debug(`[PLAYGROUND] Searching for module "${modulePath}"`);
if (existsSync(`${modulePath}.js`) || existsSync(`${modulePath}.json`)) {
console.debug(`[PLAYGROUND] Alias found in modules`);
return modulesDir;
}
});

moduleAlias.addAlias('dw', (fromTarget, request, alias) => {
console.debug(
`[PLAYGROUND] [ALIAS="${alias}"] Aliasing module "${request}" for "${fromTarget}"`
);

const customMock = request.replace('dw', `src/mocks/dw`);

if (existsSync(`${customMock}.js`)) {
console.log('FOUND in custom mocks');

return `${__dirname}/mocks/dw`;
}

const requestedModule = request.replace(
'dw',
`${rootDir}/node_modules/dw-api-mock/dw`
);

if (existsSync(requestedModule) || existsSync(`${requestedModule}.js`)) {
console.log('FOUND in dw-api-mock');
return 'dw-api-mock/dw';
}
});
}

module.exports = setupAliases;
32 changes: 32 additions & 0 deletions src/analyzer/ControllersRegistry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { readdirSync, realpathSync } = require('fs');

class ControllersRegistry {
controllers = {};

registerAllControllers(cartridgesPath) {
cartridgesPath.split(':').forEach((cartridge) => {
const path = realpathSync(
`${__dirname}/../../sfra/cartridges/${cartridge}/cartridge/controllers`
);

readdirSync(path)
.filter((fileName) => fileName.match(/[A-Z]+/))
.forEach((fileName) => {
this.registerController(
cartridge,
fileName.replace('.js', ''),
`${path}/${fileName}`
);
});
});
}

registerController(cartridge, controller, filePath) {
this.controllers[controller] = {
cartridge,
filePath,
};
}
}

module.exports = new ControllersRegistry();
71 changes: 71 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const express = require('express');
const { cosmiconfigSync } = require('cosmiconfig');

const config = cosmiconfigSync('sfcc-playground').search()?.config || {};
global.playgroundConfig = config;

const setupAliases = require('./aliases');
setupAliases(config.cartridgesDir, config.cartridgePath, config.modulesPath);

const server = require('./server/Server');
const Session = require('./server/Session');
const Request = require('./server/Request');
const Response = require('./server/Response');
const { locateAllFilesInCartridges } = require('./utils');
const controllersRegistry = require('./analyzer/ControllersRegistry');
const Module = require('module');

const app = express();

app.get('/controllers', (req, res, next) => {
controllersRegistry.registerAllControllers(config.cartridgePath);

res.send({
controllers: controllersRegistry.controllers,
});
next();
});

app.all('/route/:route', (req, res, next) => {
server.clearRoutes();
const [controllerName, action] = req.params.route.split('-');

global.session = new Session();
global.request = new Request(req, global.customer, global.session);
global.response = new Response();

let actionFn;

locateAllFilesInCartridges(`controllers/${controllerName}`)
.reverse()
.forEach((controllerFilePath) => {
const controller = require(controllerFilePath);
Module.prototype.superModule = controller;

if (!controller[action]) {
global.response.log(
'Controller action',
action,
'not found in the controller',
controllerName
);
global.response.setStatusCode(404);
} else {
actionFn = controller[action];
}
});

if (typeof actionFn !== 'function') {
global.response.log('Controller', controllerName, 'not found');
global.response.setStatusCode(404);
} else {
actionFn();
}

res.send(global.response.toJson());
next();
});

app.listen(config.apiPort || 8080, () => {
console.log(`🚀 Salesforce playground is running on port ${config.apiPort}`);
});
7 changes: 7 additions & 0 deletions src/mocks/dw/system/Site.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const OrigSite = require('dw-api-mock/dw/system/Site');

class Site extends OrigSite {
static current = () => Site.getCurrent();
}

module.exports = Site;
4 changes: 4 additions & 0 deletions src/mocks/dw/web/CSRFProtection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
getTokenName: () => 'token_name',
generateToken: () => 'token_value',
};
25 changes: 25 additions & 0 deletions src/server/Request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Request {
error = {};

get queryString() {
return this.expressRequest.query;
}

get httpMethod() {
return this.expressRequest.method;
}

get pageMetaData() {
return {
pageMetaTags: [],
};
}

constructor(expressRequest, customer, session) {
this.expressRequest = expressRequest;
this.customer = customer;
this.session = session;
}
}

module.exports = Request;
Loading

0 comments on commit 1b5ef5d

Please sign in to comment.