Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React web app init #24

Merged
merged 5 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ Start service (monitors for file changes and sets debug configs)
yarn start
```

To run the web app (auto-served in production):
```
cd web && yarn start
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not super happy with this because it means spinning up two distinct servers when working in dev but the react-scripts people are pretty inflexible about having react-scripts build produce dev code. Building for production is pretty fast but adding 5-10 seconds to every code change (even when nothing changed on the web app) seemed like a bit much. See: facebook/create-react-app#790

```

To debug, run the Visual Studio Code "Attach to local" launch config (port 9229)

## Running tests
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion docker/app/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ EXPOSE 9229/tcp
EXPOSE 3000/tcp

# wait for db to come up before running
CMD ["dockerize", "-wait", "tcp://db:5432", "-wait", "tcp://s3:9000", "-timeout", "10s", "node", "--inspect=0.0.0.0:9229", "built/server.js"]
CMD ["dockerize", "-wait", "tcp://db:5432", "-wait", "tcp://s3:9000", "-timeout", "10s", "node", "--inspect=0.0.0.0:9229", "build/server.js"]
13 changes: 6 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"busboy-body-parser": "^0.3.2",
"connect-busboy": "0.0.2",
"dateformat": "^3.0.3",
"eslint": "^5.15.0",
"eslint": "^7.11.0",
"express": "^4.16.4",
"express-fileupload": "^1.1.1-alpha.3",
"firebase-admin": "^9.4.1",
Expand All @@ -44,7 +44,7 @@
"ts-node": "^8.8.1",
"tsc": "^1.20150623.0",
"twilio": "^3.41.1",
"typescript": "^3.8.3",
"typescript": "^4.1.2",
"umzug": "^2.3.0",
"uuid": "^3.3.2"
},
Expand All @@ -62,12 +62,12 @@
"supertest": "^4.0.2"
},
"scripts": {
"build": "tsc",
"build": "tsc && (cd ./web && yarn run build)",
Copy link
Contributor Author

@brad-richardson brad-richardson Mar 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want to clean this up in the future but I don't know enough to know best practices. I found a few variations but pulled some inspiration from this: https://medium.com/codeduck/a-real-world-project-typescript-express-and-react-4701c0458e9c

The gist of it is that we compile the minified typescript and then move that to the /build folder to serve up from the same output as the server.

"deps": "docker-compose -f docker-compose.deps.yml up",
"test": "docker-compose -f docker-compose.test.yml up --build --abort-on-container-exit",
"test:local": "yarn run build && node --inspect=0.0.0.0:9228 built/test-run.js",
"test:local": "yarn run build && node --inspect=0.0.0.0:9228 build/test-run.js",
"start": "nodemon",
"start:prod": "node built/server.js"
"start:prod": "node build/server.js"
},
"repository": {
"type": "git",
Expand All @@ -76,6 +76,5 @@
"keywords": [],
"author": "",
"license": "ISC",
"homepage": "https://bitbucket.org/kkendall33/carswaddleserver#readme",
"description": ""
"homepage": "https://bitbucket.org/kkendall33/carswaddleserver#readme"
}
10 changes: 5 additions & 5 deletions src/controllers/vehicle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class VehicleService {
}
}

public async createVehicle(toCreate, user): Promise<any> {
public async createVehicle(toCreate: any, user: any): Promise<any> {
if (!VehicleService.isValidVehicle(toCreate)) {
return Promise.reject(new Error('Must provide one of vin, licensePlate or vehicleDescription.'));
}
Expand All @@ -68,7 +68,7 @@ export class VehicleService {
return this.getVehicle(vehicleID);
}

public async updateVehicle(updated, user): Promise<any> {
public async updateVehicle(updated: any, user: any): Promise<any> {
if (!VehicleService.isValidVehicle(updated)) {
return Promise.reject(new Error('Must provide one of vin, licensePlate or vehicleDescription.'));
}
Expand Down Expand Up @@ -104,7 +104,7 @@ export class VehicleService {
return this.getVehicle(updated.id);
}

private buildVehicleDescription(descriptionJSON, vehicleID): any {
private buildVehicleDescription(descriptionJSON: any, vehicleID: string): any {
return this.models.VehicleDescription.build({
id: uuidV1(),
make: descriptionJSON.make,
Expand All @@ -116,7 +116,7 @@ export class VehicleService {
});
}

public static isValidVehicle(v): boolean {
public static isValidVehicle(v: any): boolean {
if (!v) {
return false;
}
Expand All @@ -126,7 +126,7 @@ export class VehicleService {
return hasVin || hasLicensePlate || hasDescription;
}

public static isValidDescription(d): boolean {
public static isValidDescription(d: any): boolean {
return d && Util.areStrings(d.make, d.model) && Util.isNullOrNumber(d.year) && Util.areNullOrStrings(d.style, d.trim);
}

Expand Down
30 changes: 15 additions & 15 deletions src/data/vehicle-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,45 @@ const Database = require("better-sqlite3");
const db = new Database(__dirname + "/../../resources/vehicle-lookup.db", {readonly: true, fileMustExist: true, verbose: console.log});

class VehicleSpecs {
id: number
year: number
make: string
model: string
engine: string
quarts: number
oilRating: string
viscosity: string
viscosityAlt: string
filter: string
id!: number
year!: number
make!: string
model!: string
engine!: string
quarts!: number
oilRating!: string
viscosity!: string
viscosityAlt!: string
filter!: string
}

export class VehicleLookup {
static listYears(make?: string, model?: string): number[] {
const prep = this.queryPrep(make, model);
const stmt = db.prepare("SELECT DISTINCT v.year FROM vehicle v WHERE v.id IN (SELECT docid FROM vehicle_fts " + prep.whereClause + ") ORDER BY v.year DESC");

return stmt.all(prep.params).map(x => x.year);
return stmt.all(prep.params).map((x: VehicleSpecs) => x.year);
}

static listMakes(make?: string, year?: number): string[] {
const prep = this.queryPrep(make, null, year);
const stmt = db.prepare("SELECT DISTINCT v.make FROM vehicle v WHERE v.id IN (SELECT docid FROM vehicle_fts " + prep.whereClause + ") ORDER BY v.make");

return stmt.all(prep.params).map(x => x.make);
return stmt.all(prep.params).map((x: VehicleSpecs) => x.make);
}

static listModels(make: string, model?: string, year?: number): string[] {
const prep = this.queryPrep(make, model, year);
const stmt = db.prepare("SELECT DISTINCT v.model FROM vehicle v WHERE v.id IN (SELECT docid FROM vehicle_fts " + prep.whereClause + ") ORDER BY v.model");

return stmt.all(prep.params).map(x => x.model);
return stmt.all(prep.params).map((x: VehicleSpecs) => x.model);
}

static listEngines(make: string, model: string, year: number, engine?: string): string[] {
const prep = this.queryPrep(make, model, year, engine);
const stmt = db.prepare("SELECT v.engine FROM vehicle v WHERE v.id IN (SELECT docid FROM vehicle_fts " + prep.whereClause + ") ORDER BY v.id");

return stmt.all(prep.params).map(x => x.engine);
return stmt.all(prep.params).map((x: VehicleSpecs) => x.engine);
}

static getVehicleSpecs(make: string, model: string, year?: number, engine?: string): VehicleSpecs {
Expand All @@ -50,7 +50,7 @@ export class VehicleLookup {
return stmt.get(prep.params);
}

private static queryPrep(make?: string, model?: string, year?: number, engine?: string): any {
private static queryPrep(make?: string, model?: string | null, year?: number, engine?: string): any {
var ftsMatchTokens = [];
if (year) {
ftsMatchTokens.push("year:" +year)
Expand Down
3 changes: 2 additions & 1 deletion src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ console.log(__dirname)
// bodyParser.limit = '500mb';

const app = express();
app.use(express.static(__dirname + '/../www'));
app.use(pino);

express.static.mime.define({'application/pkcs7-mime': ['apple-app-site-association']});
Expand All @@ -34,3 +33,5 @@ console.log('working on ' + port);
const passport = require('./passport')(models);

require('./routes')(app, models, passport);
// Should serve from /build/public
app.use(express.static(__dirname + '/public'));
2 changes: 1 addition & 1 deletion src/test-run.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ console.log(body);
function runTests(token) {
process.env.TEST_JWT = token;
var args = process.argv.slice(2);
var testsToRun = args[0] || './built/test/**/*.*s'
var testsToRun = args[0] || './build/test/**/*.*s'
execSync(
'mocha ' + testsToRun,
{stdio: 'inherit'}
Expand Down
8 changes: 4 additions & 4 deletions src/test/integration/vehicleIT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('Vehicle api', function() {
})
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.equal(resp.body.vehicleDescription.make, 'Toyota');
assert.equal(resp.body.vehicleDescription.model, 'Corolla');
assert.equal(resp.body.vehicleDescription.trim, 'LE');
Expand All @@ -37,7 +37,7 @@ describe('Vehicle api', function() {
})
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.equal(resp.body.licensePlate, 'ABC 123');
assert.equal(resp.body.state, 'UT');
})
Expand All @@ -51,7 +51,7 @@ describe('Vehicle api', function() {
})
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
console.log("NEXT");
host_request.put('/api/vehicle')
.send({
Expand All @@ -62,7 +62,7 @@ describe('Vehicle api', function() {
}
})
.expect(200)
.then(r => {
.then((r: any) => {
assert.isNull(r.body.licensePlate);
assert.isNull(r.body.state);
assert.equal(r.body.vehicleDescription.make, 'Toyota');
Expand Down
14 changes: 7 additions & 7 deletions src/test/integration/vehicleLookupIT.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/MAKE?make=Toy')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 'Toyota');
})
});
Expand All @@ -20,7 +20,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/MODEL?make=Toyota')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 'Corolla');
})
});
Expand All @@ -29,7 +29,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/MODEL?make=Toyota&model=Coro')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 'Corolla');
})
});
Expand All @@ -38,7 +38,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/MODEL?make=Toyota&model=Corolla')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 'Corolla');
})
});
Expand All @@ -47,7 +47,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/YEAR?make=Toyota&model=Corolla')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 2018);
})
});
Expand All @@ -56,7 +56,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup/ENGINE?make=Toyota&model=Corolla&year=2018')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
assert.include(resp.body, 'L 4-Cyl 1.8 (2ZR-FE) (GAS)');
})
});
Expand All @@ -65,7 +65,7 @@ describe('Vehicle lookup api', function() {
return host_request.get('/api/vehicle/lookup?make=Toyota&model=Sienna&year=2018&engine=LE 6-Cyl 3.5 (2GR-FKS) (GAS)')
.set("Authorization", "bearer " + jwt)
.expect(200)
.then(resp => {
.then((resp: any) => {
const vehicle = resp.body;
assert.equal(vehicle.year, 2018);
assert.equal(vehicle.make, 'Toyota');
Expand Down
54 changes: 5 additions & 49 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,65 +7,21 @@
"lib": ["es6"], /* 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": "built", /* Redirect output structure to the directory. */
"outDir": "build", /* Redirect output structure to the directory. */
"rootDir": "src", /* 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. */
"noEmitOnError": true, // Don't emit js outputs on error
// "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 */
"esModuleInterop": true,
"resolveJsonModule": true, /* Include modules imported with '.json' extension */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"./src/**/*"
],
"exclude": [
"./src/web/**/*"
]
}
23 changes: 23 additions & 0 deletions web/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
Loading