express-ts skeleton

This commit is contained in:
Filip Rojek 2021-08-14 15:55:17 +02:00
parent cb19ff9c21
commit 1531f38435
38 changed files with 470 additions and 1 deletions

View File

@ -1 +0,0 @@
# node-framework

55
artisan Normal file
View File

@ -0,0 +1,55 @@
// console.log(process.argv)
let arguments = process.argv
const fs = require('fs')
if (arguments[ 2 ] == 'init')
{
let path = __dirname
let paths = [
__dirname + '/views',
__dirname + '/models',
__dirname + '/controllers',
__dirname + '/public',
__dirname + '/routes',
__dirname + '/tests',
__dirname + '/utils',
__dirname + '/',
]
let pathsTypescript = {}
for (let i = 0; i < paths.length; i++)
{
fs.mkdir(paths[ i ], (err) => {
if (err) {
console.log(err)
}
})
}
}
if (arguments[ 2 ].includes('make:'))
{
switch (arguments[ 2 ].split('make:')[ 1 ])
{
case 'view':
// console.log("\x1b[32m%s\x1b[0m", 'View created successfully.')
console.log("\x1b[33m%s\x1b[0m", 'Views coming soon.')
break
case 'model':
console.log("\x1b[32m%s\x1b[0m", 'Model created successfully.')
break
case 'controller':
console.log("\x1b[32m%s\x1b[0m", 'Controller created successfully.')
break
case 'test':
console.log("\x1b[33m%s\x1b[0m", 'Tests coming soon.')
break
case 'middleware':
console.log("\x1b[33m%s\x1b[0m", 'Middlewares coming soon.')
break
case 'routes':
console.log("\x1b[33ms\x1b[0m", 'Routes coming soon.')
break
default:
console.log("\x1b[41m\x1b[37m%s\x1b[0m", 'node artisan make:view | model | controller | test | middleware | routes')
}
}

View File

21
framework/README.md Normal file
View File

@ -0,0 +1,21 @@
# Simple node.js framework that extends express
## About
- The point of this framework is to add into express some feel of php framework Laravel.
- Primarily get simply express app into MVC architecture
## Installation
- tutorial coming soon! :)
## How to use
- coming soon!
### Artisan
- The key tool of this framework is artisan
- with that tool you can easily make view, model, controller etc. with prepared lines of code that you will have to write manually, if you didn't use some tool like this. We are programmers, we are lazy to do manual stuff :).
#### make
- make is the keyword that you will use with this framework a lot.
- make is for creating new components of your project.
- to create a view, model, controller, test or routes: `node artisan make:something`
- for example, to make an controller, you will write: `node artisan make:controller`

15
framework/install Normal file
View File

@ -0,0 +1,15 @@
#!/usr/bin/node
const fs = require('fs')
const { exec } = require("child_process");
/**
* This will only works if the project folder is in the parent folder
* This is not global fs solution!
*/
console.log(__dirname);
fs.copyFile('./framework/src/artisan', './artisan', (err) => {
err ? console.log(err) : ''
})
console.log("\x1b[32m%s\x1b[0m", "Framework installed successfully!");

View File

View File

View File

View File

View File

View File

View File

@ -0,0 +1,3 @@
node_modules/
.env
package-lock.json

View File

@ -0,0 +1 @@
# New Project

View File

@ -0,0 +1,5 @@
/** @type {import('@ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};

View File

@ -0,0 +1,45 @@
{
"name": "project-name",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"test": "jest",
"clean": "rimraf dist/*",
"copy-assets": "ts-node src/utils/copyAssets",
"tsc": "tsc -p .",
"build": "npm-run-all clean tsc copy-assets"
},
"keywords": [],
"author": "Filip Rojek",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"ejs": "^3.1.6",
"express": "^4.17.1",
"mongoose": "^5.12.3",
"morgan": "^1.10.0"
},
"devDependencies": {
"@types/cors": "^2.8.10",
"@types/ejs": "^3.0.6",
"@types/express": "^4.17.11",
"@types/fs-extra": "^9.0.12",
"@types/jest": "^26.0.24",
"@types/mongoose": "^5.10.5",
"@types/morgan": "^1.9.2",
"@types/node": "^14.14.41",
"@types/shelljs": "^0.8.9",
"fs-extra": "^10.0.0",
"jest": "^27.0.6",
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.2",
"shelljs": "^0.8.4",
"ts-jest": "^27.0.4",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}

View File

@ -0,0 +1,2 @@
APP_PORT = 8080
DB_URI = 'mongodb://username:password@localhost:27017/database?authSource=admin'

View File

@ -0,0 +1,43 @@
import express from "express";
import morgan from "morgan";
import mongoose from "mongoose";
import path from "path";
import cors from "cors";
const config = require("./utils/environment");
const routes = require("./routes");
const middlewares = require("./middlewares");
const port: Number = config.APP_PORT;
const app = express();
// MongoDB
const dbURI: string = config.DB_URI;
mongoose
.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then((result) => {
console.log("connected to db");
app.listen(port, () => {
console.log(`Server is listening on http://localhost:${port}`);
});
})
.catch((err) => {
console.log(err);
});
// Middlewares
app.use(middlewares);
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(cors());
app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Routes
app.use(routes);

View File

@ -0,0 +1,10 @@
import { Request, Response } from "express";
const root_get = (req: Request, res: Response) => {
res.render("home");
return true;
};
module.exports = {
root_get,
};

View File

@ -0,0 +1,8 @@
import { Router } from "express";
const sayHiMiddleware = require("./sayHiMiddleware");
const router = Router();
router.use(sayHiMiddleware);
module.exports = router;

View File

@ -0,0 +1,11 @@
import { Router, Request, Response, NextFunction } from "express";
const router = Router();
router.use((req: Request, res: Response, next: NextFunction) => {
console.log("Hi :)");
next();
});
module.exports = router;

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

@ -0,0 +1,13 @@
import { Router } from 'express'
const rootRoutes = require('./rootRoutes')
const router = Router()
router.use(rootRoutes)
// 404
router.use((req, res) => {
res.status(404).send('E404')
})
module.exports = router

View File

@ -0,0 +1,8 @@
const { Router } = require('express')
const rootController = require('../controllers/rootController')
const router = Router()
router.get('/', rootController.root_get)
module.exports = router

View File

@ -0,0 +1,9 @@
const { getReq, getRes } = require("./modules/reqRes.module.js");
const { root_get } = require("../controllers/rootController.ts");
test("Home page render test", () => {
const req = getReq();
const res = getRes();
expect(root_get(req, res)).toBe(true)
});

View File

@ -0,0 +1,16 @@
module.exports.getReq = () => {
const req = {};
req.body = {};
return req;
};
module.exports.getRes = () => {
const res = {};
res.locals = {};
res.status = () => res;
res.json = () => res;
res.send = () => res;
res.render = () => res;
return res;
};

View File

@ -0,0 +1,6 @@
import * as shell from "shelljs";
// Copy all the view templates
shell.cp("-R", "src/views", "dist/");
shell.cp("-R", "src/public", "dist/");
shell.cp("-u", "src/.env", "dist/");

View File

@ -0,0 +1,7 @@
import path from 'path'
require('dotenv').config({ path: path.join(__dirname, '../.env') })
module.exports = {
APP_PORT: process.env.APP_PORT,
DB_URI: process.env.DB_URI
}

View File

@ -0,0 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Project</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Open Sans', sans-serif;
}
.content {
width: 100vw;
height: 100vh;
display: flex;
justify-content: space-between;
padding-top: 5rem;
flex-direction: column;
}
footer, .welcome {
display: flex;
justify-content: center;
}
.welcome {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
img {
width: 200px;
padding-top: 2rem;
}
footer {
padding-bottom: 2rem;
text-align: center;
}
.logos {
display: flex;
align-items: center;
gap: 1rem;
}
</style>
</head>
<body>
<div class="content">
<div class="welcome">
<h1>Let's make something amazing!</h1>
<div class="logos">
<img src="/nodejs_logo.svg" alt="node.js logo">
<img src="/expressjs.png" alt="express.js logo">
</div>
</div>
<footer>
<div class="author">
<p>Made by </p><a href="http://www.filiprojek.cz">filiprojek.cz</a>
</div>
</footer>
</div>
</body>
</html>

View File

@ -0,0 +1,71 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* 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', 'react', 'react-jsx' or 'react-jsxdev'. */
// "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": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "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 */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* 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. */
}
}

51
framework/src/artisan Normal file
View File

@ -0,0 +1,51 @@
// console.log(process.argv)
let arguments = process.argv
const fs = require('fs')
if (arguments[ 2 ] == 'init')
{
let path = __dirname
let paths = [
__dirname + '/views',
__dirname + '/models',
__dirname + '/controllers',
__dirname + '/public',
__dirname + '/routes',
__dirname + '/tests',
__dirname + '/utils',
__dirname + '/',
]
let pathsTypescript = {}
for (let i = 0; i < paths.length; i++)
{
fs.mkdir(paths[i])
}
}
if (arguments[ 2 ].includes('make:'))
{
switch (arguments[ 2 ].split('make:')[ 1 ])
{
case 'view':
// console.log("\x1b[32m%s\x1b[0m", 'View created successfully.')
console.log("\x1b[33m%s\x1b[0m", 'Views coming soon.')
break
case 'model':
console.log("\x1b[32m%s\x1b[0m", 'Model created successfully.')
break
case 'controller':
console.log("\x1b[32m%s\x1b[0m", 'Controller created successfully.')
break
case 'test':
console.log("\x1b[33m%s\x1b[0m", 'Tests coming soon.')
break
case 'middleware':
console.log("\x1b[33m%s\x1b[0m", 'Middlewares coming soon.')
break
case 'routes':
console.log("\x1b[33ms\x1b[0m", 'Routes coming soon.')
break
default:
console.log("\x1b[41m\x1b[37m%s\x1b[0m", 'node artisan make:view | model | controller | test | middleware | routes')
}
}