From 95e60bc04ed92edcb86e7e4a33686ded75721152 Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Wed, 2 Feb 2022 16:01:34 +0100 Subject: [PATCH] nork 3.0.4 --- package.json | 4 +- src/skeletons/express-ts/.prettierrc | 20 ++++++++ src/skeletons/express-ts/norkconfig.json | 3 +- src/skeletons/express-ts/package.json | 13 +++-- src/skeletons/express-ts/src/.env.example | 17 ++++++- .../express-ts/src/config/database.ts | 49 +++++++++++++++++++ .../express-ts/src/config/postgres.config.ts | 10 ++++ .../src/middlewares/authMiddleware.ts | 32 ++++++++++++ .../src/middlewares/handleValidation.ts | 13 +++++ .../express-ts/src/routes/rootRoutes.ts | 5 +- src/skeletons/express-ts/src/server.ts | 40 +++++++-------- .../express-ts/src/utils/environment.ts | 35 ++++++++++++- .../src/validators/rootValidator.ts | 9 ++++ 13 files changed, 221 insertions(+), 29 deletions(-) create mode 100644 src/skeletons/express-ts/.prettierrc create mode 100644 src/skeletons/express-ts/src/config/database.ts create mode 100644 src/skeletons/express-ts/src/config/postgres.config.ts create mode 100644 src/skeletons/express-ts/src/middlewares/authMiddleware.ts create mode 100644 src/skeletons/express-ts/src/middlewares/handleValidation.ts create mode 100644 src/skeletons/express-ts/src/validators/rootValidator.ts diff --git a/package.json b/package.json index ab403d0..e6f2471 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nork", - "version": "3.0.3", + "version": "3.0.4", "description": "The best node.js 'framework' :)", "main": "dist/app.js", "bin": "dist/app.js", @@ -25,7 +25,7 @@ "author": "Filip Rojek", "license": "MIT", "dependencies": { - "colors": "^1.4.0", + "colors":"1.4.0", "fs-extra": "^10.0.0", "inquirer": "^8.1.2", "pad": "^3.2.0" diff --git a/src/skeletons/express-ts/.prettierrc b/src/skeletons/express-ts/.prettierrc new file mode 100644 index 0000000..fceb42a --- /dev/null +++ b/src/skeletons/express-ts/.prettierrc @@ -0,0 +1,20 @@ +{ + "arrowParens": "avoid", + "bracketSpacing": true, + "endOfLine": "lf", + "htmlWhitespaceSensitivity": "css", + "insertPragma": false, + "jsxBracketSameLine": true, + "jsxSingleQuote": true, + "printWidth": 200, + "proseWrap": "preserve", + "quoteProps": "as-needed", + "requirePragma": false, + "semi": false, + "singleQuote": true, + "tabWidth": 4, + "trailingComma": "all", + "useTabs": true, + "vueIndentScriptAndStyle": true, + "parser": "typescript" +} \ No newline at end of file diff --git a/src/skeletons/express-ts/norkconfig.json b/src/skeletons/express-ts/norkconfig.json index 265d99b..22d2a0c 100644 --- a/src/skeletons/express-ts/norkconfig.json +++ b/src/skeletons/express-ts/norkconfig.json @@ -1,3 +1,4 @@ { - "lang": "ts" + "lang": "ts", + "db": "" } \ No newline at end of file diff --git a/src/skeletons/express-ts/package.json b/src/skeletons/express-ts/package.json index 4ae4d96..3f00f89 100644 --- a/src/skeletons/express-ts/package.json +++ b/src/skeletons/express-ts/package.json @@ -5,6 +5,7 @@ "main": "app.js", "scripts": { "start": "node -r tsconfig-paths/register -r ts-node/register dist/server.js", + "start:dev": "npx nodemon src/server.ts", "dev": "nodemon src/server.ts", "test": "jest", "clean": "rimraf dist/*", @@ -16,15 +17,20 @@ "author": "", "license": "ISC", "dependencies": { - "colors": "^1.4.0", + "colors": "1.4.0", "cookie-parser": "^1.4.5", "cors": "^2.8.5", "dotenv": "^8.2.0", "ejs": "^3.1.6", "express": "^4.17.1", + "express-validator": "^6.14.0", "fs-extra": "^10.0.0", + "jsonwebtoken": "^8.5.1", "mongoose": "^5.12.3", - "morgan": "^1.10.0" + "morgan": "^1.10.0", + "pg": "^8.7.1", + "pg-hstore": "^2.3.4", + "sequelize": "^6.15.0" }, "devDependencies": { "@types/cookie-parser": "^1.4.2", @@ -33,6 +39,7 @@ "@types/express": "^4.17.11", "@types/fs-extra": "^9.0.12", "@types/jest": "^27.0.1", + "@types/jsonwebtoken": "^8.5.8", "@types/mongoose": "^5.10.5", "@types/morgan": "^1.9.2", "@types/node": "^14.14.41", @@ -59,4 +66,4 @@ "exec": "node -r tsconfig-paths/register -r ts-node/register ./src/server.ts", "ext": "ts, js" } -} \ No newline at end of file +} diff --git a/src/skeletons/express-ts/src/.env.example b/src/skeletons/express-ts/src/.env.example index b1a432b..a6d54b2 100644 --- a/src/skeletons/express-ts/src/.env.example +++ b/src/skeletons/express-ts/src/.env.example @@ -1,2 +1,17 @@ -APP_PORT = 8080 +# General +APP_PORT = 6060 +APP_HOSTNAME = 'localhost' +APP_HOST = 'http://localhost:8080' # frontend url +CORS_WHITELIST = http://172.15.46.21:8080;http://192.168.0.1:8080 + +JWT_SECRET = '' + +# MongoDB DB_URI = 'mongodb://username:password@localhost:27017/database?authSource=admin' + +# PostgreSQL +DB_PORT = 5432 +DB_HOST = '127.0.0.1' +DB_USERNAME = '' +DB_PASSWORD = '' +DB_DATABASE = '' \ No newline at end of file diff --git a/src/skeletons/express-ts/src/config/database.ts b/src/skeletons/express-ts/src/config/database.ts new file mode 100644 index 0000000..80694ef --- /dev/null +++ b/src/skeletons/express-ts/src/config/database.ts @@ -0,0 +1,49 @@ +import mongoose from 'mongoose' +import config from '@/utils/environment' +import { Err, Succ } from '@/services/globalService' +import db from '@/config/postgres.config' + +// MongoDB +const dbURI: string = config.DB_URI +function connect() { + if (!config.NORK.db) { + new Err(500, 'no database is in norkcfg.json') + return false + } + + if (config.NORK.db == 'mongodb') { + mongoose + .connect(dbURI, { + useNewUrlParser: true, + useUnifiedTopology: true, + useCreateIndex: true, + }) + .then(() => { + new Succ(200, 'connected to db') + return true + }) + .catch((err: any) => { + new Err(500, err) + return false + }) + } + + if (config.NORK.db == 'postgresql') { + db.sync() + .then(() => { + new Succ(200, 'connected to db') + return true + }) + .catch((err: any) => { + new Err(500, `Can't connect to db\n${err}`) + return false + }) + } + + if (config.NORK.db.length > 0) { + new Err(500, `unsupported database ${config.NORK.db}`) + return false + } +} + +export default connect diff --git a/src/skeletons/express-ts/src/config/postgres.config.ts b/src/skeletons/express-ts/src/config/postgres.config.ts new file mode 100644 index 0000000..0f469f0 --- /dev/null +++ b/src/skeletons/express-ts/src/config/postgres.config.ts @@ -0,0 +1,10 @@ +import { Sequelize } from 'sequelize' +import config from '@/utils/environment' + +const db = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, { + host: config.DB_HOST, + dialect: 'postgres', + logging: false, +}) + +export default db diff --git a/src/skeletons/express-ts/src/middlewares/authMiddleware.ts b/src/skeletons/express-ts/src/middlewares/authMiddleware.ts new file mode 100644 index 0000000..292bea0 --- /dev/null +++ b/src/skeletons/express-ts/src/middlewares/authMiddleware.ts @@ -0,0 +1,32 @@ +import { Request, Response, NextFunction } from 'express' +import jwt from 'jsonwebtoken' +import env from '@/utils/environment' +import { Err, Succ } from '@/services/globalService' +// import User from '@/models/User' // uncomment this + +export const requireAuth = (req: Request, res: Response, next: NextFunction) => { + const token = req.cookies.jwt + new Err(500, 'uncomment code in authMiddleware before using!') + /* if (token) { + jwt.verify(token, env.JWT_SECRET, async (err: any, decodedToken: any) => { + if (err) { + // console.error(err.message) + res.status(401).send(new Err(401, 'user is not authenticated')) + } + if (!err) { + const user = await User.findByPk(decodedToken.id) + if (user === null) { + res.status(401).send(new Err(401, 'user is not authenticated')) + return + } + res.locals.user = user + new Succ(100, 'user is authenticated') + next() + } + }) + } + + if (!token) { + res.status(401).send(new Err(401, 'user is not authenticated')) + } */ +} diff --git a/src/skeletons/express-ts/src/middlewares/handleValidation.ts b/src/skeletons/express-ts/src/middlewares/handleValidation.ts new file mode 100644 index 0000000..3f72c18 --- /dev/null +++ b/src/skeletons/express-ts/src/middlewares/handleValidation.ts @@ -0,0 +1,13 @@ +import { Request, Response, NextFunction } from 'express' +import { validationResult } from 'express-validator' + +class Middleware { + handleValidationError(req: Request, res: Response, next: NextFunction) { + const error = validationResult(req) + if (!error.isEmpty()) { + return res.status(400).json(error.array()[0]) + } + next() + } +} +export default new Middleware() diff --git a/src/skeletons/express-ts/src/routes/rootRoutes.ts b/src/skeletons/express-ts/src/routes/rootRoutes.ts index 7374556..d7f5384 100644 --- a/src/skeletons/express-ts/src/routes/rootRoutes.ts +++ b/src/skeletons/express-ts/src/routes/rootRoutes.ts @@ -1,6 +1,9 @@ import { Router } from 'express' import * as rootController from '@/controllers/rootController' +import rootValidator from '@/validators/rootValidator' +import handleValidation from '@/middlewares/handleValidation' export const router = Router() +const mws = [handleValidation.handleValidationError] -router.get('/', rootController.root_get) +router.get('/', rootValidator.checkRootGet(), mws, rootController.root_get) diff --git a/src/skeletons/express-ts/src/server.ts b/src/skeletons/express-ts/src/server.ts index 7943293..619976d 100644 --- a/src/skeletons/express-ts/src/server.ts +++ b/src/skeletons/express-ts/src/server.ts @@ -1,24 +1,24 @@ -import mongoose from 'mongoose' +import http from 'http' import { app } from '@/app' import config from '@/utils/environment' -import { Err, Succ } from '@/services/globalService' +import { Succ } from '@/services/globalService' +import database from '@/config/database' +const port: number = config.APP_PORT || 8080 +const hostname: string = config.APP_HOSTNAME || 'localhost' +const server = http.createServer(app) -const port: Number = config.APP_PORT || 8080 +// Server +export function runServer(): void { + server.listen(port, hostname, () => { + new Succ(200, `Server is listening on http://localhost:${port}`) + }) +} -// MongoDB -const dbURI: string = config.DB_URI -mongoose - .connect(dbURI, { - useNewUrlParser: true, - useUnifiedTopology: true, - useCreateIndex: true, - }) - .then(() => { - new Succ(200, 'connected to db') - app.listen(port, () => { - new Succ(200, `Server is listening on http://localhost:${port}`) - }) - }) - .catch((err: any) => { - new Err(500, err) - }) +if (!config.NORK.db) { + runServer() +} else { + const db_connection = database() + if (db_connection) { + runServer() + } +} diff --git a/src/skeletons/express-ts/src/utils/environment.ts b/src/skeletons/express-ts/src/utils/environment.ts index 6280b67..b955f49 100644 --- a/src/skeletons/express-ts/src/utils/environment.ts +++ b/src/skeletons/express-ts/src/utils/environment.ts @@ -1,7 +1,40 @@ import path from 'path' -require('dotenv').config({ path: path.join(__dirname, '../.env') }) +import fs from 'fs-extra' +import { Err } from '@/services/globalService' +import dotenv from 'dotenv' + +dotenv.config({ path: path.join(__dirname, '../.env') }) +const norkcfg = fs.readJSONSync(path.join(__dirname, '../../norkconfig.json')) + +if (norkcfg.db) { + if (norkcfg.db == 'postgresql') { + if (!process.env.DB_PORT) { + process.env.DB_PORT = '5432' + } + if (!process.env.DB_HOST) { + process.env.DB_HOST = '127.0.0.1' + } + if (!process.env.DB_USERNAME || !process.env.DB_PASSWORD || !process.env.DB_DATABASE) { + new Err(500, 'missing DB parameters in .env file') + process.exit(1) + } + } +} export default { + // General APP_PORT: Number(process.env.APP_PORT), + APP_HOST: String(process.env.APP_HOST), + APP_HOSTNAME: process.env.APP_HOSTNAME !== undefined ? String(process.env.APP_HOSTNAME) : null, + CORS_WHITELIST: String(process.env.CORS_WHITELIST), + JWT_SECRET: String(process.env.JWT_SECRET), + // MongoDB DB_URI: String(process.env.DB_URI), + // PostgreSQL + DB_PORT: Number(process.env.DB_PORT), + DB_HOST: String(process.env.DB_HOST), + DB_USERNAME: String(process.env.DB_USERNAME), + DB_PASSWORD: String(process.env.DB_PASSWORD), + DB_DATABASE: String(process.env.DB_DATABASE), + NORK: norkcfg, } diff --git a/src/skeletons/express-ts/src/validators/rootValidator.ts b/src/skeletons/express-ts/src/validators/rootValidator.ts new file mode 100644 index 0000000..7b1acbb --- /dev/null +++ b/src/skeletons/express-ts/src/validators/rootValidator.ts @@ -0,0 +1,9 @@ +import { body, param, query } from 'express-validator' + +class rootValidator { + checkRootGet() { + return [] + } +} + +export default new rootValidator()