To be honest, I do not quite remember everything I changed here today. But it is all good, I tell ya.

This commit is contained in:
Filip Rojek 2021-11-03 17:35:24 +01:00
parent 686cddefed
commit 36758cbadb
23 changed files with 253 additions and 159 deletions

View File

@ -1,32 +1,32 @@
{ {
"name": "nork", "name": "nork",
"version": "1.1.6", "version": "1.2.0",
"description": "The best node.js 'framework' :)", "description": "The best node.js 'framework' :)",
"main": "src/app.js", "main": "src/app.js",
"bin": "src/app.js", "bin": "src/app.js",
"scripts": { "scripts": {
"start": "node src/app.js" "start": "node src/app.js"
}, },
"keywords": [ "keywords": [
"node", "node",
"framework", "framework",
"express", "express",
"mvc" "mvc"
], ],
"author": "Filip Rojek", "author": "Filip Rojek",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"colors": "^1.4.0", "colors": "^1.4.0",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"inquirer": "^8.1.2", "inquirer": "^8.1.2",
"pad": "^3.2.0" "pad": "^3.2.0"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/filiprojek/nork.git" "url": "git+https://github.com/filiprojek/nork.git"
}, },
"bugs": { "bugs": {
"url": "https://github.com/filiprojek/nork/issues" "url": "https://github.com/filiprojek/nork/issues"
}, },
"homepage": "https://github.com/filiprojek/nork/blob/master/README.md" "homepage": "https://github.com/filiprojek/nork/blob/master/README.md"
} }

View File

@ -59,9 +59,11 @@ const logHelp = (specific = false, command = false) => {
console.log(pad(' create [app-name]', spc), 'create a new project') console.log(pad(' create [app-name]', spc), 'create a new project')
console.log(pad(' create [app-name] -i', spc), 'create a new project in current directory') console.log(pad(' create [app-name] -i', spc), 'create a new project in current directory')
console.log(pad(' make controller [name]', spc), 'create a new controller') console.log(pad(' make controller [name]', spc), 'create a new controller')
console.log(pad(' make interface [name]', spc), 'create a new interface')
console.log(pad(' make middleware [name]', spc), 'create a new middleware') console.log(pad(' make middleware [name]', spc), 'create a new middleware')
console.log(pad(' make model [name]', spc), 'create a new model') console.log(pad(' make model [name]', spc), 'create a new model')
console.log(pad(' make route [name]', spc), 'create a new route') console.log(pad(' make route [name]', spc), 'create a new route')
console.log(pad(' make service [name]', spc), 'create a new service')
console.log(pad(' make test [name]', spc), 'create a new test') console.log(pad(' make test [name]', spc), 'create a new test')
console.log(pad(' make view [name]', spc), 'create a new view') console.log(pad(' make view [name]', spc), 'create a new view')
console.log(pad(' setup', spc), 'set up an existing project for nork') console.log(pad(' setup', spc), 'set up an existing project for nork')
@ -112,7 +114,7 @@ const logHelp = (specific = false, command = false) => {
data.author = answers.author data.author = answers.author
// copy skeleton to new project // copy skeleton to new project
process.argv.includes('-i') ? projectPath = process.cwd() : projectPath = path.join(process.cwd(), data.project_name) process.argv.includes('-i') ? (projectPath = process.cwd()) : (projectPath = path.join(process.cwd(), data.project_name))
fs.copySync(path.join(__dirname, './skeletons/express-' + data.lang), projectPath) fs.copySync(path.join(__dirname, './skeletons/express-' + data.lang), projectPath)
// edit package.json file // edit package.json file
@ -140,7 +142,7 @@ const logHelp = (specific = false, command = false) => {
const component = process.argv[3] const component = process.argv[3]
const norkcfg = require(path.join(process.cwd(), 'norkconfig.json')) const norkcfg = require(path.join(process.cwd(), 'norkconfig.json'))
let tsComponents = ['controller', 'middleware', 'route'] let tsComponents = ['controller', 'middleware', 'route', 'service']
if (tsComponents.includes(component)) { if (tsComponents.includes(component)) {
let src = path.join(__dirname, './make-files/express-' + norkcfg.lang + '/' + component + '.' + norkcfg.lang) let src = path.join(__dirname, './make-files/express-' + norkcfg.lang + '/' + component + '.' + norkcfg.lang)
@ -182,6 +184,17 @@ const logHelp = (specific = false, command = false) => {
let src = path.join(__dirname, './make-files/express-' + norkcfg.lang + '/' + component + '.js') let src = path.join(__dirname, './make-files/express-' + norkcfg.lang + '/' + component + '.js')
let dest = path.join(process.cwd(), './src/' + component + 's' + '/' + process.argv[4] + '.test.js') let dest = path.join(process.cwd(), './src/' + component + 's' + '/' + process.argv[4] + '.test.js')
try {
fs.copySync(src, dest, { overwrite: false, errorOnExist: true })
} catch (err) {
return logError(err.message)
}
return logSuccess()
}
if (component == 'interface') {
let src = path.join(__dirname, './make-files/express-' + norkcfg.lang + '/' + component + '.ts')
let dest = path.join(process.cwd(), './src/' + component + 's' + '/' + process.argv[4] + '.ts')
try { try {
fs.copySync(src, dest, { overwrite: false, errorOnExist: true }) fs.copySync(src, dest, { overwrite: false, errorOnExist: true })
} catch (err) { } catch (err) {

View File

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

View File

@ -0,0 +1,4 @@
export interface interfaceName {
hello: string
world: boolean | null | undefined
}

View File

@ -1,10 +1,8 @@
import { Router, Request, Response, NextFunction } from 'express' import { Router, Request, Response, NextFunction } from 'express'
const router = Router() export const router = Router()
router.use((req: Request, res: Response, next: NextFunction) => { router.use((req: Request, res: Response, next: NextFunction) => {
console.log('Hi :)') console.log('Hi :)')
next() next()
}) })
module.exports = router

View File

@ -1,17 +0,0 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const modelSchema = new Schema(
{
title: {
type: String,
required: true,
},
},
{
timestamps: true,
},
)
const ModelName = mongoose.model('ModelName', modelSchema)
module.exports = ModelName

View File

@ -0,0 +1,15 @@
import { Schema, model } from 'mongoose'
const modelSchema = new Schema<any>(
{
title: {
type: String,
required: true,
},
},
{
timestamps: true,
},
)
export default model('ModelName', modelSchema)

View File

@ -1,8 +1,6 @@
import { Router } from 'express' import { Router } from 'express'
const rootController = require('../controllers/rootController') import * as rootController from '@/controllers/rootController'
const router = Router() export const router = Router()
router.get('/', rootController.root_get) router.get('/', rootController.root_get)
module.exports = router

View File

@ -0,0 +1,3 @@
export function helloWorld() {
console.log('hello world')
}

View File

@ -1,45 +1,62 @@
{ {
"name": "project-name", "name": "project-name",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "app.js", "main": "app.js",
"scripts": { "scripts": {
"start": "node dist/app.js", "start": "node -r tsconfig-paths/register -r ts-node/register dist/server.js",
"dev": "nodemon src/app.ts", "dev": "nodemon src/server.ts",
"test": "jest", "test": "jest",
"clean": "rimraf dist/*", "clean": "rimraf dist/*",
"copy-assets": "ts-node src/utils/copyAssets", "copy-assets": "ts-node src/utils/copyAssets",
"tsc": "tsc -p .", "tsc": "tsc -p .",
"build": "npm-run-all clean tsc copy-assets" "build": "npm-run-all clean tsc copy-assets"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"cors": "^2.8.5", "colors": "^1.4.0",
"dotenv": "^8.2.0", "cookie-parser": "^1.4.5",
"ejs": "^3.1.6", "cors": "^2.8.5",
"express": "^4.17.1", "dotenv": "^8.2.0",
"mongoose": "^5.12.3", "ejs": "^3.1.6",
"morgan": "^1.10.0", "express": "^4.17.1",
"fs-extra": "^10.0.0" "fs-extra": "^10.0.0",
}, "mongoose": "^5.12.3",
"devDependencies": { "morgan": "^1.10.0"
"@types/cors": "^2.8.10", },
"@types/ejs": "^3.0.6", "devDependencies": {
"@types/express": "^4.17.11", "@types/cookie-parser": "^1.4.2",
"@types/fs-extra": "^9.0.12", "@types/cors": "^2.8.10",
"@types/jest": "^27.0.1", "@types/ejs": "^3.0.6",
"@types/mongoose": "^5.10.5", "@types/express": "^4.17.11",
"@types/morgan": "^1.9.2", "@types/fs-extra": "^9.0.12",
"@types/node": "^14.14.41", "@types/jest": "^27.0.1",
"@types/shelljs": "^0.8.9", "@types/mongoose": "^5.10.5",
"jest": "^27.0.6", "@types/morgan": "^1.9.2",
"npm-run-all": "^4.1.5", "@types/node": "^14.14.41",
"rimraf": "^3.0.2", "@types/shelljs": "^0.8.9",
"shelljs": "^0.8.4", "jest": "^27.0.6",
"ts-jest": "^27.0.5", "npm-run-all": "^4.1.5",
"ts-node": "^9.1.1", "rimraf": "^3.0.2",
"typescript": "^4.2.4" "shelljs": "^0.8.4",
} "ts-jest": "^27.0.5",
} "ts-node": "^9.1.1",
"tsconfig-paths": "^3.11.0",
"typescript": "^4.2.4"
},
"nodemonConfig": {
"ignore": [
"**/*.test.ts",
"**/*.spec.ts",
".git",
"node_modules"
],
"watch": [
"src"
],
"exec": "node -r tsconfig-paths/register -r ts-node/register ./src/server.ts",
"ext": "ts, js"
}
}

View File

@ -1,43 +1,36 @@
import express from 'express' import express from 'express'
import morgan from 'morgan' import morgan from 'morgan'
import mongoose from 'mongoose'
import path from 'path' import path from 'path'
import cors from 'cors' import cors from 'cors'
import cookieParser from 'cookie-parser'
import { router as routes } from '@/routes'
import { router as middlewares } from '@/middlewares'
const config = require('./utils/environment') const corsWhitelist = ['http://localhost:8080', 'http://localhost:6060']
const routes = require('./routes') const corsOptions = {
const middlewares = require('./middlewares') origin: function (origin: any, callback: any) {
if (!origin || corsWhitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
optionsSuccessStatus: 200,
credentials: true,
}
const port: Number = config.APP_PORT || 8080 export const app = express()
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 // Middlewares
app.use(middlewares) app.use(middlewares)
app.set('view engine', 'ejs') app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views')) app.set('views', path.join(__dirname, 'views'))
app.use(cors()) app.use(cors(corsOptions))
app.use(morgan('dev')) app.use(morgan('dev'))
app.use(express.urlencoded({ extended: true })) app.use(express.urlencoded({ extended: true }))
app.use(express.json()) app.use(express.json())
app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'public')))
app.use(cookieParser())
// Routes // Routes
app.use(routes) app.use(routes)

View File

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

View File

@ -0,0 +1,4 @@
export interface ErrType {
code: number
message: string
}

View File

@ -1,8 +1,6 @@
import { Router } from 'express' import { Router } from 'express'
const sayHiMiddleware = require('./sayHiMiddleware') import { router as sayHiMiddleware } from '@/middlewares/sayHiMiddleware'
const router = Router() export const router = Router()
router.use(sayHiMiddleware) router.use(sayHiMiddleware)
module.exports = router

View File

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

View File

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

View File

@ -1,8 +1,6 @@
import { Router } from 'express' import { Router } from 'express'
const rootController = require('../controllers/rootController') import * as rootController from '@/controllers/rootController'
const router = Router() export const router = Router()
router.get('/', rootController.root_get) router.get('/', rootController.root_get)
module.exports = router

View File

@ -0,0 +1,24 @@
import mongoose from 'mongoose'
import { app } from '@/app'
import config from '@/utils/environment'
import { Err, Succ } from '@/services/globalService'
const port: Number = config.APP_PORT || 8080
// 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)
})

View File

@ -0,0 +1,40 @@
import colors from 'colors'
import { ErrType } from '@/interfaces/globalInterface'
export class Err implements ErrType {
code: number
message: string
constructor(code: number, message: string) {
this.code = code
this.message = message
this.drop()
}
drop() {
console.log(colors.bgRed(`${this.code}`) + colors.bgBlack.red(` ${this.message}`))
return {
code: this.code,
message: this.message,
}
}
}
export class Succ {
code: number
message: string
constructor(code: number, message: string) {
this.code = code
this.message = message
this.drop()
}
drop() {
console.log(colors.bgGreen.black(`${this.code}`) + colors.green.bgBlack(` ${this.message}`))
return {
code: this.code,
message: this.message,
}
}
}

View File

@ -0,0 +1,3 @@
export const helloWorld = () => {
console.log('hello world')
}

View File

@ -3,4 +3,5 @@ import * as shell from 'shelljs'
// Copy all the view templates // Copy all the view templates
shell.cp('-R', 'src/views', 'dist/') shell.cp('-R', 'src/views', 'dist/')
shell.cp('-R', 'src/public', 'dist/') shell.cp('-R', 'src/public', 'dist/')
shell.cp('-R', 'src/models', 'dist/')
shell.cp('-u', 'src/.env', 'dist/') shell.cp('-u', 'src/.env', 'dist/')

View File

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

View File

@ -14,7 +14,7 @@
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */ // "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */ "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. */ "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */ // "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
@ -44,8 +44,22 @@
/* Module Resolution Options */ /* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ "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'. */ "paths": {
"@/*": ["src/","src/*"],
"@dist/*": ["dist/*"],
"@controllers/*": ["src/controllers/"],
"@interfaces/*": ["src/interfaces/*"],
"@middlewares/*": ["src/middlewares/*"],
"@models/*": ["src/models/*"],
"@public/*": ["src/public/*"],
"@routes/*": ["src/routes/*"],
"@services/*": ["src/services/*"],
"@test/*": ["src/test/*"],
"@utils/*": ["src/utils/*"],
"@validators/*": ["src/validators/*"],
"@views/*": ["src/views/*"],
},
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "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. */ // "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */ // "types": [], /* Type declaration files to be included in compilation. */