Skip to content

Commit

Permalink
feat: ability to generate HTML when running best from cli
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Silberman committed Jun 20, 2019
1 parent 0b50ef7 commit 480e6c8
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 39 deletions.
4 changes: 2 additions & 2 deletions packages/@best/api-db/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path';
import { FrozenGlobalConfig, ApiDatabaseConfig } from '@best/types';
import { FrozenGlobalConfig, FrontendConfig } from '@best/types';
import { ApiDBAdapter } from './types';

const LOCAL_ADAPTERS = ['sql/postgres', 'sql/sqlite'];
Expand All @@ -10,7 +10,7 @@ function req(id: string) {
return r.default || r;
}

export const loadDbFromConfig = (globalConfig: FrozenGlobalConfig | { apiDatabase: ApiDatabaseConfig }): ApiDBAdapter | undefined => {
export const loadDbFromConfig = (globalConfig: FrozenGlobalConfig | FrontendConfig): ApiDBAdapter | undefined => {
const config = globalConfig.apiDatabase;
if (! config) { return; }

Expand Down
1 change: 1 addition & 0 deletions packages/@best/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@best/builder": "4.0.0",
"@best/compare": "4.0.0",
"@best/config": "4.0.0",
"@best/frontend": "4.0.0",
"@best/github-integration": "4.0.0",
"@best/console-stream": "4.0.0",
"@best/utils": "4.0.0",
Expand Down
6 changes: 4 additions & 2 deletions packages/@best/cli/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { logError } from "@best/utils";
import { runBest } from '../run_best';
import { runCompare } from '../run_compare';
import { getConfigs } from "@best/config";
import { ProjectConfigs, FrozenProjectConfig, CliConfig } from '@best/types';
import { ProjectConfigs, FrozenProjectConfig, CliConfig, BenchmarkResultsSnapshot } from '@best/types';
import { buildStaticFrontend } from '@best/frontend';

export function buildArgs(maybeArgv?: string[]): CliConfig {
const parsedArgs = yargs(maybeArgv || process.argv.slice(2))
Expand Down Expand Up @@ -103,7 +104,8 @@ export async function runCLI(argsCLI: CliConfig, projects: string[]) {
output.report(results);

if (argsCLI.generateHTML) {

const benchmarkResults: BenchmarkResultsSnapshot[] = results;
await buildStaticFrontend(benchmarkResults, globalConfig, process.stdout);
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/@best/cli/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
{ "path": "../builder" },
{ "path": "../compare" },
{ "path": "../config" },
{ "path": "../frontend" },
{ "path": "../github-integration" },
{ "path": "../console-stream" },
{ "path": "../runner" },
Expand Down
4 changes: 3 additions & 1 deletion packages/@best/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
"name": "@best/frontend",
"version": "4.0.0",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@best/api-db": "4.0.0",
"@best/types": "4.0.0",
"@lwc/rollup-plugin": "^1.0.0",
"compression": "^1.7.4",
"express": "^4.17.1",
Expand Down Expand Up @@ -71,7 +73,7 @@
"lwc:serve": "lwc-services build && lwc-services serve",
"lwc:watch": "lwc-services watch --webpack=webpack.config.js",
"api:migrate": "node-pg-migrate -m server/migrations",
"api:watch": "nodemon --watch server -e ts --exec 'NODE_ENV=development ts-node server/index.ts --files typings/index.d.ts'",
"api:watch": "nodemon --watch server -e ts --exec 'NODE_ENV=development ts-node server/serve.ts'",
"watch": "concurrently 'yarn lwc:watch' 'yarn api:watch'"
}
}
4 changes: 2 additions & 2 deletions packages/@best/frontend/server/api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Router } from 'express'
import { loadDbFromConfig } from '@best/api-db'
import { ApiDatabaseConfig } from '@best/types';
import { FrontendConfig } from '@best/types';

export default (config: { apiDatabase: ApiDatabaseConfig }): Router => {
export default (config: FrontendConfig): Router => {
const db = loadDbFromConfig(config);
const router = Router()

Expand Down
38 changes: 18 additions & 20 deletions packages/@best/frontend/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,37 @@ import express from 'express'
import helmet from 'helmet'
import compression from 'compression'
import * as path from 'path'
import { FrontendConfig } from '@best/types';

import api from './api'
import config from './best-fe.config'

// CONFIG
// FRONTEND

const PORT = process.env.PORT || 3000
const DIST_DIR = path.resolve(__dirname, '../dist/')
export const Frontend = (config: FrontendConfig): express.Application => {
// CONFIG

// EXPRESS
const DIST_DIR = path.resolve(__dirname, '../dist/')

const app: express.Application = express()
// EXPRESS

app.use(helmet())
app.use(compression())
const app: express.Application = express()

// API
app.use(helmet())
app.use(compression())

app.use('/api/v1', api(config))
// API

// FRONTEND
app.use('/api/v1', api(config))

if (process.env.NODE_ENV === 'production') {
app.use(express.static(DIST_DIR))
app.get('*', (req, res): void => res.sendFile(path.resolve(DIST_DIR, 'index.html')))
}
// FRONTEND

// LISTEN
if (process.env.NODE_ENV === 'production') {
app.use(express.static(DIST_DIR))
app.get('*', (req, res): void => res.sendFile(path.resolve(DIST_DIR, 'index.html')))
}

app.listen(PORT, (): void => {
// eslint-disable-next-line no-console
console.log('[%s] API Listening on http://localhost:%d', app.settings.env, PORT)
})
return app
}

// EXPORTS

Expand Down
21 changes: 21 additions & 0 deletions packages/@best/frontend/server/serve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import express from 'express';
import { Frontend } from './index'
import config from './best-fe.config'

/*
* NOTE:
* THIS FILE IS FOR DEVELOPMENT TESTING ONLY
*/

const PORT = process.env.PORT || 3000

const app = express()

app.use(Frontend(config))

// LISTEN

app.listen(PORT, (): void => {
// eslint-disable-next-line no-console
console.log('[%s] API Listening on http://localhost:%d', app.settings.env, PORT)
})
8 changes: 4 additions & 4 deletions packages/@best/frontend/server/static/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ const timeFromQuery = (project: { lastReleaseDate: string }, timing: string): Da
} else if (timing === '2-months') {
let date = new Date();
date.setMonth(date.getMonth() - 2);
return date
return date;
}

return undefined
return undefined;
}

const buildBranch = async (options: MockerOptions, db: ApiDBAdapter, proj: Project, branch: string): Promise<MockedSnapshotBranch> => {
Expand Down Expand Up @@ -53,8 +53,8 @@ export const buildMockedDataFromApi = async (options: MockerOptions): Promise<{

if (! db) { return null }

const allProjects = await db.fetchProjects()
const projects = allProjects.filter((proj): boolean => options.projectIds.includes(proj.id))
const allProjects = await db.fetchProjects();
const projects = allProjects.filter((proj): boolean => options.projectNames.includes(proj.name));

const snapshots: MockedSnapshots = await projects.reduce(async (acc, proj): Promise<MockedSnapshots> => {
return {
Expand Down
26 changes: 20 additions & 6 deletions packages/@best/frontend/server/static/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import path from 'path'
import fs from 'fs'
import { promisify } from 'util'
import { rollup } from 'rollup'
import { BenchmarkResultsSnapshot, FrozenGlobalConfig } from '@best/types';
import { OutputStream } from '@best/console-stream';

import rollupConfig from './rollup.config'
import config from '../best-fe.config'

const asyncRead = promisify(fs.readFile);
const asyncWrite = promisify(fs.writeFile);
Expand All @@ -13,12 +14,21 @@ const fetchTemplate = async (): Promise<string> => {
return asyncRead(path.resolve(__dirname, 'static-template.html'), 'utf8')
}

export const buildStaticFrontend = async (): Promise<boolean> => {
export const buildStaticFrontend = async (results: BenchmarkResultsSnapshot[], globalConfig: FrozenGlobalConfig, stream: NodeJS.WriteStream): Promise<boolean> => {
if (! globalConfig.apiDatabase) { throw new Error('No database configured') }

const outputStream = new OutputStream(stream, globalConfig.isInteractive);
const { branch } = globalConfig.gitInfo;

outputStream.writeln('Beginning to generate static HTML...');

const projectNames = results.map((res): string => res.projectConfig.projectName);

const options = {
projectIds: [1],
projectNames,
timingOptions: ['all', '2-months', 'last-release'],
branches: ['master'],
config
branches: [branch],
config: { apiDatabase: globalConfig.apiDatabase }
}

try {
Expand All @@ -29,9 +39,13 @@ export const buildStaticFrontend = async (): Promise<boolean> => {
const template = await fetchTemplate();
const distDir = path.resolve(__dirname, '../../dist/static');

const indexPath = path.resolve(distDir, 'index.html')
const indexPath = path.resolve(distDir, 'index.html');
await asyncWrite(indexPath, template);

outputStream.writeln(`Done generating static HTML. URL: ${indexPath}`);
} catch (err) {
outputStream.writeln('Error while trying to generate static HTML.');

return false;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/@best/frontend/server/static/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as rollup from 'rollup';
const asyncRead = promisify(fs.readFile);

export interface MockerOptions {
projectIds: number[];
projectNames: string[];
timingOptions: string[];
branches: string[];
config: { apiDatabase: ApiDatabaseConfig };
Expand Down
3 changes: 2 additions & 1 deletion packages/@best/frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"types": ["./typings"]
},
"references": [
{ "path": "../api-db" }
{ "path": "../api-db" },
{ "path": "../types" }
]
}
4 changes: 4 additions & 0 deletions packages/@best/types/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ export interface ApiDatabaseConfig {
path: string;
}

export interface FrontendConfig {
apiDatabase: ApiDatabaseConfig;
}

export interface CliConfig {
[key: string]: any,
_: string[],
Expand Down

0 comments on commit 480e6c8

Please sign in to comment.