Merge pull request #5 from Mueller-Patrick/BETTERZON-38

Betterzon 38: Basic REST Backend for first use case
This commit is contained in:
Patrick 2020-11-29 22:45:06 +01:00 committed by GitHub
commit 717afca067
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 8865 additions and 694 deletions

5
.gitignore vendored
View File

@ -1,7 +1,7 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
**/dist
/tmp
/out-tsc
# Only exists if Bazel was run
@ -52,3 +52,6 @@ testem.log
.DS_Store
Thumbs.db
/CucumberTests/target/
# Env files
.env

View File

@ -2,7 +2,10 @@
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -1,41 +0,0 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

View File

@ -1,90 +0,0 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

7765
Backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,34 @@
{
"name": "backend",
"version": "0.0.0",
"private": true,
"name": "Backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./bin/www"
"start": "node dist/index",
"webpack": "webpack --config webpack.config.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pug": "2.0.0-beta11"
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"helmet": "^4.2.0",
"mariadb": "^2.5.1",
"typeorm": "^0.2.29"
},
"devDependencies": {
"@types/cors": "^2.8.8",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.9",
"@types/helmet": "^4.0.0",
"@types/node": "^14.14.9",
"@types/webpack": "^4.41.25",
"ts-loader": "^6.2.2",
"typescript": "^4.1.2",
"webpack": "^5.6.0",
"webpack-cli": "^3.3.12",
"webpack-node-externals": "^1.7.2"
}
}

View File

@ -1,8 +0,0 @@
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}

View File

@ -1,11 +0,0 @@
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {
title: 'Express'
});
});
module.exports = router;

View File

@ -1,9 +0,0 @@
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
module.exports = router;

View File

@ -0,0 +1,13 @@
export default class HttpException extends Error {
statusCode: number;
message: string;
error: string | null;
constructor(statusCode: number, message: string, error?: string) {
super(message);
this.statusCode = statusCode;
this.message = message;
this.error = error || null;
}
}

83
Backend/src/index.ts Normal file
View File

@ -0,0 +1,83 @@
/**
* Required External Modules
*/
import * as dotenv from 'dotenv';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import {productsRouter} from './models/products/products.router';
import {categoriesRouter} from './models/categories/categories.router';
import {manufacturersRouter} from './models/manufacturers/manufacturers.router';
import {pricesRouter} from './models/prices/prices.router';
import {vendorsRouter} from './models/vendors/vendors.router';
import {errorHandler} from './middleware/error.middleware';
import {notFoundHandler} from './middleware/notFound.middleware';
dotenv.config();
/**
* App Variables
*/
if (!process.env.PORT) {
process.exit(1);
}
const PORT: number = parseInt(process.env.PORT as string, 10);
const app = express();
/**
* App Configuration
*/
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use('/products', productsRouter);
app.use('/categories', categoriesRouter);
app.use('/manufacturers', manufacturersRouter);
app.use('/prices', pricesRouter);
app.use('/vendors', vendorsRouter);
app.use(errorHandler);
app.use(notFoundHandler);
/**
* Server Activation
*/
const server = app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
/**
* Webpack HMR Activation
*/
type ModuleId = string | number;
interface WebpackHotModule {
hot?: {
data: any;
accept(
dependencies: string[],
callback?: (updatedDependencies: ModuleId[]) => void,
): void;
accept(dependency: string, callback?: () => void): void;
accept(errHandler?: (err: Error) => void): void;
dispose(callback: (data: any) => void): void;
};
}
declare const module: WebpackHotModule;
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => server.close());
}

View File

@ -0,0 +1,15 @@
import HttpException from "../common/http-exception";
import { Request, Response, NextFunction } from "express";
export const errorHandler = (
error: HttpException,
request: Request,
response: Response,
next: NextFunction
) => {
const status = error.statusCode || 500;
const message =
error.message || "It's not you. It's us. We are having some problems.";
response.status(status).send(message);
};

View File

@ -0,0 +1,12 @@
import { Request, Response, NextFunction } from "express";
export const notFoundHandler = (
request: Request,
response: Response,
next: NextFunction
) => {
const message = "Resource not found";
response.status(404).send(message);
};

View File

@ -0,0 +1,5 @@
import {Category} from './category.interface';
export interface Categories {
[key: number]: Category;
}

View File

@ -0,0 +1,112 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import * as CategoryService from './categories.service';
import {Category} from './category.interface';
import {Categories} from './categories.interface';
/**
* Router Definition
*/
export const categoriesRouter = express.Router();
/**
* Controller Definitions
*/
// GET items/
categoriesRouter.get('/', async (req: Request, res: Response) => {
try {
const categories: Categories = await CategoryService.findAll();
res.status(200).send(categories);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:id
categoriesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const category: Category = await CategoryService.find(id);
res.status(200).send(category);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:name
categoriesRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term;
if (!term) {
res.status(400).send('Missing parameters.');
return;
}
try {
const categories: Categories = await CategoryService.findBySearchTerm(term);
res.status(200).send(categories);
} catch (e) {
res.status(404).send(e.message);
}
});
// POST items/
// categoriesRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// categoriesRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// categoriesRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -0,0 +1,135 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
import {Category} from './category.interface';
import {Categories} from './categories.interface';
/**
* Service Methods
*/
export const findAll = async (): Promise<Categories> => {
let conn;
let categRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT category_id, name FROM categories');
for (let row in rows) {
if (row !== 'meta') {
let categ: Category = {
category_id: 0,
name: ''
};
const sqlCateg = rows[row];
categ.category_id = sqlCateg.category_id;
categ.name = sqlCateg.name;
categRows.push(categ);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return categRows;
};
export const find = async (id: number): Promise<Category> => {
let conn;
let categ: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT category_id, name FROM categories WHERE category_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
categ = rows[row];
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return categ;
};
export const findBySearchTerm = async (term: string): Promise<Categories> => {
let conn;
let categRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT category_id, name FROM categories WHERE name LIKE ?', term);
for (let row in rows) {
if (row !== 'meta') {
categRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return categRows;
};
// export const create = async (newItem: Product): Promise<void> => {
// let conn;
// try {
// conn = await pool.getConnection();
// await conn.query("");
//
// } catch (err) {
// throw err;
// } finally {
// if (conn) conn.end();
// }
// };
//
// export const update = async (updatedItem: Product): Promise<void> => {
// if (models.products[updatedItem.product_id]) {
// models.products[updatedItem.product_id] = updatedItem;
// return;
// }
//
// throw new Error("No record found to update");
// };
//
// export const remove = async (id: number): Promise<void> => {
// const record: Product = models.products[id];
//
// if (record) {
// delete models.products[id];
// return;
// }
//
// throw new Error("No record found to delete");
// };

View File

@ -0,0 +1,4 @@
export interface Category {
category_id: number;
name: string;
}

View File

@ -0,0 +1,4 @@
export interface Manufacturer {
manufacturer_id: number;
name: string;
}

View File

@ -0,0 +1,5 @@
import {Manufacturer} from './manufacturer.interface';
export interface Manufacturers {
[key: number]: Manufacturer;
}

View File

@ -0,0 +1,112 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import * as ManufacturerService from './manufacturers.service';
import {Manufacturer} from './manufacturer.interface';
import {Manufacturers} from './manufacturers.interface';
/**
* Router Definition
*/
export const manufacturersRouter = express.Router();
/**
* Controller Definitions
*/
// GET items/
manufacturersRouter.get('/', async (req: Request, res: Response) => {
try {
const manufacturers: Manufacturers = await ManufacturerService.findAll();
res.status(200).send(manufacturers);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:id
manufacturersRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const manufacturer: Manufacturer = await ManufacturerService.find(id);
res.status(200).send(manufacturer);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:name
manufacturersRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term;
if (!term) {
res.status(400).send('Missing parameters.');
return;
}
try {
const manufacturer: Manufacturers = await ManufacturerService.findBySearchTerm(term);
res.status(200).send(manufacturer);
} catch (e) {
res.status(404).send(e.message);
}
});
// POST items/
// manufacturersRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// manufacturersRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// manufacturersRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -0,0 +1,135 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
import {Manufacturer} from './manufacturer.interface';
import {Manufacturers} from './manufacturers.interface';
/**
* Service Methods
*/
export const findAll = async (): Promise<Manufacturers> => {
let conn;
let manRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers');
for (let row in rows) {
if (row !== 'meta') {
let man: Manufacturer = {
manufacturer_id: 0,
name: ''
};
const sqlMan = rows[row];
man.manufacturer_id = sqlMan.manufacturer_id;
man.name = sqlMan.name;
manRows.push(man);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return manRows;
};
export const find = async (id: number): Promise<Manufacturer> => {
let conn;
let man: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE manufacturer_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
man = rows[row];
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return man;
};
export const findBySearchTerm = async (term: string): Promise<Manufacturers> => {
let conn;
let manRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT manufacturer_id, name FROM manufacturers WHERE name LIKE ?', term);
for (let row in rows) {
if (row !== 'meta') {
manRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return manRows;
};
// export const create = async (newItem: Product): Promise<void> => {
// let conn;
// try {
// conn = await pool.getConnection();
// await conn.query("");
//
// } catch (err) {
// throw err;
// } finally {
// if (conn) conn.end();
// }
// };
//
// export const update = async (updatedItem: Product): Promise<void> => {
// if (models.products[updatedItem.product_id]) {
// models.products[updatedItem.product_id] = updatedItem;
// return;
// }
//
// throw new Error("No record found to update");
// };
//
// export const remove = async (id: number): Promise<void> => {
// const record: Product = models.products[id];
//
// if (record) {
// delete models.products[id];
// return;
// }
//
// throw new Error("No record found to delete");
// };

View File

@ -0,0 +1,7 @@
export interface Price {
price_id: number;
product_id: number;
vendor_id: number;
price_in_cents: number;
timestamp: Date;
}

View File

@ -0,0 +1,5 @@
import {Price} from './price.interface';
export interface Prices {
[key: number]: Price;
}

View File

@ -0,0 +1,112 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import * as PriceService from './prices.service';
import {Price} from './price.interface';
import {Prices} from './prices.interface';
/**
* Router Definition
*/
export const pricesRouter = express.Router();
/**
* Controller Definitions
*/
// GET items/
pricesRouter.get('/', async (req: Request, res: Response) => {
try {
const prices: Prices = await PriceService.findAll();
res.status(200).send(prices);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:id
pricesRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const price: Price = await PriceService.find(id);
res.status(200).send(price);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:name
pricesRouter.get('/products/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const prices: Prices = await PriceService.findByProduct(id);
res.status(200).send(prices);
} catch (e) {
res.status(404).send(e.message);
}
});
// POST items/
// pricesRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// pricesRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// pricesRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -0,0 +1,140 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
import {Price} from './price.interface';
import {Prices} from './prices.interface';
/**
* Service Methods
*/
export const findAll = async (): Promise<Prices> => {
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, vendor_id, price_in_cents, timestamp FROM prices');
for (let row in rows) {
if (row !== 'meta') {
let price: Price = {
price_id: 0,
price_in_cents: 0,
product_id: 0,
timestamp: new Date(),
vendor_id: 0
};
const sqlPrice = rows[row];
price.price_id = sqlPrice.price_id;
price.product_id = sqlPrice.product_id;
price.vendor_id = sqlPrice.vendor_id;
price.price_in_cents = sqlPrice.price_in_cents;
price.timestamp = sqlPrice.timestamp;
priceRows.push(price);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return priceRows;
};
export const find = async (id: number): Promise<Price> => {
let conn;
let price: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, vendor_id, price_in_cents, timestamp FROM prices WHERE price_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
price = rows[row];
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return price;
};
export const findByProduct = async (product: number): Promise<Prices> => {
let conn;
let priceRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT price_id, product_id, vendor_id, price_in_cents, timestamp FROM prices WHERE product_id = ?', product);
for (let row in rows) {
if (row !== 'meta') {
priceRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return priceRows;
};
// export const create = async (newItem: Product): Promise<void> => {
// let conn;
// try {
// conn = await pool.getConnection();
// await conn.query("");
//
// } catch (err) {
// throw err;
// } finally {
// if (conn) conn.end();
// }
// };
//
// export const update = async (updatedItem: Product): Promise<void> => {
// if (models.products[updatedItem.product_id]) {
// models.products[updatedItem.product_id] = updatedItem;
// return;
// }
//
// throw new Error("No record found to update");
// };
//
// export const remove = async (id: number): Promise<void> => {
// const record: Product = models.products[id];
//
// if (record) {
// delete models.products[id];
// return;
// }
//
// throw new Error("No record found to delete");
// };

View File

@ -0,0 +1,14 @@
export interface Product {
product_id: number;
asin: string;
is_active: boolean;
name: string;
short_description: string;
long_description: string;
image_guid: string;
date_added: Date;
last_modified: Date;
manufacturer_id: number;
selling_rank: string;
category_id: number;
}

View File

@ -0,0 +1,5 @@
import {Product} from './product.interface';
export interface Products {
[key: number]: Product;
}

View File

@ -0,0 +1,112 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import * as ProductService from './products.service';
import {Product} from './product.interface';
import {Products} from './products.interface';
/**
* Router Definition
*/
export const productsRouter = express.Router();
/**
* Controller Definitions
*/
// GET items/
productsRouter.get('/', async (req: Request, res: Response) => {
try {
const products: Products = await ProductService.findAll();
res.status(200).send(products);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:id
productsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const product: Product = await ProductService.find(id);
res.status(200).send(product);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:name
productsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term;
if (!term) {
res.status(400).send('Missing parameters.');
return;
}
try {
const products: Products = await ProductService.findBySearchTerm(term);
res.status(200).send(products);
} catch (e) {
res.status(404).send(e.message);
}
});
// POST items/
// productsRouter.post('/', async (req: Request, res: Response) => {
// try {
// const product: Product = req.body.product;
//
// await ProductService.create(product);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// productsRouter.put('/', async (req: Request, res: Response) => {
// try {
// const product: Product = req.body.product;
//
// await ProductService.update(product);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// productsRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await ProductService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -0,0 +1,156 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
import {Product} from './product.interface';
import {Products} from './products.interface';
/**
* Service Methods
*/
export const findAll = async (): Promise<Products> => {
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products');
for (let row in rows) {
if (row !== 'meta') {
let prod: Product = {
asin: '',
category_id: 0,
date_added: new Date(),
image_guid: '',
is_active: false,
last_modified: new Date(),
long_description: '',
manufacturer_id: 0,
name: '',
product_id: 0,
selling_rank: '',
short_description: ''
};
const sqlProd = rows[row];
prod.product_id = sqlProd.product_id;
prod.name = sqlProd.name;
prod.asin = sqlProd.asin;
prod.is_active = sqlProd.is_active;
prod.short_description = sqlProd.short_description;
prod.long_description = sqlProd.long_description;
prod.image_guid = sqlProd.image_guid;
prod.date_added = sqlProd.date_added;
prod.last_modified = sqlProd.last_modified;
prod.manufacturer_id = sqlProd.manufacturer_id;
prod.selling_rank = sqlProd.selling_rank;
prod.category_id = sqlProd.category_id;
prodRows.push(prod);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return prodRows;
};
export const find = async (id: number): Promise<Product> => {
let conn;
let prod: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
prod = rows[row];
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return prod;
};
export const findBySearchTerm = async (term: string): Promise<Products> => {
let conn;
let prodRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE name LIKE ?', term);
for (let row in rows) {
if (row !== 'meta') {
prodRows.push(rows[row]);
}
}
} catch (err) {
console.log(err);
throw err;
} finally {
if (conn) {
conn.end();
}
}
return prodRows;
};
// export const create = async (newItem: Product): Promise<void> => {
// let conn;
// try {
// conn = await pool.getConnection();
// await conn.query("");
//
// } catch (err) {
// throw err;
// } finally {
// if (conn) conn.end();
// }
// };
//
// export const update = async (updatedItem: Product): Promise<void> => {
// if (models.products[updatedItem.product_id]) {
// models.products[updatedItem.product_id] = updatedItem;
// return;
// }
//
// throw new Error("No record found to update");
// };
//
// export const remove = async (id: number): Promise<void> => {
// const record: Product = models.products[id];
//
// if (record) {
// delete models.products[id];
// return;
// }
//
// throw new Error("No record found to delete");
// };

View File

@ -0,0 +1,10 @@
export interface Vendor {
vendor_id: number;
name: string;
streetname: string;
zip_code: string;
city: string;
country_code: string;
phone: string;
website: string;
}

View File

@ -0,0 +1,5 @@
import {Vendor} from './vendor.interface';
export interface Vendors {
[key: number]: Vendor;
}

View File

@ -0,0 +1,112 @@
/**
* Required External Modules and Interfaces
*/
import express, {Request, Response} from 'express';
import * as VendorService from './vendors.service';
import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface';
/**
* Router Definition
*/
export const vendorsRouter = express.Router();
/**
* Controller Definitions
*/
// GET items/
vendorsRouter.get('/', async (req: Request, res: Response) => {
try {
const vendors: Vendors = await VendorService.findAll();
res.status(200).send(vendors);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:id
vendorsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
if (!id) {
res.status(400).send('Missing parameters.');
return;
}
try {
const vendor: Vendor = await VendorService.find(id);
res.status(200).send(vendor);
} catch (e) {
res.status(404).send(e.message);
}
});
// GET items/:name
vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term;
if (!term) {
res.status(400).send('Missing parameters.');
return;
}
try {
const vendors: Vendors = await VendorService.findBySearchTerm(term);
res.status(200).send(vendors);
} catch (e) {
res.status(404).send(e.message);
}
});
// POST items/
// vendorsRouter.post('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.create(category);
//
// res.sendStatus(201);
// } catch (e) {
// res.status(404).send(e.message);
// }
// });
//
// // PUT items/
//
// vendorsRouter.put('/', async (req: Request, res: Response) => {
// try {
// const category: Category = req.body.category;
//
// await CategoryService.update(category);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });
//
// // DELETE items/:id
//
// vendorsRouter.delete('/:id', async (req: Request, res: Response) => {
// try {
// const id: number = parseInt(req.params.id, 10);
// await CategoryService.remove(id);
//
// res.sendStatus(200);
// } catch (e) {
// res.status(500).send(e.message);
// }
// });

View File

@ -0,0 +1,147 @@
import * as dotenv from 'dotenv';
dotenv.config();
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
connectionLimit: 5
});
/**
* Data Model Interfaces
*/
import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface';
/**
* Service Methods
*/
export const findAll = async (): Promise<Vendors> => {
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors');
for (let row in rows) {
if (row !== 'meta') {
let vendor: Vendor = {
city: '',
country_code: '',
name: '',
phone: '',
streetname: '',
vendor_id: 0,
website: '',
zip_code: ''
};
const sqlVendor = rows[row];
vendor.vendor_id = sqlVendor.vendor_id;
vendor.name = sqlVendor.name;
vendor.streetname = sqlVendor.streetname;
vendor.zip_code = sqlVendor.zip_code;
vendor.city = sqlVendor.city;
vendor.country_code = sqlVendor.country_code;
vendor.phone = sqlVendor.phone;
vendor.website = sqlVendor.website;
vendorRows.push(vendor);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return vendorRows;
};
export const find = async (id: number): Promise<Vendor> => {
let conn;
let vendor: any;
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE vendor_id = ?', id);
for (let row in rows) {
if (row !== 'meta') {
vendor = rows[row];
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return vendor;
};
export const findBySearchTerm = async (term: string): Promise<Vendors> => {
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
term = '%' + term + '%';
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE name LIKE ?', term);
for (let row in rows) {
if (row !== 'meta') {
vendorRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return vendorRows;
};
// export const create = async (newItem: Product): Promise<void> => {
// let conn;
// try {
// conn = await pool.getConnection();
// await conn.query("");
//
// } catch (err) {
// throw err;
// } finally {
// if (conn) conn.end();
// }
// };
//
// export const update = async (updatedItem: Product): Promise<void> => {
// if (models.products[updatedItem.product_id]) {
// models.products[updatedItem.product_id] = updatedItem;
// return;
// }
//
// throw new Error("No record found to update");
// };
//
// export const remove = async (id: number): Promise<void> => {
// const record: Product = models.products[id];
//
// if (record) {
// delete models.products[id];
// return;
// }
//
// throw new Error("No record found to delete");
// };

70
Backend/tsconfig.json Normal file
View File

@ -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": "./", /* 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. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* 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. */
}
}

View File

@ -1,6 +0,0 @@
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}

View File

@ -1,6 +0,0 @@
extends layout
block content
h1= title
p Welcome to #{title}, young Padawan! Glad you're here!
p Hello There! <br> - General Kenobi!

View File

@ -1,7 +0,0 @@
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content

32
Backend/webpack.config.ts Normal file
View File

@ -0,0 +1,32 @@
const webpack = require("webpack");
const path = require("path");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: ["webpack/hot/poll?100", "./src/index.ts"],
watch: false,
target: "node",
externals: [
nodeExternals({
whitelist: ["webpack/hot/poll?100"]
})
],
module: {
rules: [
{
test: /.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
}
]
},
mode: "development",
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
plugins: [new webpack.HotModuleReplacementPlugin()],
output: {
path: path.join(__dirname, "dist"),
filename: "index.js"
}
};

View File

@ -3,8 +3,8 @@
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/e2e" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/e2e" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />