Initial content
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
[
|
||||
{ "city": "London", "population": 8982000 },
|
||||
{ "city": "Paris", "population": 2161000 },
|
||||
{ "city": "Beijing", "population": 21540000 }
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerCustomTemplateEngine = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const features = __importStar(require("./custom_features"));
|
||||
const renderTemplate = (path, context, callback) => {
|
||||
(0, fs_1.readFile)(path, (err, data) => {
|
||||
if (err != undefined) {
|
||||
callback("Cannot generate content", undefined);
|
||||
}
|
||||
else {
|
||||
callback(undefined, parseTemplate(data.toString(), { ...context, features }));
|
||||
}
|
||||
});
|
||||
};
|
||||
const parseTemplate = (template, context) => {
|
||||
const ctx = Object.keys(context)
|
||||
.map((k) => `const ${k} = context.${k}`)
|
||||
.join(";");
|
||||
const expr = /{{(.*)}}/gm;
|
||||
return template.toString().replaceAll(expr, (match, group) => {
|
||||
const evalFunc = (expr) => {
|
||||
return eval(`${ctx};${expr}`);
|
||||
};
|
||||
try {
|
||||
if (group.trim()[0] === "@") {
|
||||
group = `features.${group.trim().substring(1)}`;
|
||||
group = group.replace(/\)$/m, ", context, evalFunc)");
|
||||
}
|
||||
let result = evalFunc(group);
|
||||
if (expr.test(result)) {
|
||||
result = parseTemplate(result, context);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (err) {
|
||||
return err;
|
||||
}
|
||||
});
|
||||
};
|
||||
const registerCustomTemplateEngine = (expressApp) => expressApp.engine("custom", renderTemplate);
|
||||
exports.registerCustomTemplateEngine = registerCustomTemplateEngine;
|
||||
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.conditional = exports.partial = exports.style = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const partial = (file, context) => {
|
||||
const path = `./${context.settings.views}/${file}.custom`;
|
||||
return (0, fs_1.readFileSync)(path, "utf-8");
|
||||
};
|
||||
exports.partial = partial;
|
||||
const conditional = (expression, trueFile, falseFile, context, evalFunc) => {
|
||||
return (0, exports.partial)(evalFunc(expression) ? trueFile : falseFile, context);
|
||||
};
|
||||
exports.conditional = conditional;
|
||||
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerFormRoutes = exports.registerFormMiddleware = void 0;
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const registerFormMiddleware = (app) => {
|
||||
app.use(express_1.default.urlencoded({ extended: true }));
|
||||
};
|
||||
exports.registerFormMiddleware = registerFormMiddleware;
|
||||
const registerFormRoutes = (app) => {
|
||||
app.get("/form", (req, resp) => {
|
||||
resp.render("age");
|
||||
});
|
||||
app.post("/form", (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body.age)
|
||||
+ Number.parseInt(req.body.years);
|
||||
const context = {
|
||||
...req.body, nextage
|
||||
};
|
||||
resp.render("age", context);
|
||||
});
|
||||
};
|
||||
exports.registerFormRoutes = registerFormRoutes;
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.santizeValue = void 0;
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
const characterMappings = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
const santizeValue = (value) => value?.replace(matchPattern, match => characterMappings[match]);
|
||||
exports.santizeValue = santizeValue;
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const http_1 = require("http");
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const http_proxy_1 = __importDefault(require("http-proxy"));
|
||||
const helmet_1 = __importDefault(require("helmet"));
|
||||
const express_handlebars_1 = require("express-handlebars");
|
||||
const forms_1 = require("./forms");
|
||||
const port = 5000;
|
||||
const expressApp = (0, express_1.default)();
|
||||
const proxy = http_proxy_1.default.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", (0, express_handlebars_1.engine)());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
expressApp.use((0, helmet_1.default)());
|
||||
expressApp.use(express_1.default.json());
|
||||
(0, forms_1.registerFormMiddleware)(expressApp);
|
||||
(0, forms_1.registerFormRoutes)(expressApp);
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
expressApp.use(express_1.default.static("static"));
|
||||
expressApp.use(express_1.default.static("node_modules/bootstrap/dist"));
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
const server = (0, http_1.createServer)(expressApp);
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
server.listen(port, () => console.log(`HTTP Server listening on port ${port}`));
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isOdd = exports.increment = exports.valueOrZero = exports.style = void 0;
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const valueOrZero = (value) => {
|
||||
return value !== undefined ? value : 0;
|
||||
};
|
||||
exports.valueOrZero = valueOrZero;
|
||||
const increment = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) + 1;
|
||||
};
|
||||
exports.increment = increment;
|
||||
const isOdd = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) % 2;
|
||||
};
|
||||
exports.isOdd = isOdd;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.testHandler = void 0;
|
||||
const testHandler = async (req, resp) => {
|
||||
resp.setHeader("Content-Type", "application/json");
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
};
|
||||
exports.testHandler = testHandler;
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getValidationResults = exports.validate = void 0;
|
||||
const validator_1 = __importDefault(require("validator"));
|
||||
const validate = (propName) => {
|
||||
const tests = {};
|
||||
const handler = (req, resp, next) => {
|
||||
const vreq = req;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
next();
|
||||
};
|
||||
handler.required = () => {
|
||||
tests.required = (val) => !validator_1.default.isEmpty(val, { ignore_whitespace: true });
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min) => {
|
||||
tests.minLength = (val) => validator_1.default.isLength(val, { min });
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val) => validator_1.default.isInt(val);
|
||||
return handler;
|
||||
};
|
||||
return handler;
|
||||
};
|
||||
exports.validate = validate;
|
||||
const getValidationResults = (req) => {
|
||||
return req.validation || { valid: true };
|
||||
};
|
||||
exports.getValidationResults = getValidationResults;
|
||||
+5533
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "part2app",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"server": "tsc-watch --noClear --onsuccess \"node dist/server/server.js\"",
|
||||
"client": "webpack serve",
|
||||
"start": "npm-run-all --parallel server client"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"bootstrap": "^5.3.2",
|
||||
"express": "^4.18.2",
|
||||
"express-handlebars": "^7.1.2",
|
||||
"handlebars": "^4.7.8",
|
||||
"helmet": "^7.1.0",
|
||||
"http-proxy": "^1.18.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"validator": "^13.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node20": "^20.1.2",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/multer": "^1.4.11",
|
||||
"@types/node": "^20.6.1",
|
||||
"@types/validator": "^13.11.5",
|
||||
"handlebars-loader": "^1.7.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"tsc-watch": "^6.0.4",
|
||||
"typescript": "^5.2.2",
|
||||
"webpack": "^5.89.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^4.15.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// do nothing
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import validator from "validator";
|
||||
|
||||
export const validate = (propName, formdata) => {
|
||||
|
||||
const val = formdata.get(propName);
|
||||
const results = { };
|
||||
|
||||
const validationChain = {
|
||||
get propertyName() { return propName},
|
||||
get results () { return results }
|
||||
};
|
||||
validationChain.required = () => {
|
||||
results.required = !validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return validationChain;
|
||||
}
|
||||
validationChain.minLength = (min) => {
|
||||
results.minLength = validator.isLength(val, { min});
|
||||
return validationChain;
|
||||
};
|
||||
validationChain.isInteger = () => {
|
||||
results.isInteger = validator.isInt(val);
|
||||
return validationChain;
|
||||
}
|
||||
return validationChain;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import express, { Express } from "express";
|
||||
|
||||
export const registerFormMiddleware = (app: Express) => {
|
||||
app.use(express.urlencoded({extended: true}))
|
||||
}
|
||||
|
||||
export const registerFormRoutes = (app: Express) => {
|
||||
|
||||
app.get("/form", (req, resp) => {
|
||||
resp.render("age");
|
||||
});
|
||||
|
||||
app.post("/form", (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body.age)
|
||||
+ Number.parseInt(req.body.years);
|
||||
const context = {
|
||||
...req.body, nextage
|
||||
};
|
||||
resp.render("age", context);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
|
||||
const characterMappings: Record<string, string> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
|
||||
export const santizeValue = (value: string) =>
|
||||
value?.replace(matchPattern, match => characterMappings[match]);
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createServer } from "http";
|
||||
import express, {Express } from "express";
|
||||
import httpProxy from "http-proxy";
|
||||
import helmet from "helmet";
|
||||
import { engine } from "express-handlebars";
|
||||
import { registerFormMiddleware, registerFormRoutes } from "./forms";
|
||||
|
||||
const port = 5000;
|
||||
|
||||
const expressApp: Express = express();
|
||||
|
||||
const proxy = httpProxy.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", engine());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
|
||||
expressApp.use(helmet());
|
||||
expressApp.use(express.json());
|
||||
|
||||
registerFormMiddleware(expressApp);
|
||||
registerFormRoutes(expressApp);
|
||||
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
|
||||
expressApp.use(express.static("static"));
|
||||
expressApp.use(express.static("node_modules/bootstrap/dist"));
|
||||
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
|
||||
const server = createServer(expressApp);
|
||||
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
|
||||
server.listen(port,
|
||||
() => console.log(`HTTP Server listening on port ${port}`));
|
||||
@@ -0,0 +1,15 @@
|
||||
export const style = (stylesheet: any) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
}
|
||||
|
||||
export const valueOrZero = (value: any) => {
|
||||
return value !== undefined ? value : 0;
|
||||
}
|
||||
|
||||
export const increment = (value: any) => {
|
||||
return Number(valueOrZero(value)) + 1;
|
||||
}
|
||||
|
||||
export const isOdd = (value: any) => {
|
||||
return Number(valueOrZero(value)) % 2;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export const testHandler = async (req: Request, resp: Response) => {
|
||||
resp.setHeader("Content-Type", "application/json")
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import validator from "validator";
|
||||
|
||||
type ValidatedRequest = Request & {
|
||||
validation: {
|
||||
results: { [key: string]: {
|
||||
[key: string]: boolean, valid: boolean
|
||||
} },
|
||||
valid: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export const validate = (propName: string) => {
|
||||
const tests: Record<string, (val: string) => boolean> = {};
|
||||
const handler = (req: Request, resp: Response, next: NextFunction ) => {
|
||||
|
||||
const vreq = req as ValidatedRequest;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
handler.required = () => {
|
||||
tests.required = (val: string) =>
|
||||
!validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min: number) => {
|
||||
tests.minLength = (val:string) => validator.isLength(val, { min});
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val: string) => validator.isInt(val);
|
||||
return handler;
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
export const getValidationResults = (req: Request) => {
|
||||
return (req as ValidatedRequest).validation || { valid : true }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<form action="/form">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">City</label>
|
||||
<input name="city" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">File</label>
|
||||
<input name="datafile" type="file" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary" formmethod="get">
|
||||
Submit (GET)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post">
|
||||
Submit (POST)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post"
|
||||
formenctype="multipart/form-data">
|
||||
Submit (POST/MIME)
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
export default (value) => value % 2;
|
||||
@@ -0,0 +1,37 @@
|
||||
<div class="container fluid">
|
||||
<div class="row">
|
||||
<div class="col-7">
|
||||
{{#if name}}
|
||||
<div class="m-2">
|
||||
<h4>Hello {{ name }}. You will be {{ nextage }}
|
||||
in {{ years }} years.</h4>
|
||||
</div>
|
||||
{{/if}}
|
||||
<div>
|
||||
<form id="age_form" action="/form" method="post">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control"
|
||||
value="{{ name }}"/>
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Current Age</label>
|
||||
<input name="age" class="form-control"
|
||||
value="{{ age }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Number of Years</label>
|
||||
<input name="years" class="form-control"
|
||||
value="{{ years }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-5">
|
||||
{{> history }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
<table class="table table-sm table-striped">
|
||||
<thead>
|
||||
<tr><th>Field</th><th>Value</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>Name:</td><td>{{ name }} </td></tr>
|
||||
<tr><td>City:</td><td>{{ city }} </td></tr>
|
||||
<tr><td>File:</td><td>{{ fileData }} </td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
{{{ body }}}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-secondary text-white m-2 p-2">
|
||||
Handlebars Even value: {{ valueOrZero req.query.c }}
|
||||
</h4>
|
||||
@@ -0,0 +1,13 @@
|
||||
<h4>Recent Queries</h4>
|
||||
<table class="table table-sm table-striped my-2">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Age</th><th>Years</th><th>Result</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{#unless history }}
|
||||
<tr><td colspan="4">No data available</td></tr>
|
||||
{{/unless }}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-primary text-white m-2 p-2">
|
||||
Handlebars Odd value: {{ valueOrZero req.query.c}}
|
||||
</h4>
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "@tsconfig/node20/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src/server",
|
||||
"outDir": "dist/server/"
|
||||
},
|
||||
"include": ["src/server/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import path from "path";
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default {
|
||||
mode: "development",
|
||||
entry: "./src/client/client.js",
|
||||
devtool: "source-map",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist/client"),
|
||||
filename: "bundle.js"
|
||||
},
|
||||
devServer: {
|
||||
static: ["./static"],
|
||||
port: 5100,
|
||||
client: { webSocketURL: "http://localhost:5000/ws" }
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.handlebars$/, loader: "handlebars-loader" }
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@templates": path.resolve(__dirname, "templates/client")
|
||||
}
|
||||
}
|
||||
};
|
||||
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
DROP TABLE IF EXISTS Results;
|
||||
DROP TABLE IF EXISTS Calculations;
|
||||
DROP TABLE IF EXISTS People;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Calculations` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, `age` INTEGER,
|
||||
years INTEGER, `nextage` INTEGER);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `People` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(255));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `Results` (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
calculationId INTEGER REFERENCES `Calculations` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
personId INTEGER REFERENCES `People` (`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE);
|
||||
|
||||
INSERT INTO Calculations (id, age, years, nextage) VALUES
|
||||
(1, 35, 5, 40), (2, 35, 10, 45);
|
||||
|
||||
INSERT INTO People (id, name) VALUES
|
||||
(1, 'Alice'), (2, "Bob");
|
||||
|
||||
INSERT INTO Results (calculationId, personId) VALUES
|
||||
(1, 1), (2, 2), (2, 1);
|
||||
@@ -0,0 +1,5 @@
|
||||
[
|
||||
{ "city": "London", "population": 8982000 },
|
||||
{ "city": "Paris", "population": 2161000 },
|
||||
{ "city": "Beijing", "population": 21540000 }
|
||||
]
|
||||
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerCustomTemplateEngine = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const features = __importStar(require("./custom_features"));
|
||||
const renderTemplate = (path, context, callback) => {
|
||||
(0, fs_1.readFile)(path, (err, data) => {
|
||||
if (err != undefined) {
|
||||
callback("Cannot generate content", undefined);
|
||||
}
|
||||
else {
|
||||
callback(undefined, parseTemplate(data.toString(), { ...context, features }));
|
||||
}
|
||||
});
|
||||
};
|
||||
const parseTemplate = (template, context) => {
|
||||
const ctx = Object.keys(context)
|
||||
.map((k) => `const ${k} = context.${k}`)
|
||||
.join(";");
|
||||
const expr = /{{(.*)}}/gm;
|
||||
return template.toString().replaceAll(expr, (match, group) => {
|
||||
const evalFunc = (expr) => {
|
||||
return eval(`${ctx};${expr}`);
|
||||
};
|
||||
try {
|
||||
if (group.trim()[0] === "@") {
|
||||
group = `features.${group.trim().substring(1)}`;
|
||||
group = group.replace(/\)$/m, ", context, evalFunc)");
|
||||
}
|
||||
let result = evalFunc(group);
|
||||
if (expr.test(result)) {
|
||||
result = parseTemplate(result, context);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (err) {
|
||||
return err;
|
||||
}
|
||||
});
|
||||
};
|
||||
const registerCustomTemplateEngine = (expressApp) => expressApp.engine("custom", renderTemplate);
|
||||
exports.registerCustomTemplateEngine = registerCustomTemplateEngine;
|
||||
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.conditional = exports.partial = exports.style = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const partial = (file, context) => {
|
||||
const path = `./${context.settings.views}/${file}.custom`;
|
||||
return (0, fs_1.readFileSync)(path, "utf-8");
|
||||
};
|
||||
exports.partial = partial;
|
||||
const conditional = (expression, trueFile, falseFile, context, evalFunc) => {
|
||||
return (0, exports.partial)(evalFunc(expression) ? trueFile : falseFile, context);
|
||||
};
|
||||
exports.conditional = conditional;
|
||||
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//import { SqlRepository } from "./sql_repository";
|
||||
const orm_repository_1 = require("./orm_repository");
|
||||
const repository = new orm_repository_1.OrmRepository();
|
||||
exports.default = repository;
|
||||
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fromOrmModel = exports.addSeedData = exports.defineRelationships = exports.initializeModels = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_models_1 = require("./orm_models");
|
||||
const primaryKey = {
|
||||
id: {
|
||||
type: sequelize_1.DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true
|
||||
}
|
||||
};
|
||||
const initializeModels = (sequelize) => {
|
||||
orm_models_1.Person.init({
|
||||
...primaryKey,
|
||||
name: { type: sequelize_1.DataTypes.STRING }
|
||||
}, { sequelize });
|
||||
orm_models_1.Calculation.init({
|
||||
...primaryKey,
|
||||
age: { type: sequelize_1.DataTypes.INTEGER },
|
||||
years: { type: sequelize_1.DataTypes.INTEGER },
|
||||
nextage: { type: sequelize_1.DataTypes.INTEGER },
|
||||
}, { sequelize });
|
||||
orm_models_1.ResultModel.init({
|
||||
...primaryKey,
|
||||
}, { sequelize });
|
||||
};
|
||||
exports.initializeModels = initializeModels;
|
||||
const defineRelationships = () => {
|
||||
orm_models_1.ResultModel.belongsTo(orm_models_1.Person, { foreignKey: "personId" });
|
||||
orm_models_1.ResultModel.belongsTo(orm_models_1.Calculation, { foreignKey: "calculationId" });
|
||||
};
|
||||
exports.defineRelationships = defineRelationships;
|
||||
const addSeedData = async (sequelize) => {
|
||||
await sequelize.query(`
|
||||
INSERT INTO Calculations
|
||||
(id, age, years, nextage, createdAt, updatedAt) VALUES
|
||||
(1, 35, 5, 40, date(), date()),
|
||||
(2, 35, 10, 45, date(), date())`);
|
||||
await sequelize.query(`
|
||||
INSERT INTO People (id, name, createdAt, updatedAt) VALUES
|
||||
(1, 'Alice', date(), date()), (2, "Bob", date(), date())`);
|
||||
await sequelize.query(`
|
||||
INSERT INTO ResultModels
|
||||
(calculationId, personId, createdAt, updatedAt) VALUES
|
||||
(1, 1, date(), date()), (2, 2, date(), date()),
|
||||
(2, 1, date(), date());`);
|
||||
};
|
||||
exports.addSeedData = addSeedData;
|
||||
const fromOrmModel = (model) => {
|
||||
return {
|
||||
id: model?.id || 0,
|
||||
name: model?.Person?.name || "",
|
||||
age: model?.Calculation?.age || 0,
|
||||
years: model?.Calculation?.years || 0,
|
||||
nextage: model?.Calculation?.nextage || 0
|
||||
};
|
||||
};
|
||||
exports.fromOrmModel = fromOrmModel;
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ResultModel = exports.Calculation = exports.Person = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
class Person extends sequelize_1.Model {
|
||||
}
|
||||
exports.Person = Person;
|
||||
class Calculation extends sequelize_1.Model {
|
||||
}
|
||||
exports.Calculation = Calculation;
|
||||
class ResultModel extends sequelize_1.Model {
|
||||
}
|
||||
exports.ResultModel = ResultModel;
|
||||
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OrmRepository = void 0;
|
||||
const sequelize_1 = require("sequelize");
|
||||
const orm_helpers_1 = require("./orm_helpers");
|
||||
const orm_models_1 = require("./orm_models");
|
||||
class OrmRepository {
|
||||
sequelize;
|
||||
constructor() {
|
||||
this.sequelize = new sequelize_1.Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_age.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
async initModelAndDatabase() {
|
||||
(0, orm_helpers_1.initializeModels)(this.sequelize);
|
||||
(0, orm_helpers_1.defineRelationships)();
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
await (0, orm_helpers_1.addSeedData)(this.sequelize);
|
||||
}
|
||||
async saveResult(r) {
|
||||
return await this.sequelize.transaction(async (tx) => {
|
||||
const [person] = await orm_models_1.Person.findOrCreate({
|
||||
where: { name: r.name },
|
||||
transaction: tx
|
||||
});
|
||||
const [calculation] = await orm_models_1.Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
},
|
||||
transaction: tx
|
||||
});
|
||||
return (await orm_models_1.ResultModel.create({
|
||||
personId: person.id, calculationId: calculation.id
|
||||
}, { transaction: tx })).id;
|
||||
});
|
||||
}
|
||||
async getAllResults(limit) {
|
||||
return (await orm_models_1.ResultModel.findAll({
|
||||
include: [orm_models_1.Person, orm_models_1.Calculation],
|
||||
limit,
|
||||
order: [["id", "DESC"]]
|
||||
})).map(row => (0, orm_helpers_1.fromOrmModel)(row));
|
||||
}
|
||||
async getResultsByName(name, limit) {
|
||||
return (await orm_models_1.ResultModel.findAll({
|
||||
include: [orm_models_1.Person, orm_models_1.Calculation],
|
||||
where: {
|
||||
"$Person.name$": name
|
||||
},
|
||||
limit, order: [["id", "DESC"]]
|
||||
})).map(row => (0, orm_helpers_1.fromOrmModel)(row));
|
||||
}
|
||||
}
|
||||
exports.OrmRepository = OrmRepository;
|
||||
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TransactionHelper = void 0;
|
||||
class TransactionHelper {
|
||||
steps = [];
|
||||
add(sql, params) {
|
||||
this.steps.push([sql, params]);
|
||||
return this;
|
||||
}
|
||||
run(db) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let index = 0;
|
||||
let lastRow = NaN;
|
||||
const cb = (err, rowID) => {
|
||||
if (err) {
|
||||
db.run("ROLLBACK", () => reject());
|
||||
}
|
||||
else {
|
||||
lastRow = rowID ? rowID : lastRow;
|
||||
if (++index === this.steps.length) {
|
||||
db.run("COMMIT", () => resolve(lastRow));
|
||||
}
|
||||
else {
|
||||
this.runStep(index, db, cb);
|
||||
}
|
||||
}
|
||||
};
|
||||
db.run("BEGIN", () => this.runStep(0, db, cb));
|
||||
});
|
||||
}
|
||||
runStep(idx, db, cb) {
|
||||
const [sql, params] = this.steps[idx];
|
||||
db.run(sql, params, function (err) {
|
||||
cb(err, this.lastID);
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.TransactionHelper = TransactionHelper;
|
||||
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.insertResult = exports.insertCalculation = exports.insertPerson = exports.queryByNameSql = exports.queryAllSql = void 0;
|
||||
const baseSql = `
|
||||
SELECT Results.*, name, age, years, nextage FROM Results
|
||||
INNER JOIN People ON personId = People.id
|
||||
INNER JOIN Calculations ON calculationId = Calculations.id`;
|
||||
const endSql = `ORDER BY id DESC LIMIT $limit`;
|
||||
exports.queryAllSql = `${baseSql} ${endSql}`;
|
||||
exports.queryByNameSql = `${baseSql} WHERE name = $name ${endSql}`;
|
||||
exports.insertPerson = `
|
||||
INSERT INTO People (name)
|
||||
SELECT $name
|
||||
WHERE NOT EXISTS (SELECT name FROM People WHERE name = $name)`;
|
||||
exports.insertCalculation = `
|
||||
INSERT INTO Calculations (age, years, nextage)
|
||||
SELECT $age, $years, $nextage
|
||||
WHERE NOT EXISTS
|
||||
(SELECT age, years, nextage FROM Calculations
|
||||
WHERE age = $age AND years = $years AND nextage = $nextage)`;
|
||||
exports.insertResult = `
|
||||
INSERT INTO Results (personId, calculationId)
|
||||
SELECT People.id as personId, Calculations.id as calculationId from People
|
||||
CROSS JOIN Calculations
|
||||
WHERE People.name = $name
|
||||
AND Calculations.age = $age
|
||||
AND Calculations.years = $years
|
||||
AND Calculations.nextage = $nextage`;
|
||||
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SqlRepository = void 0;
|
||||
const fs_1 = require("fs");
|
||||
const sqlite3_1 = require("sqlite3");
|
||||
const sql_queries_1 = require("./sql_queries");
|
||||
const sql_helpers_1 = require("./sql_helpers");
|
||||
class SqlRepository {
|
||||
db;
|
||||
constructor() {
|
||||
this.db = new sqlite3_1.Database("age.db");
|
||||
this.db.exec((0, fs_1.readFileSync)("age.sql").toString(), err => {
|
||||
if (err != undefined)
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
async saveResult(r) {
|
||||
return await new sql_helpers_1.TransactionHelper()
|
||||
.add(sql_queries_1.insertPerson, { $name: r.name })
|
||||
.add(sql_queries_1.insertCalculation, {
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.add(sql_queries_1.insertResult, {
|
||||
$name: r.name,
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.run(this.db);
|
||||
}
|
||||
getAllResults($limit) {
|
||||
return this.executeQuery(sql_queries_1.queryAllSql, { $limit });
|
||||
}
|
||||
getResultsByName($name, $limit) {
|
||||
return this.executeQuery(sql_queries_1.queryByNameSql, { $name, $limit });
|
||||
}
|
||||
executeQuery(sql, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, params, (err, rows) => {
|
||||
if (err == undefined) {
|
||||
resolve(rows);
|
||||
}
|
||||
else {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.SqlRepository = SqlRepository;
|
||||
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.registerFormRoutes = exports.registerFormMiddleware = void 0;
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const data_1 = __importDefault(require("./data"));
|
||||
const rowLimit = 10;
|
||||
const registerFormMiddleware = (app) => {
|
||||
app.use(express_1.default.urlencoded({ extended: true }));
|
||||
};
|
||||
exports.registerFormMiddleware = registerFormMiddleware;
|
||||
const registerFormRoutes = (app) => {
|
||||
app.get("/form", async (req, resp) => {
|
||||
resp.render("age", {
|
||||
history: await data_1.default.getAllResults(rowLimit)
|
||||
});
|
||||
});
|
||||
app.post("/form", async (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body.age)
|
||||
+ Number.parseInt(req.body.years);
|
||||
await data_1.default.saveResult({ ...req.body, nextage });
|
||||
const context = {
|
||||
...req.body, nextage,
|
||||
history: await data_1.default.getResultsByName(req.body.name, rowLimit)
|
||||
};
|
||||
resp.render("age", context);
|
||||
});
|
||||
};
|
||||
exports.registerFormRoutes = registerFormRoutes;
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.santizeValue = void 0;
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
const characterMappings = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
const santizeValue = (value) => value?.replace(matchPattern, match => characterMappings[match]);
|
||||
exports.santizeValue = santizeValue;
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const http_1 = require("http");
|
||||
const express_1 = __importDefault(require("express"));
|
||||
const http_proxy_1 = __importDefault(require("http-proxy"));
|
||||
const helmet_1 = __importDefault(require("helmet"));
|
||||
const express_handlebars_1 = require("express-handlebars");
|
||||
const forms_1 = require("./forms");
|
||||
const port = 5000;
|
||||
const expressApp = (0, express_1.default)();
|
||||
const proxy = http_proxy_1.default.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", (0, express_handlebars_1.engine)());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
expressApp.use((0, helmet_1.default)());
|
||||
expressApp.use(express_1.default.json());
|
||||
(0, forms_1.registerFormMiddleware)(expressApp);
|
||||
(0, forms_1.registerFormRoutes)(expressApp);
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
expressApp.use(express_1.default.static("static"));
|
||||
expressApp.use(express_1.default.static("node_modules/bootstrap/dist"));
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
const server = (0, http_1.createServer)(expressApp);
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
server.listen(port, () => console.log(`HTTP Server listening on port ${port}`));
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isOdd = exports.increment = exports.valueOrZero = exports.style = void 0;
|
||||
const style = (stylesheet) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
};
|
||||
exports.style = style;
|
||||
const valueOrZero = (value) => {
|
||||
return value !== undefined ? value : 0;
|
||||
};
|
||||
exports.valueOrZero = valueOrZero;
|
||||
const increment = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) + 1;
|
||||
};
|
||||
exports.increment = increment;
|
||||
const isOdd = (value) => {
|
||||
return Number((0, exports.valueOrZero)(value)) % 2;
|
||||
};
|
||||
exports.isOdd = isOdd;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.testHandler = void 0;
|
||||
const testHandler = async (req, resp) => {
|
||||
resp.setHeader("Content-Type", "application/json");
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
};
|
||||
exports.testHandler = testHandler;
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getValidationResults = exports.validate = void 0;
|
||||
const validator_1 = __importDefault(require("validator"));
|
||||
const validate = (propName) => {
|
||||
const tests = {};
|
||||
const handler = (req, resp, next) => {
|
||||
const vreq = req;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
next();
|
||||
};
|
||||
handler.required = () => {
|
||||
tests.required = (val) => !validator_1.default.isEmpty(val, { ignore_whitespace: true });
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min) => {
|
||||
tests.minLength = (val) => validator_1.default.isLength(val, { min });
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val) => validator_1.default.isInt(val);
|
||||
return handler;
|
||||
};
|
||||
return handler;
|
||||
};
|
||||
exports.validate = validate;
|
||||
const getValidationResults = (req) => {
|
||||
return req.validation || { valid: true };
|
||||
};
|
||||
exports.getValidationResults = getValidationResults;
|
||||
Binary file not shown.
+6957
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "part2app",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"server": "tsc-watch --noClear --onsuccess \"node dist/server/server.js\"",
|
||||
"client": "webpack serve",
|
||||
"start": "npm-run-all --parallel server client"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"bootstrap": "^5.3.2",
|
||||
"express": "^4.18.2",
|
||||
"express-handlebars": "^7.1.2",
|
||||
"handlebars": "^4.7.8",
|
||||
"helmet": "^7.1.0",
|
||||
"http-proxy": "^1.18.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"sequelize": "^6.35.1",
|
||||
"sqlite3": "^5.1.6",
|
||||
"validator": "^13.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tsconfig/node20": "^20.1.2",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/multer": "^1.4.11",
|
||||
"@types/node": "^20.6.1",
|
||||
"@types/validator": "^13.11.5",
|
||||
"handlebars-loader": "^1.7.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"tsc-watch": "^6.0.4",
|
||||
"typescript": "^5.2.2",
|
||||
"webpack": "^5.89.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^4.15.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// do nothing
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import validator from "validator";
|
||||
|
||||
export const validate = (propName, formdata) => {
|
||||
|
||||
const val = formdata.get(propName);
|
||||
const results = { };
|
||||
|
||||
const validationChain = {
|
||||
get propertyName() { return propName},
|
||||
get results () { return results }
|
||||
};
|
||||
validationChain.required = () => {
|
||||
results.required = !validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return validationChain;
|
||||
}
|
||||
validationChain.minLength = (min) => {
|
||||
results.minLength = validator.isLength(val, { min});
|
||||
return validationChain;
|
||||
};
|
||||
validationChain.isInteger = () => {
|
||||
results.isInteger = validator.isInt(val);
|
||||
return validationChain;
|
||||
}
|
||||
return validationChain;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Repository } from "./repository";
|
||||
//import { SqlRepository } from "./sql_repository";
|
||||
import { OrmRepository } from "./orm_repository";
|
||||
|
||||
const repository: Repository = new OrmRepository();
|
||||
export default repository;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { DataTypes, Sequelize } from "sequelize";
|
||||
import { Calculation, Person, ResultModel } from "./orm_models";
|
||||
import { Result } from "./repository";
|
||||
|
||||
const primaryKey = {
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
autoIncrement: true,
|
||||
primaryKey: true
|
||||
}
|
||||
};
|
||||
|
||||
export const initializeModels = (sequelize: Sequelize) => {
|
||||
|
||||
Person.init({
|
||||
...primaryKey,
|
||||
name: { type: DataTypes.STRING }
|
||||
}, { sequelize });
|
||||
|
||||
Calculation.init({
|
||||
...primaryKey,
|
||||
age: { type: DataTypes.INTEGER},
|
||||
years: { type: DataTypes.INTEGER},
|
||||
nextage: { type: DataTypes.INTEGER},
|
||||
}, { sequelize });
|
||||
|
||||
ResultModel.init({
|
||||
...primaryKey,
|
||||
}, { sequelize });
|
||||
}
|
||||
|
||||
export const defineRelationships = () => {
|
||||
ResultModel.belongsTo(Person, { foreignKey: "personId" });
|
||||
ResultModel.belongsTo(Calculation, { foreignKey: "calculationId"});
|
||||
}
|
||||
|
||||
export const addSeedData = async (sequelize: Sequelize) => {
|
||||
await sequelize.query(`
|
||||
INSERT INTO Calculations
|
||||
(id, age, years, nextage, createdAt, updatedAt) VALUES
|
||||
(1, 35, 5, 40, date(), date()),
|
||||
(2, 35, 10, 45, date(), date())`);
|
||||
|
||||
await sequelize.query(`
|
||||
INSERT INTO People (id, name, createdAt, updatedAt) VALUES
|
||||
(1, 'Alice', date(), date()), (2, "Bob", date(), date())`);
|
||||
|
||||
await sequelize.query(`
|
||||
INSERT INTO ResultModels
|
||||
(calculationId, personId, createdAt, updatedAt) VALUES
|
||||
(1, 1, date(), date()), (2, 2, date(), date()),
|
||||
(2, 1, date(), date());`);
|
||||
}
|
||||
|
||||
export const fromOrmModel = (model: ResultModel | null) : Result => {
|
||||
return {
|
||||
id: model?.id || 0,
|
||||
name: model?.Person?.name || "",
|
||||
age: model?.Calculation?.age || 0,
|
||||
years: model?.Calculation?.years || 0,
|
||||
nextage: model?.Calculation?.nextage || 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Model, CreationOptional, ForeignKey, InferAttributes,
|
||||
InferCreationAttributes } from "sequelize";
|
||||
|
||||
export class Person extends Model<InferAttributes<Person>,
|
||||
InferCreationAttributes<Person>> {
|
||||
|
||||
declare id?: CreationOptional<number>;
|
||||
declare name: string
|
||||
}
|
||||
|
||||
export class Calculation extends Model<InferAttributes<Calculation>,
|
||||
InferCreationAttributes<Calculation>> {
|
||||
|
||||
declare id?: CreationOptional<number>;
|
||||
declare age: number;
|
||||
declare years: number;
|
||||
declare nextage: number;
|
||||
}
|
||||
|
||||
export class ResultModel extends Model<InferAttributes<ResultModel>,
|
||||
InferCreationAttributes<ResultModel>> {
|
||||
|
||||
declare id: CreationOptional<number>;
|
||||
declare personId: ForeignKey<Person["id"]>;
|
||||
declare calculationId: ForeignKey<Calculation["id"]>;
|
||||
|
||||
declare Person?: InferAttributes<Person>;
|
||||
declare Calculation?: InferAttributes<Calculation>;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Sequelize } from "sequelize";
|
||||
import { Repository, Result } from "./repository";
|
||||
import { addSeedData, defineRelationships,
|
||||
fromOrmModel, initializeModels } from "./orm_helpers";
|
||||
import { Calculation, Person, ResultModel } from "./orm_models";
|
||||
|
||||
export class OrmRepository implements Repository {
|
||||
sequelize: Sequelize;
|
||||
|
||||
constructor() {
|
||||
this.sequelize = new Sequelize({
|
||||
dialect: "sqlite",
|
||||
storage: "orm_age.db",
|
||||
logging: console.log,
|
||||
logQueryParameters: true
|
||||
});
|
||||
this.initModelAndDatabase();
|
||||
}
|
||||
|
||||
async initModelAndDatabase() : Promise<void> {
|
||||
initializeModels(this.sequelize);
|
||||
defineRelationships();
|
||||
await this.sequelize.drop();
|
||||
await this.sequelize.sync();
|
||||
await addSeedData(this.sequelize);
|
||||
}
|
||||
|
||||
async saveResult(r: Result): Promise<number> {
|
||||
return await this.sequelize.transaction(async (tx) => {
|
||||
|
||||
const [person] = await Person.findOrCreate({
|
||||
where: { name : r.name},
|
||||
transaction: tx
|
||||
});
|
||||
|
||||
const [calculation] = await Calculation.findOrCreate({
|
||||
where: {
|
||||
age: r.age, years: r.years, nextage: r.nextage
|
||||
},
|
||||
transaction: tx
|
||||
});
|
||||
|
||||
return (await ResultModel.create({
|
||||
personId: person.id, calculationId: calculation.id},
|
||||
{transaction: tx})).id;
|
||||
});
|
||||
}
|
||||
|
||||
async getAllResults(limit: number): Promise<Result[]> {
|
||||
return (await ResultModel.findAll({
|
||||
include: [Person, Calculation],
|
||||
limit,
|
||||
order: [["id", "DESC"]]
|
||||
})).map(row => fromOrmModel(row));
|
||||
}
|
||||
|
||||
async getResultsByName(name: string, limit: number): Promise<Result[]> {
|
||||
return (await ResultModel.findAll({
|
||||
include: [Person, Calculation],
|
||||
where: {
|
||||
"$Person.name$": name
|
||||
},
|
||||
limit, order: [["id", "DESC"]]
|
||||
})).map(row => fromOrmModel(row));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface Result {
|
||||
id: number,
|
||||
name: string,
|
||||
age: number,
|
||||
years: number,
|
||||
nextage: number
|
||||
}
|
||||
|
||||
export interface Repository {
|
||||
|
||||
saveResult(r: Result): Promise<number>;
|
||||
|
||||
getAllResults(limit: number) : Promise<Result[]>;
|
||||
|
||||
getResultsByName(name: string, limit: number): Promise<Result[]>;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Database } from "sqlite3";
|
||||
|
||||
export class TransactionHelper {
|
||||
steps: [sql: string, params: any][] = [];
|
||||
|
||||
add(sql: string, params: any): TransactionHelper {
|
||||
this.steps.push([sql, params]);
|
||||
return this;
|
||||
}
|
||||
|
||||
run(db: Database): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let index = 0;
|
||||
let lastRow: number = NaN;
|
||||
const cb = (err: any, rowID?: number) => {
|
||||
if (err) {
|
||||
db.run("ROLLBACK", () => reject());
|
||||
} else {
|
||||
lastRow = rowID ? rowID : lastRow;
|
||||
if (++index === this.steps.length) {
|
||||
db.run("COMMIT", () => resolve(lastRow));
|
||||
} else {
|
||||
this.runStep(index, db, cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
db.run("BEGIN", () => this.runStep(0, db, cb));
|
||||
});
|
||||
}
|
||||
|
||||
runStep(idx: number, db: Database, cb: (err: any, row: number) => void) {
|
||||
const [sql, params] = this.steps[idx];
|
||||
db.run(sql, params, function (err: any) {
|
||||
cb(err, this.lastID)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
const baseSql = `
|
||||
SELECT Results.*, name, age, years, nextage FROM Results
|
||||
INNER JOIN People ON personId = People.id
|
||||
INNER JOIN Calculations ON calculationId = Calculations.id`;
|
||||
|
||||
const endSql = `ORDER BY id DESC LIMIT $limit`;
|
||||
|
||||
export const queryAllSql = `${baseSql} ${endSql}`;
|
||||
|
||||
export const queryByNameSql = `${baseSql} WHERE name = $name ${endSql}`;
|
||||
|
||||
export const insertPerson = `
|
||||
INSERT INTO People (name)
|
||||
SELECT $name
|
||||
WHERE NOT EXISTS (SELECT name FROM People WHERE name = $name)`;
|
||||
|
||||
export const insertCalculation = `
|
||||
INSERT INTO Calculations (age, years, nextage)
|
||||
SELECT $age, $years, $nextage
|
||||
WHERE NOT EXISTS
|
||||
(SELECT age, years, nextage FROM Calculations
|
||||
WHERE age = $age AND years = $years AND nextage = $nextage)`;
|
||||
|
||||
export const insertResult = `
|
||||
INSERT INTO Results (personId, calculationId)
|
||||
SELECT People.id as personId, Calculations.id as calculationId from People
|
||||
CROSS JOIN Calculations
|
||||
WHERE People.name = $name
|
||||
AND Calculations.age = $age
|
||||
AND Calculations.years = $years
|
||||
AND Calculations.nextage = $nextage`;
|
||||
@@ -0,0 +1,50 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { Database } from "sqlite3";
|
||||
import { Repository, Result } from "./repository";
|
||||
import { queryAllSql, queryByNameSql,
|
||||
insertPerson, insertCalculation, insertResult } from "./sql_queries";
|
||||
import { TransactionHelper } from "./sql_helpers";
|
||||
|
||||
export class SqlRepository implements Repository {
|
||||
db: Database;
|
||||
|
||||
constructor() {
|
||||
this.db = new Database("age.db");
|
||||
this.db.exec(readFileSync("age.sql").toString(), err => {
|
||||
if (err != undefined) throw err;
|
||||
});
|
||||
}
|
||||
|
||||
async saveResult(r: Result): Promise<number> {
|
||||
return await new TransactionHelper()
|
||||
.add(insertPerson, { $name: r.name })
|
||||
.add(insertCalculation, {
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.add(insertResult, {
|
||||
$name: r.name,
|
||||
$age: r.age, $years: r.years, $nextage: r.nextage
|
||||
})
|
||||
.run(this.db);
|
||||
}
|
||||
|
||||
getAllResults($limit: number): Promise<Result[]> {
|
||||
return this.executeQuery(queryAllSql, { $limit });
|
||||
}
|
||||
|
||||
getResultsByName($name: string, $limit: number): Promise<Result[]> {
|
||||
return this.executeQuery(queryByNameSql, { $name, $limit });
|
||||
}
|
||||
|
||||
executeQuery(sql: string, params: any) : Promise<Result[]> {
|
||||
return new Promise<Result[]>((resolve, reject) => {
|
||||
this.db.all<Result>(sql, params, (err, rows) => {
|
||||
if (err == undefined) {
|
||||
resolve(rows);
|
||||
} else {
|
||||
reject(err);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import express, { Express } from "express";
|
||||
import repository from "./data";
|
||||
|
||||
const rowLimit = 10;
|
||||
|
||||
export const registerFormMiddleware = (app: Express) => {
|
||||
app.use(express.urlencoded({extended: true}))
|
||||
}
|
||||
|
||||
export const registerFormRoutes = (app: Express) => {
|
||||
|
||||
app.get("/form", async (req, resp) => {
|
||||
resp.render("age", {
|
||||
history: await repository.getAllResults(rowLimit)
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/form", async (req, resp) => {
|
||||
const nextage = Number.parseInt(req.body.age)
|
||||
+ Number.parseInt(req.body.years);
|
||||
|
||||
await repository.saveResult({...req.body, nextage });
|
||||
|
||||
const context = {
|
||||
...req.body, nextage,
|
||||
history: await repository.getResultsByName(
|
||||
req.body.name, rowLimit)
|
||||
};
|
||||
resp.render("age", context);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const matchPattern = /[&<>="'`]/g;
|
||||
|
||||
const characterMappings: Record<string, string> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
"\"": """,
|
||||
"=": "=",
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
|
||||
export const santizeValue = (value: string) =>
|
||||
value?.replace(matchPattern, match => characterMappings[match]);
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createServer } from "http";
|
||||
import express, {Express } from "express";
|
||||
import httpProxy from "http-proxy";
|
||||
import helmet from "helmet";
|
||||
import { engine } from "express-handlebars";
|
||||
import { registerFormMiddleware, registerFormRoutes } from "./forms";
|
||||
|
||||
const port = 5000;
|
||||
|
||||
const expressApp: Express = express();
|
||||
|
||||
const proxy = httpProxy.createProxyServer({
|
||||
target: "http://localhost:5100", ws: true
|
||||
});
|
||||
|
||||
expressApp.set("views", "templates/server");
|
||||
expressApp.engine("handlebars", engine());
|
||||
expressApp.set("view engine", "handlebars");
|
||||
|
||||
expressApp.use(helmet());
|
||||
expressApp.use(express.json());
|
||||
|
||||
registerFormMiddleware(expressApp);
|
||||
registerFormRoutes(expressApp);
|
||||
|
||||
expressApp.use("^/$", (req, resp) => resp.redirect("/form"));
|
||||
|
||||
expressApp.use(express.static("static"));
|
||||
expressApp.use(express.static("node_modules/bootstrap/dist"));
|
||||
|
||||
expressApp.use((req, resp) => proxy.web(req, resp));
|
||||
|
||||
const server = createServer(expressApp);
|
||||
|
||||
server.on('upgrade', (req, socket, head) => proxy.ws(req, socket, head));
|
||||
|
||||
server.listen(port,
|
||||
() => console.log(`HTTP Server listening on port ${port}`));
|
||||
@@ -0,0 +1,15 @@
|
||||
export const style = (stylesheet: any) => {
|
||||
return `<link href="/css/${stylesheet}" rel="stylesheet" />`;
|
||||
}
|
||||
|
||||
export const valueOrZero = (value: any) => {
|
||||
return value !== undefined ? value : 0;
|
||||
}
|
||||
|
||||
export const increment = (value: any) => {
|
||||
return Number(valueOrZero(value)) + 1;
|
||||
}
|
||||
|
||||
export const isOdd = (value: any) => {
|
||||
return Number(valueOrZero(value)) % 2;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export const testHandler = async (req: Request, resp: Response) => {
|
||||
resp.setHeader("Content-Type", "application/json")
|
||||
resp.json(req.body);
|
||||
resp.end();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import validator from "validator";
|
||||
|
||||
type ValidatedRequest = Request & {
|
||||
validation: {
|
||||
results: { [key: string]: {
|
||||
[key: string]: boolean, valid: boolean
|
||||
} },
|
||||
valid: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export const validate = (propName: string) => {
|
||||
const tests: Record<string, (val: string) => boolean> = {};
|
||||
const handler = (req: Request, resp: Response, next: NextFunction ) => {
|
||||
|
||||
const vreq = req as ValidatedRequest;
|
||||
if (!vreq.validation) {
|
||||
vreq.validation = { results: {}, valid: true };
|
||||
}
|
||||
vreq.validation.results[propName] = { valid: true };
|
||||
|
||||
Object.keys(tests).forEach(k => {
|
||||
let valid = vreq.validation.results[propName][k]
|
||||
= tests[k](req.body?.[propName]);
|
||||
if (!valid) {
|
||||
vreq.validation.results[propName].valid = false;
|
||||
vreq.validation.valid = false;
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
handler.required = () => {
|
||||
tests.required = (val: string) =>
|
||||
!validator.isEmpty(val, { ignore_whitespace: true});
|
||||
return handler;
|
||||
};
|
||||
handler.minLength = (min: number) => {
|
||||
tests.minLength = (val:string) => validator.isLength(val, { min});
|
||||
return handler;
|
||||
};
|
||||
handler.isInteger = () => {
|
||||
tests.isInteger = (val: string) => validator.isInt(val);
|
||||
return handler;
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
export const getValidationResults = (req: Request) => {
|
||||
return (req as ValidatedRequest).validation || { valid : true }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<form action="/form">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">City</label>
|
||||
<input name="city" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">File</label>
|
||||
<input name="datafile" type="file" class="form-control" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary" formmethod="get">
|
||||
Submit (GET)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post">
|
||||
Submit (POST)
|
||||
</button>
|
||||
<button class="btn btn-primary" formmethod="post"
|
||||
formenctype="multipart/form-data">
|
||||
Submit (POST/MIME)
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
export default (value) => value % 2;
|
||||
@@ -0,0 +1,37 @@
|
||||
<div class="container fluid">
|
||||
<div class="row">
|
||||
<div class="col-7">
|
||||
{{#if name}}
|
||||
<div class="m-2">
|
||||
<h4>Hello {{ name }}. You will be {{ nextage }}
|
||||
in {{ years }} years.</h4>
|
||||
</div>
|
||||
{{/if}}
|
||||
<div>
|
||||
<form id="age_form" action="/form" method="post">
|
||||
<div class="m-2">
|
||||
<label class="form-label">Name</label>
|
||||
<input name="name" class="form-control"
|
||||
value="{{ name }}"/>
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Current Age</label>
|
||||
<input name="age" class="form-control"
|
||||
value="{{ age }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<label class="form-label">Number of Years</label>
|
||||
<input name="years" class="form-control"
|
||||
value="{{ years }}" />
|
||||
</div>
|
||||
<div class="m-2">
|
||||
<button class="btn btn-primary">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-5">
|
||||
{{> history }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
<table class="table table-sm table-striped">
|
||||
<thead>
|
||||
<tr><th>Field</th><th>Value</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>Name:</td><td>{{ name }} </td></tr>
|
||||
<tr><td>City:</td><td>{{ city }} </td></tr>
|
||||
<tr><td>File:</td><td>{{ fileData }} </td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="/bundle.js"></script>
|
||||
<link href="css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
{{{ body }}}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-secondary text-white m-2 p-2">
|
||||
Handlebars Even value: {{ valueOrZero req.query.c }}
|
||||
</h4>
|
||||
@@ -0,0 +1,21 @@
|
||||
<h4>Recent Queries</h4>
|
||||
<table class="table table-sm table-striped my-2">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Age</th><th>Years</th><th>Result</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{#unless history }}
|
||||
<tr><td colspan="4">No data available</td></tr>
|
||||
{{/unless }}
|
||||
{{#each history }}
|
||||
<tr>
|
||||
<td>{{ this.name }} </td>
|
||||
<td>{{ this.age }} </td>
|
||||
<td>{{ this.years }} </td>
|
||||
<td>{{ this.nextage }} </td>
|
||||
</tr>
|
||||
{{/each }}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -0,0 +1,3 @@
|
||||
<h4 class="bg-primary text-white m-2 p-2">
|
||||
Handlebars Odd value: {{ valueOrZero req.query.c}}
|
||||
</h4>
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "@tsconfig/node20/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src/server",
|
||||
"outDir": "dist/server/"
|
||||
},
|
||||
"include": ["src/server/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import path from "path";
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default {
|
||||
mode: "development",
|
||||
entry: "./src/client/client.js",
|
||||
devtool: "source-map",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist/client"),
|
||||
filename: "bundle.js"
|
||||
},
|
||||
devServer: {
|
||||
static: ["./static"],
|
||||
port: 5100,
|
||||
client: { webSocketURL: "http://localhost:5000/ws" }
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.handlebars$/, loader: "handlebars-loader" }
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@templates": path.resolve(__dirname, "templates/client")
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user