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,6 +1,6 @@
{ {
"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",

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

@ -4,8 +4,8 @@
"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",
@ -16,15 +16,18 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"colors": "^1.4.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"ejs": "^3.1.6", "ejs": "^3.1.6",
"express": "^4.17.1", "express": "^4.17.1",
"fs-extra": "^10.0.0",
"mongoose": "^5.12.3", "mongoose": "^5.12.3",
"morgan": "^1.10.0", "morgan": "^1.10.0"
"fs-extra": "^10.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.10", "@types/cors": "^2.8.10",
"@types/ejs": "^3.0.6", "@types/ejs": "^3.0.6",
"@types/express": "^4.17.11", "@types/express": "^4.17.11",
@ -40,6 +43,20 @@
"shelljs": "^0.8.4", "shelljs": "^0.8.4",
"ts-jest": "^27.0.5", "ts-jest": "^27.0.5",
"ts-node": "^9.1.1", "ts-node": "^9.1.1",
"tsconfig-paths": "^3.11.0",
"typescript": "^4.2.4" "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

@ -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. */