Awesome Open Source
Awesome Open Source

koa2Example


npm

npm install koa-generator -g
koa2 projectName
bin
    www             --
node_modules
app
    model           --
    service         --CRUD
    util            --
config              --
middleware          --()
public              --mvc(mvvm)
    images
    javascripts
    stylesheets
routes(controller)  --()
    ***.js
views               --mvc(mvvm)
    ***.pug
app.js              --
package.json

app.js
```js
const json = require('koa-json')
app.use(json())
```
```js
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
```

,app.js
```js
function doSomething(ctx) {
    console.log('doSomething')
}

var interceptor = () => async (ctx,next) => {
    doSomething(ctx)
    await next()
}

module.exports = interceptor;
```
```js
let authoization = async (ctx, next) => {
    //next
    //ctx.body = {
    //    message: 'exception',
    //    code: -1
    //}

    //ctx.response.redirect('/');

    //next
    //await next()
}

router.all('*', async (ctx, next) => {
    authoization(ctx, next)
})

module.exports = router;
```

koa202 - koa2 nodelog4js

koa-logger
koa-log4

Koa2token

nodejsbcryptjs

bcryptbcryptjs

npm install bcryptjs --save
var bcrypt = require('bcryptjs');
var hash = bcrypt.hashSync('bacon', 10);
bcrypt.compareSync("bacon", hash);
bcrypt.compareSync("not_bacon", hash);

const routePath = {
    'test': '../routes/test',
    ...
}
  1. middlewareapp
let activateRoutes = (app) => {
    let routes = [];
    let index = 0;
    for(let key in routePath){
        routes[index] = require(routePath[key]);
        app.use(routes[index].routes(), routes[index].allowedMethods());
        index++;
    }
    return app;
}

router.all('*', async (ctx, next) => {
    //console.log('all: /api/mockServer')
    ctx.set("Access-Control-Allow-Origin", "*");  //  URI
    ctx.set('Access-Control-Allow-Methods', '*');  // 
    ctx.set("Access-Control-Max-Age", "3600");  // 
    ctx.set("Access-Control-Allow-Headers", "apk");  //   CORS 
    ctx.set("Access-Control-Allow-Credentials", "true");  //  Cookie 
    //ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    ctx.set("Content-Type", "application/json;charset=utf-8");

    console.log('ctx.request.method:',ctx.request.method)
    // 
    if (ctx.request.method == "OPTIONS") {
        ctx.response.stutas = "200"
        ctx.body = 'OPTIONS';
    }

    try {
        await next();
        //console.log("");
    } catch (e) {
        //console.log("");
        ctx.response.status = e.statusCode || err.status || 500;
        ctx.response.body = {
            message: e.message
        }
    }
})

const path = [
    '/',
    '/index',
    '/api/*'
]
const url = '/api/check'
function passThrough(path,url) {
    let flag = false;
    for(let i = 0;i < path.length;i++){
        if(path[i] === '*'){
            flag = true;
            break;
        }else{
            let pathParts = path[i].split('/');
            let urlParts = url.split('/');
            let pathMatch = true;
            for(let j = 0;j < pathParts.length;j++){
                if(pathParts[j] !== urlParts[j] && pathParts[j] !== '*'){
                    pathMatch = false;
                }
            }
            if(pathMatch){
                flag = true;
                break;
            }
        }
    }
    return flag;
}

SQLLINQ

const tableName = 'users';

const usersRepository = {
    findAllUser: async () => {
        return await new connector().selectAllFromTable(tableName).execute();
    },
    addUserData: async (model) => {
        return await new connector().insertDataToTable(tableName,model).execute();
    },
    findUser: async (name) => {
        return await new connector().selectAllFromTable(tableName).whereAllEquals({name:name}).execute();
    },
}
let pools = {};

//
if (!pools.hasOwnProperty('data')) {
    pools['data'] = mysql.createPool({
        host: config.database.HOST,
        user: config.database.USERNAME,
        password: config.database.PASSWORD,
        database: config.database.DATABASE
    });
}

//   
// sql sql
// values sql
// sql values  https://github.com/mysqljs/mysql#performing-queries
const query = (sql, values) => {
    return new Promise((resolve, reject) => {
        //
        pools['data'].getConnection((err, connection) => {
            if (err) {
                console.log(err,'');
                reject(err);
            }
            else{
            	console.log('');
                //
	            connection.query(sql, values, (err, results) => {
	                if (err) {
                        console.log(err);
	                	reject(err);
	                } else {
                        console.log(results);
	                	connection.release();
	                	resolve(results);
	                }
	            });
            }
        })
    });
}

const connector = class{
    constructor(){
        this.sql = ''
    }
    
    getStatement() {
        return this.sql;
    }
    execute() {
        global.logHandle('execute')
        return query(this.sql);
    }
    columnName(name) {
        global.logHandle('columnName')
        this.sql += ` ${name}`;
        global.logHandle(this.sql);
        return this;
    }
    operator(operation) {
        global.logHandle('operator')
        this.sql += ` ${operation}`;
        global.logHandle(this.sql);
        return this;
    }
    condition(condition) {
        global.logHandle('condition')
        this.sql += ` ${condition}`;
        global.logHandle(this.sql);
        return this;
    }
    selectAllFromTable(tableName) {
        global.logHandle('selectAllFromTable')
        this.sql += `select * from ${tableName}`;
        global.logHandle(this.sql);
        return this;
    }
    selectSomeFromTable(tableName,columnNames,distinct = false,top = '') {
        global.logHandle('selectSomeFromTable')
        if(distinct){
            if(top){
                this.sql += `select distinct top ${top} ${columnNames.join(" ")} from ${tableName}`;
            }else{
                this.sql += `select distinct ${columnNames.join(" ")} from ${tableName}`;
            }
        }else{
            if(top){
                this.sql += `select top ${top} ${columnNames.join(" ")} from ${tableName}`;
            }else{
                this.sql += `select ${columnNames.join(" ")} from ${tableName}`;
            }
        }
        global.logHandle(this.sql);
        return this;
    }
    insertDataToTable(tableName,model) {
        global.logHandle('insertDataToTable')
        this.sql += `insert into ${tableName} set `;
        let index = 0;
        for(let key in model){
            if(index === 0){
                this.sql += `${key} = '${model[key]}'`;
                index++;
            }
            else{
                this.sql += `,${key} = '${model[key]}'`;
            }
        }
        global.logHandle(this.sql);
        return this;
    }
    whereStatement(statement) {
        global.logHandle('whereStatement')
        this.sql += ` where ${statement}`;
        global.logHandle(this.sql);
        return this;
    }
    whereAllEquals(model) {
        global.logHandle('whereAllEquals')
        let index = 0;
        for(let key in model){
            if(index === 0){
                this.sql += ` where ${key} = '${model[key]}'`;
                index++;
            }
            else{
                this.sql += ` and ${key} = '${model[key]}'`;
            }
        }
        global.logHandle(this.sql);
        return this;
    }
    orderBy(key) {
        global.logHandle('orderBy')
        this.sql += ` order by ${key}`;
        global.logHandle(this.sql);
        return this;
    }
    orderByDesc(key) {
        global.logHandle('orderByDesc')
        this.sql += ` order by ${key} desc`;
        global.logHandle(this.sql);
        return this;
    }
    groupBy(key,condition = '') {
        global.logHandle('groupBy')
        this.sql += ` group by ${key}`;
        if(condition){
            this.sql += ` ${condition}`;
        }
        global.logHandle(this.sql);
        return this;
    }
    limit(begin,count = '') {
        global.logHandle('limit')
        this.sql += ` limit ${begin}`;
        if(count){
            this.sql += `,${count}`;
        }
        global.logHandle(this.sql);
        return this;
    }
    combine(sql) {
        global.logHandle('combine')
        this.sql += ` ${sql}`;
        global.logHandle(this.sql);
        return this;
    }
}

* 

    

* 

    URLhashchangepushstate

URL

let historyEvent = function(type) {
    let origin = history[type];
    return function() {
        let result = origin.apply(this, arguments);
        let event = new Event(type);
        event.arguments = arguments;
        window.dispatchEvent(event);
        return result;
    };
};
history.pushState = historyEvent('pushState');
history.replaceState = historyEvent('replaceState');

window.addEventListener('replaceState', function(e) {
    console.log('replaceState');
});
window.addEventListener('pushState', function(e) {
    console.log('pushState');
});
function getClientIP(req) {
    return (req.headers ? (req.headers['x-forwarded-for'] || req.headers['x-real-ip']) : null) || //  IP
        (req.connection ? (req.connection.remoteAddress || (req.connection.socket ? req.connection.socket.remoteAddress : null)) : null) || //  connection  IP
        (req.socket ? req.socket.remoteAddress : null) || //  socket  IP
        'unknown';
}
let model = myUtil.deepClone(monitorBrowserModel);
let body = JSON.parse(ctx.request.body);
for(let key in model){
    model[key] = JSON.stringify(body[key]);
}
model.ip = myUtil.getClientIP(ctx.request.header);
model.time = new Date().getTime();
delete model.id;
let result = await monitorRepository.addBrowserData(model);

browser

CREATE TABLE `browser_monitor` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `browserVersion` varchar(100) DEFAULT NULL,
  `browserVersionNumber` varchar(100) DEFAULT NULL,
  `browserName` varchar(100) DEFAULT NULL,
  `os` varchar(100) DEFAULT NULL,
  `netType` varchar(100) DEFAULT NULL,
  `language` varchar(100) DEFAULT NULL,
  `platform` varchar(100) DEFAULT NULL,
  `model` varchar(100) DEFAULT NULL,
  `domain` varchar(100) DEFAULT NULL,
  `url` varchar(300) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  `referrer` varchar(300) DEFAULT NULL,
  `lastModified` varchar(100) DEFAULT NULL,
  `cookie` varchar(500) DEFAULT NULL,
  `characterSet` varchar(100) DEFAULT NULL,
  `screenHeight` varchar(100) DEFAULT NULL,
  `screenWidth` varchar(100) DEFAULT NULL,
  `colorDepth` varchar(100) DEFAULT NULL,
  `devicePixelRatio` varchar(100) DEFAULT NULL,
  `dnsTime` varchar(100) DEFAULT NULL,
  `tcpTime` varchar(100) DEFAULT NULL,
  `firstPaintTime` varchar(100) DEFAULT NULL,
  `FirstContentfulPaintTime` varchar(100) DEFAULT NULL,
  `domRenderTime` varchar(100) DEFAULT NULL,
  `loadTime` varchar(100) DEFAULT NULL,
  `ip` varchar(100) DEFAULT NULL,
  `time` varchar(200) DEFAULT NULL,
  `performance` varchar(2000) DEFAULT NULL,
  `redirectTime` varchar(200) DEFAULT NULL,
  `redirectCount` int(11) DEFAULT NULL,
  `sslTime` varchar(200) DEFAULT NULL,
  `requestTime` varchar(200) DEFAULT NULL,
  `responseTime` varchar(200) DEFAULT NULL,
  `domExplainTime` varchar(200) DEFAULT NULL,
  `resourceLoadTime` varchar(200) DEFAULT NULL,
  `domAnalysisTime` varchar(200) DEFAULT NULL,
  `blankTime` varchar(200) DEFAULT NULL,
  `firstInteractiveTime` varchar(200) DEFAULT NULL,
  `domReadyTime` varchar(200) DEFAULT NULL,
  `loadCompleteTime` varchar(200) DEFAULT NULL,
  `entriesInfo` varchar(2000) DEFAULT NULL,
  `jsCount` int(11) DEFAULT NULL,
  `cssCount` int(11) DEFAULT NULL,
  `xhrCount` int(11) DEFAULT NULL,
  `imgCount` int(11) DEFAULT NULL,
  `resourceCount` int(11) DEFAULT NULL,
  `jsLoadTime` varchar(200) DEFAULT NULL,
  `cssLoadTime` varchar(200) DEFAULT NULL,
  `xhrLoadTime` varchar(200) DEFAULT NULL,
  `imgLoadTime` varchar(200) DEFAULT NULL,
  `userAgent` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idbrowser_monitor_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;

error

CREATE TABLE `error_monitor` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(200) DEFAULT NULL,
  `type` varchar(100) DEFAULT NULL,
  `row` int(11) DEFAULT NULL,
  `col` int(11) DEFAULT NULL,
  `source` varchar(200) DEFAULT NULL,
  `msg` varchar(2000) DEFAULT NULL,
  `ip` varchar(100) DEFAULT NULL,
  `time` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

event

CREATE TABLE `event_monitor` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `eventType` varchar(100) DEFAULT NULL,
  `happenTime` varchar(200) DEFAULT NULL,
  `content` varchar(2000) DEFAULT NULL,
  `ip` varchar(100) DEFAULT NULL,
  `time` varchar(200) DEFAULT NULL,
  `url` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;

request

CREATE TABLE `request_monitor` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `requestMethod` varchar(20) DEFAULT NULL,
  `requestOriginalUrl` varchar(200) DEFAULT NULL,
  `ip` varchar(200) DEFAULT NULL,
  `requestContent` varchar(2000) DEFAULT NULL,
  `responseTime` varchar(200) DEFAULT NULL,
  `responseStatus` varchar(200) DEFAULT NULL,
  `responseContent` varchar(2000) DEFAULT NULL,
  `time` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

stay

CREATE TABLE `stay_monitor` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(200) DEFAULT NULL,
  `stayTime` int(11) DEFAULT NULL,
  `ip` varchar(100) DEFAULT NULL,
  `time` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8;

blob

dash.js ffmpeg mp4->m4s url.createObjectURL

blob

blob:http://

BLOB

videom3u8

pm2

PM2Node.js

PM2

PM2

* 

    pm2 start <> (-i <>)

* 

    pm2 restart all

    pm2 restart <int>

* 

    pm2 reload all

    pm2 reload <int>

* 

    pm2 scale <> <>

* 

    start:pm2 save

    ~/.pm2dump.pm2PM2pm2 startup (<>)

* 

    pm2 stop all

    pm2 stop <int>

* 

    pm2 delete all

    pm2 delete <int>

* 

    pm2 logs [--raw]

    pm2 flush

    pm2 reloadLogs

* 

    pm2 monit

* 

    pm2 list

    pm2 show <int>
    
    pm2 info <int>

chromeDebug

node --inspect bin/www

devtools

chrome console object

koa

swagger-jsdoc

koa2-swagger-ui

Swagger Petstore


Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
Javascript (1,511,581
Jwt (3,538
Logger (1,642
Monitor (1,061
Koa2 (900
Linq (424
Pm2 (326
Related Projects