Skip to content

Commit

Permalink
Refactor to TypeScript, rework folder structure
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbromley committed Oct 15, 2020
1 parent 33ebdf5 commit 6b70967
Show file tree
Hide file tree
Showing 25 changed files with 145 additions and 75 deletions.
7 changes: 4 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
.idea
node_modules
vendure/assets
vendure/import-assets
vendure/email/output
static/assets
static/import-assets
static/email/output
vendure.sqlite
yarn-error.log
data-cache
dist
storefront.zip
/build/
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ RUN yarn
COPY --chown=node:node . .
RUN ["chmod", "+x", "install-storefront.sh"]
RUN ["./install-storefront.sh", "v0.1.21"]
RUN ["yarn", "tsc"]
EXPOSE 3000
CMD [ "pm2-runtime", "process.json" ]
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Vendure Demo

This is a demo project used as the basis for the online Vendure demo. The index.js script populates the server using the Vendure CLI `populate` command, and then caches the generated pristine data. Every day, this cached data is restored to reset any changes which have been made to the server instance in that time.
This is a demo project used as the basis for the online Vendure demo. The src/index.ts script populates the server using the Vendure CLI `populate` command, and then caches the generated pristine data. Every day, this cached data is restored to reset any changes which have been made to the server instance in that time.

## Storefront

Expand All @@ -14,7 +14,7 @@ This version should match one of the [storefront release tags](https://github.co

## Running Locally

To run locally, install dependencies with `yarn` and then run the script with `node index.js`.
To run locally, install dependencies with `yarn` and then run the script with `yarn start`.

## Running in Docker

Expand Down
2 changes: 1 addition & 1 deletion install-storefront.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
cd "${0%/*}"
echo Fetching storefront $1...
curl https://vendure-storefront-artifacts.s3.eu-central-1.amazonaws.com/$1/vendure-storefront-build-$1.zip -L -o storefront.zip
unzip storefront.zip
unzip -o storefront.zip
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
"name": "vendure-demo",
"version": "1.0.0",
"description": "Demo of the Vendure server",
"main": "index.js",
"main": "src/index.ts",
"author": "Michael Bromley",
"license": "MIT",
"private": true,
"scripts": {
"start": "node index.js"
"start": "node build/index.js"
},
"dependencies": {
"@vendure/admin-ui-plugin": "0.16.0",
Expand All @@ -18,5 +18,8 @@
"fs-extra": "^9.0.1",
"graphql-request": "^3.1.0",
"sqlite3": "^5.0.0"
},
"devDependencies": {
"typescript": "^4.0.3"
}
}
2 changes: 1 addition & 1 deletion process.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"apps": [
{
"script": "index.js",
"script": "build/index.js",
"name": "vendure-demo",
"max_memory_restart": "1G",
"cron_restart": "0 3 */1 * *",
Expand Down
2 changes: 1 addition & 1 deletion index.js → src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { resetServer } = require('./reset-server');
import { resetServer } from './reset-server';

resetServer()
.catch(err => console.error(err));
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
// @ts-check
const fs = require('fs-extra');
const path = require('path');
const { VendurePlugin } = require('@vendure/core');
import path from 'path';
import { VendurePlugin } from '@vendure/core';

/**
* This plugin just serves the index.html file at the root.
*/
class LandingPagePlugin {

static configure(config) {
@VendurePlugin({
configuration: config => {
config.apiOptions.middleware.push({
handler: (req, res, next) => {
if (req.url.indexOf('/health') !== 0 &&
req.url.indexOf('/admin-api') !== 0 &&
req.url.indexOf('/shop-api') !== 0 &&
req.url.indexOf('/storefront') !== 0) {
const file = req.url === '/' ? 'index.html' : req.url;
res.sendFile(path.join(__dirname, file));
res.sendFile(path.join(__dirname, '../../../static/landing-page', file));
} else {
next();
}
Expand All @@ -25,13 +22,5 @@ class LandingPagePlugin {
});
return config;
}
}
Reflect.decorate([
VendurePlugin({
configuration: config => LandingPagePlugin.configure(config),
})
],
LandingPagePlugin
);

module.exports = { LandingPagePlugin };
})
export class LandingPagePlugin {}
52 changes: 27 additions & 25 deletions reset-server.js → src/reset-server.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const { bootstrap } = require('@vendure/core');
const { populate } = require('@vendure/core/cli');
const { config } = require('./vendure-config');
const { exec } = require('child_process');
const fs = require('fs-extra');
const path = require('path');
const { request } = require('graphql-request');
import { INestApplication } from '@nestjs/common';
import { bootstrap } from '@vendure/core';
import { populate } from '@vendure/core/cli';
import { config } from './vendure-config';
import fs from 'fs-extra';
import path from 'path';
import { request } from 'graphql-request';

const CACHE_DIR = 'data-cache';
let app;
const CACHE_DIR = '../data-cache';
let app: INestApplication;

// Allow graceful restarts by pm2. See http://pm2.keymetrics.io/docs/usage/signals-clean-restart/#graceful-stop
process.on('SIGINT', async () => {
Expand All @@ -25,7 +25,7 @@ process.on('SIGINT', async () => {
});


async function resetServer() {
export async function resetServer() {
console.log(`[${(new Date()).toISOString()}] Resetting Vendure server to a pristine condition...`);
if (app) {
await app.close();
Expand All @@ -42,6 +42,7 @@ async function resetServer() {
app = await bootstrap(config).catch(err => {
// tslint:disable-next-line:no-console
console.log(err);
throw err;
});
})
}
Expand All @@ -52,8 +53,8 @@ async function resetServer() {
async function clean() {
console.log(`Cleaning up data`);
await fs.remove('vendure.sqlite');
await fs.remove('vendure/assets');
await fs.remove('vendure/import-assets');
await fs.remove('static/assets');
await fs.remove('static/import-assets');
}

/**
Expand All @@ -73,22 +74,27 @@ function populateServer() {
synchronize: true,
},
importExportOptions: {
importAssetsDir: path.join(__dirname, './node_modules/@vendure/create/assets/images'),
importAssetsDir: getVendureCreateAsset('assets/images'),
},
}).then((app) => createTestCustomer().then(() => app)),
path.join(__dirname, './node_modules/@vendure/create/assets/initial-data.json'),
path.join(__dirname, './node_modules/@vendure/create/assets/products.csv'),
path.join(__dirname, './node_modules/@vendure/create/assets/images'),
getVendureCreateAsset('assets/initial-data.json'),
getVendureCreateAsset('assets/products.csv'),
).then(app => app.close());
}

function getVendureCreateAsset(fileName: string): string {
return path.join(
path.dirname(require.resolve('@vendure/create')), fileName
);
}

/**
* Copies the pristine database and product images from the cached directory.
*/
async function resetFromCache() {
console.log('Re-populating from cache');
await fs.copy(path.join(__dirname, `${CACHE_DIR}/vendure.sqlite`), path.join(__dirname, 'vendure.sqlite'));
await fs.copy(path.join(__dirname, `${CACHE_DIR}/vendure/assets`), path.join(__dirname, 'vendure/assets'));
await fs.copy(path.join(__dirname, `${CACHE_DIR}/vendure.sqlite`), path.join(__dirname, '../vendure.sqlite'));
await fs.copy(path.join(__dirname, `${CACHE_DIR}/static/assets`), path.join(__dirname, '../static/assets'));
}

/**
Expand All @@ -97,13 +103,13 @@ async function resetFromCache() {
async function cachePopulatedContent() {
if (!cacheExists()) {
console.log('Saving populated data to cache');
await fs.copy(path.join(__dirname, 'vendure.sqlite'), path.join(__dirname, `${CACHE_DIR}/vendure.sqlite`));
await fs.copy(path.join(__dirname, 'vendure/assets'), path.join(__dirname, `${CACHE_DIR}/vendure/assets`));
await fs.copy(path.join(__dirname, '../vendure.sqlite'), path.join(__dirname, `${CACHE_DIR}/vendure.sqlite`));
await fs.copy(path.join(__dirname, '../static/assets'), path.join(__dirname, `${CACHE_DIR}/static/assets`));
}
}

function cacheExists() {
return fs.existsSync(CACHE_DIR);
return fs.existsSync(path.join(__dirname, CACHE_DIR));
}

/**
Expand All @@ -127,7 +133,3 @@ function createTestCustomer() {
`;
return request('http://localhost:3000/shop-api', query);
}

module.exports = {
resetServer,
};
43 changes: 21 additions & 22 deletions vendure-config.js → src/vendure-config.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
const { AdminUiPlugin } = require('@vendure/admin-ui-plugin');
const { AssetServerPlugin } = require('@vendure/asset-server-plugin');
const { createProxyHandler, examplePaymentHandler, DefaultSearchPlugin, DefaultJobQueuePlugin } = require('@vendure/core');
const { EmailPlugin, defaultEmailHandlers } = require('@vendure/email-plugin');
const path = require('path');
const { LandingPagePlugin } = require('./landing-page/landing-page-plugin');
// @ts-check
/** @type VendureConfig */
const config = {
import { AdminUiPlugin } from '@vendure/admin-ui-plugin';
import { AssetServerPlugin } from '@vendure/asset-server-plugin';
import {
createProxyHandler,
DefaultJobQueuePlugin,
DefaultSearchPlugin,
examplePaymentHandler,
VendureConfig
} from '@vendure/core';
import { defaultEmailHandlers, EmailPlugin } from '@vendure/email-plugin';
import path from 'path';
import { LandingPagePlugin } from './plugins/landing-page/landing-page-plugin';

export const config: VendureConfig = {
apiOptions: {
port: 3000,
adminApiPath: 'admin-api',
shopApiPath: 'shop-api',
adminApiPlayground: {
settings: { 'request.credentials': 'include' },
settings: {'request.credentials': 'include'},
},
adminApiDebug: true,
shopApiPlayground: {
settings: { 'request.credentials': 'include' },
settings: {'request.credentials': 'include'},
},
shopApiDebug: true,
middleware: [{
Expand All @@ -34,17 +39,14 @@ const config = {
},
dbConnectionOptions: {
type: 'sqlite',
synchronize: false, // not working with SQLite/SQL.js, see https://github.com/typeorm/typeorm/issues/2576
synchronize: false,
logging: false,
database: path.join(__dirname, 'vendure.sqlite'),
database: path.join(__dirname, '../vendure.sqlite'),
},
paymentOptions: {
paymentMethodHandlers: [examplePaymentHandler],
},
customFields: {},
importExportOptions: {
importAssetsDir: path.join(__dirname, 'vendure/import-assets'),
},
workerOptions: {
runInMainProcess: true,
options: { port: 3222 }
Expand All @@ -53,14 +55,14 @@ const config = {
DefaultJobQueuePlugin,
AssetServerPlugin.init({
route: 'assets',
assetUploadDir: path.join(__dirname, 'vendure/assets'),
assetUploadDir: path.join(__dirname, '../static/assets'),
port: 3001,
assetUrlPrefix: 'https://demo.vendure.io/assets/'
}),
EmailPlugin.init({
handlers: defaultEmailHandlers,
templatePath: path.join(__dirname, 'vendure/email/templates'),
outputPath: path.join(__dirname, 'vendure/email/output'),
templatePath: path.join(__dirname, '../static/email/templates'),
outputPath: path.join(__dirname, '../static/email/output'),
mailboxPort: 3003,
globalTemplateVars: {
fromAddress: '"Vendure Demo Store" <[email protected]>',
Expand All @@ -76,11 +78,8 @@ const config = {
adminUiConfig: {
apiHost: 'auto',
apiPort: 'auto',
availableLanguages: ["en", "es", "zh_Hant", "zh_Hans", "pl", "de"],
},
}),
LandingPagePlugin,
],
};

module.exports = { config };
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes
File renamed without changes.
70 changes: 70 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["./src/**/*.ts"]
}
Loading

0 comments on commit 6b70967

Please sign in to comment.