Initial Commit

+ Dockerization
+ Git Setup
+ Example Files
+ HandleBars Setup
+ Express Logic
+ Folder Structure
+ LICENSE
+ Public Folder
This commit is contained in:
Daniel Legt 2022-05-10 00:15:45 +03:00
commit 1b8292dc50
25 changed files with 3209 additions and 0 deletions

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
**/node_modules

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
# NodeJS
node_modules
# Dist
dist/*
!dist/.keep
# Ignore Project specific files
docker-compose.yaml
.env

13
Dockerfile Normal file
View File

@ -0,0 +1,13 @@
FROM node:18-alpine
# Create app directory
WORKDIR /app
# Bundle app source
COPY . .
# Install Requirements and build the app
RUN npm install && npm run build;
EXPOSE 5386
CMD [ "npm", "run", "start" ]

7
LICENSE Normal file
View File

@ -0,0 +1,7 @@
Copyright © 2021 Kato Twofold
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0
README.md Normal file
View File

0
Uploads/.keep Normal file
View File

327
Views/errors/404.html Normal file
View File

@ -0,0 +1,327 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Simple HttpErrorPages | MIT License | https://github.com/HttpErrorPages -->
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>We&#39;ve got some trouble | 400 - Bad Request</title>
<style type="text/css">
/*! normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */
html {
font-family: sans-serif;
line-height: 1.15;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%
}
body {
margin: 0
}
article,
aside,
footer,
header,
nav,
section {
display: block
}
h1 {
font-size: 2em;
margin: .67em 0
}
figcaption,
figure,
main {
display: block
}
figure {
margin: 1em 40px
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible
}
pre {
font-family: monospace, monospace;
font-size: 1em
}
a {
background-color: transparent;
-webkit-text-decoration-skip: objects
}
a:active,
a:hover {
outline-width: 0
}
abbr[title] {
border-bottom: none;
text-decoration: underline;
text-decoration: underline dotted
}
b,
strong {
font-weight: inherit
}
b,
strong {
font-weight: bolder
}
code,
kbd,
samp {
font-family: monospace, monospace;
font-size: 1em
}
dfn {
font-style: italic
}
mark {
background-color: #ff0;
color: #000
}
small {
font-size: 80%
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline
}
sub {
bottom: -.25em
}
sup {
top: -.5em
}
audio,
video {
display: inline-block
}
audio:not([controls]) {
display: none;
height: 0
}
img {
border-style: none
}
svg:not(:root) {
overflow: hidden
}
button,
input,
optgroup,
select,
textarea {
font-family: sans-serif;
font-size: 100%;
line-height: 1.15;
margin: 0
}
button,
input {
overflow: visible
}
button,
select {
text-transform: none
}
[type=reset],
[type=submit],
button,
html [type=button] {
-webkit-appearance: button
}
[type=button]::-moz-focus-inner,
[type=reset]::-moz-focus-inner,
[type=submit]::-moz-focus-inner,
button::-moz-focus-inner {
border-style: none;
padding: 0
}
[type=button]:-moz-focusring,
[type=reset]:-moz-focusring,
[type=submit]:-moz-focusring,
button:-moz-focusring {
outline: 1px dotted ButtonText
}
fieldset {
border: 1px solid silver;
margin: 0 2px;
padding: .35em .625em .75em
}
legend {
box-sizing: border-box;
color: inherit;
display: table;
max-width: 100%;
padding: 0;
white-space: normal
}
progress {
display: inline-block;
vertical-align: baseline
}
textarea {
overflow: auto
}
[type=checkbox],
[type=radio] {
box-sizing: border-box;
padding: 0
}
[type=number]::-webkit-inner-spin-button,
[type=number]::-webkit-outer-spin-button {
height: auto
}
[type=search] {
-webkit-appearance: textfield;
outline-offset: -2px
}
[type=search]::-webkit-search-cancel-button,
[type=search]::-webkit-search-decoration {
-webkit-appearance: none
}
::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit
}
details,
menu {
display: block
}
summary {
display: list-item
}
canvas {
display: inline-block
}
template {
display: none
}
[hidden] {
display: none
}
/*! Simple HttpErrorPages | MIT X11 License | https://github.com/AndiDittrich/HttpErrorPages */
body,
html {
width: 100%;
height: 100%;
background-color: #21232a
}
body {
color: #fff;
text-align: center;
text-shadow: 0 2px 4px rgba(0, 0, 0, .5);
padding: 0;
min-height: 100%;
-webkit-box-shadow: inset 0 0 100px rgba(0, 0, 0, .8);
box-shadow: inset 0 0 100px rgba(0, 0, 0, .8);
display: table;
font-family: "Open Sans", Arial, sans-serif
}
h1 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
font-size: 36px
}
h1 small {
font-size: 68%;
font-weight: 400;
line-height: 1;
color: #777
}
a {
text-decoration: none;
color: #fff;
font-size: inherit;
border-bottom: dotted 1px #707070
}
.lead {
color: silver;
font-size: 21px;
line-height: 1.4
}
.cover {
display: table-cell;
vertical-align: middle;
padding: 0 20px
}
footer {
position: fixed;
width: 100%;
height: 40px;
left: 0;
bottom: 0;
color: #a0a0a0;
font-size: 14px
}
</style>
</head>
<body>
<div class="cover">
<h1>Bad Request <small>400</small></h1>
<p class="lead">We've been looking far and wide, yet couldn't find what you're looking for 😢
</p>
</div>
</body>
</html>

68
Views/home.handlebars Normal file
View File

@ -0,0 +1,68 @@
<style>
:root {
--primary-color: #fff;
--background-color: #e5e5e5;
--text-color: #2d2d2d;
font-family: sans-serif;
}
/* 'light' or 'dark' options */
@media (prefers-color-scheme: dark) {
:root {
--primary-color: #455363;
--background-color: #1f2935;
--text-color: #fff;
}
}
body {
background-color: var(--background-color);
color: var(--text-color);
padding: 1rem;
}
.disabled {
opacity: 0.5;
pointer-events: none;
}
</style>
<h1>About</h1>
<p>Hey there, this is the main body of the content, over here you can see that this file is individual from the other
ones</p>
<p>It is completely isolated and has nothing to do with the header or the footer</p>
<br>
<h1>Examples</h1>
<p>Wanna know what date it is? It's --> {{{time}}}</p>
<br>
<h1>Example Listing</h1>
<p>
This is just some filler text 😊
</p>
<p>
Sorry about the lack of style, but I really wanted to keep this as vanilla and minimal as possible
whilst still providing a solid example for as many
things as possible.<br>
It is quite a bit more complex than the <code>master</code> branch, but it's still super useful!
</p>
<p>
Here's an example of how to use for-loops, if you are new I think this will come in handy, I know that
it was quite a bother for me to find a working example, the following works amazingly well with this
project setup.
</p>
<table>
<thead>
<tr>
<th>#</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{{#each listExample as | row |}}
<tr id="row-{{row.id}}" class="{{#if row.disabled }}disabled{{else}}enabled{{/if}}">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
</tr>
{{/each}}
</tbody>
</table>

5
Views/layouts/main.hbs Normal file
View File

@ -0,0 +1,5 @@
{{> header}}
{{{body}}}
{{> footer}}

View File

@ -0,0 +1,3 @@
</body>
</html>

20
Views/partials/header.hbs Normal file
View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
{{!-- Configuration Tags --}}
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="exercise date in seconds"/>
<meta name="robots" content="index, follow">
{{!-- Some public information --}}
<meta name="keywords" content="free, online tools, tools, free tools, free online tools, online, tools, web, convert, pdf, html, png, jpg, csv, generator, random, fakerr, faker, helper"/>
<meta name="author" content="Kato Twofold" />
<meta name="copyright" content="Kato Twofold" />
<meta name="description" content="Generate, Convert, Extract right here online, we even have an API for it!" />
{{!-- The title --}}
<title>Kato's cafe tools</title>
</head>
<body>

0
dist/.keep vendored Normal file
View File

View File

@ -0,0 +1,16 @@
version: '3.1'
# Run using docker-compose --compatibility up -d
# Otherwise it's going to ignore the deploy options.
services:
katocafe:
container_name: kato_cafe
build: .
restart: unless-stopped
ports:
- 6921:5386
# volumes:
# - hostLocation:/location/in/container
deploy:
resources:
limits:
memory: 1G

2474
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
package.json Normal file
View File

@ -0,0 +1,18 @@
{
"scripts": {
"start": "node ./dist/app.js",
"test": "cd src && ts-node-dev --respawn app.ts",
"build": "tsc"
},
"devDependencies": {
"ts-node-dev": "^1.1.8"
},
"dependencies": {
"@types/express": "^4.17.13",
"dotenv": "^16.0.0",
"express": "^4.18.1",
"express-handlebars": "^6.0.5",
"ts-node": "^10.7.0",
"typescript": "^4.6.4"
}
}

16
src/Config/config.ts Normal file
View File

@ -0,0 +1,16 @@
// Imports
import dotenv from "dotenv";
// Load in the dotconfig configuration
dotenv.config();
// The server's port
const SERVER_PORT: string = process.env.SERVER_PORT || '5386';
// The whole configuration
const config = {
serverPort: SERVER_PORT,
devmode: !!process.env.DEV_MODE,
};
export default config;

View File

@ -0,0 +1,26 @@
import { Request, Response, NextFunction, Router } from 'express';
const homepageController = ( req:Request, res:Response, next:NextFunction ) => {
// Make sure that the browser isn't caching this
res.setHeader(`Cache-Control`, `no-cache, must-revalidate`);
res.setHeader(`Pragma`, `no-cache`);
res.setHeader(`Expires`, `Sat, 26 Jul 1997 05:00:00 GMT`);
// Render the home page
res.render('home', {
// This is a simple variable
title: 'Page Title',
// A simple list example for the loops
listExample: {
0: {id: 0, name: `ZERO`},
1: {id: 1, name: `First`, disabled: true},
2: {id: 2, name: `Second`},
3: {id: 3, name: `Third`},
},
// layout: 'main', // Change this from main to your layout ( from the layouts folder ) if you so wish, it's basically the wrapper of it all
time: new Date().toLocaleDateString()
});
}
export { homepageController }

0
src/Helpers/.keep Normal file
View File

0
src/Models/.keep Normal file
View File

12
src/Routes/Homepage.ts Normal file
View File

@ -0,0 +1,12 @@
// Imports
import express from 'express';
import { homepageController } from '../Controllers/Homepage';
// Get the router
const router = express.Router();
// Set the route
router.get("/", homepageController);
// Export the reouter
export {router as homepageRouter};

92
src/app.ts Normal file
View File

@ -0,0 +1,92 @@
// #region Imports
import http from 'http';
import express from 'express';
import config from './Config/config';
import { engine } from 'express-handlebars';
import { homepageRouter } from './Routes/Homepage';
//#endregion
// Declare a NameSpace constant for each file so that it's easier to identify where debug messages are coming from
const NAMESPACE = `App`;
// Setup the expressJS instance
const router = express();
// Set the view engine as Handlebars
router.engine('handlebars', engine({
extname: 'hbs',
}));
router.set('view engine', 'handlebars');
router.set('views', './Views/');
// Setup the router to log all activity that is happening
router.use((req, res, next) => {
// Log the request to the server
console.info(NAMESPACE, `METHOD: [${req.method}], URL: [${req.url}], IP: [${req.socket.remoteAddress}]`);
// Whenever we finish the request, send out a message telling us what exactly has happened to it.
res.on(`finish`, () => {
console.info(NAMESPACE, `METHOD: [${req.method}], URL: [${req.url}], IP: [${req.socket.remoteAddress}], STATUS: ${res.statusCode}`);
})
// Run the next function queued for this request
next();
})
// Parse the request
router.use(express.urlencoded({ extended: false }));
router.use(express.json({ strict: false }));
// API Rules
router.use((req, res, next) => {
// Set some basic headers
res.header(`Access-Control-Allow-Origin`, `*`);
res.header(`Access-Control-Allow-Headers`, `Origin, X-Request-With, Content-Type, Accept, Authorization`);
if (req.method == 'OPTIONS') {
res.header(`Access-Control-Allow-Methods`, 'GET PATCH DELETE POST PUT');
return res.send(200).json({});
}
next();
})
// Routing
// Register the public folder where you can serve static/public data
router.use(`/public`, express.static('./src/public/'));
// Handle the homepage
router.get("/", homepageRouter);
{ // Error handling
router.use((req, res, next) => {
// Generate an error
const error = new Error(`Page Not Found`);
// Set the response to 404
res.status(404)
// Read the request's preffered response type ( default text/html )
if (!!req.headers.accept) {
// Check if HTML is acceptable
console.log(req.headers.accept);
if (req.headers.accept.includes(`text/html`)) {
return res.sendFile(`./views/errors/404.html`, { root: __dirname });
}
}
// If text/html is not accepted, then simply return a JSON
return res.json({
message: error.message
})
});
}
// Finally actually start the server and run it
const httpServer = http.createServer(router);
httpServer.listen(config.serverPort, () => {
console.info(NAMESPACE, `Server Running on Port ${config.serverPort}`)
})

0
src/public/css/.keep Normal file
View File

0
src/public/img/.keep Normal file
View File

0
src/public/js/.keep Normal file
View File

101
tsconfig.json Normal file
View File

@ -0,0 +1,101 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"lib": ["ES2020"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src/", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}