Skip to content

Commit

Permalink
refactor: apps
Browse files Browse the repository at this point in the history
  • Loading branch information
AxiosLeo committed May 6, 2024
1 parent 3f1cc46 commit 77bf381
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 114 deletions.
112 changes: 1 addition & 111 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,120 +1,10 @@
'use strict';

const Application = require('./src/app');
const { Application, KoaApplication } = require('./src/apps');
const Controller = require('./src/controller');
const KoaBodyParser = require('koa-bodyparser');
const { Router } = require('./src/router');
const { printer } = require('@axiosleo/cli-tool');
const response = require('./src/response');
const session = require('koa-session');
const KoaStaticServer = require('koa-static-server');
const path = require('path');
const Koa = require('koa');
const Model = require('./src/model');
const { dispatcher } = require('./src/core');
const { _assign } = require('@axiosleo/cli-tool/src/helper/obj');
const multer = require('@koa/multer');

/**
* @param {import('./index').KoaContext} context
*/
const handleRes = (context) => {
let response = context.response;
if (response.format === 'json' && response.notResolve !== true) {
let code, message;
if (response.code) {
[code, message] = response.code.split(';');
}
response.data = {
request_id: context.request_id,
timestamp: (new Date()).getTime(),
code: code || `${response.status}`,
message: message || context.response.message,
data: response.data,
};
}
context.koa.type = response.format;
Object.keys(response.headers).forEach(k => {
context.koa.set(k, response.headers[k]);
});
context.koa.body = response.data || '';
context.koa.response.status = response.status;
};

class KoaApplication extends Application {
constructor(config = {}) {
config = _assign({
port: 8080,
listen_host: 'localhost',
debug: false,
routers: [],
app_id: '',
// session_key: '',
session: {
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 1296000000, // ms, 15 days
// autoCommit: true, /** (boolean) automatically commit headers (default true) */
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: true, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
// secure: process.env.DEBUG ? false : true, /** (boolean) secure cookie*/
secure: false,
// sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
},
static: {
rootDir: path.join(__dirname, './public'),
},
body_parser: {}
}, config);

printer.println().green('start on ').println(`http://localhost:${config.port}`).println();
super(config);
this.koa = new Koa(this.config.server);

// session middleware
if (this.config.session) {
this.koa.keys = [this.app_id];
this.koa.use(session({
key: this.config.session_key || 'koa.sess', /** (string) cookie key (default is koa.sess) */
...this.config.session
}, this.koa));
}

['a', 'b', 'c'].forEach((item, index) => {
index;
});

const upload = multer();
this.koa.use(upload.any());

// body parser
this.koa.use(KoaBodyParser(this.config.body_parser));

// dispatcher request
this.koa.use(dispatcher({
app: this,
app_id: this.app_id,
workflow: this.workflow,
routes: this.routes
}));

// koa static services
if (this.config.static) {
this.koa.use(KoaStaticServer(this.config.static));
}
this.on('response', handleRes);
}

async start() {
this.emit('starting');
// set '0.0.0.0' for public access
this.koa.listen(this.config.port, this.config.listen_host);
}
}

module.exports = {
Controller,
Expand Down
5 changes: 2 additions & 3 deletions src/app.js → src/apps/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

const EventEmitter = require('events');
const { v4 } = require('uuid');

const { Configuration, Workflow } = require('@axiosleo/cli-tool');
const { resolveRouters } = require('./core');
const flowOperator = require('./workflow');
const { resolveRouters } = require('../core');
const flowOperator = require('../workflow');

class Application extends EventEmitter {
constructor(config) {
Expand Down
11 changes: 11 additions & 0 deletions src/apps/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

const Application = require('./app');
const KoaApplication = require('./koa');
const SocketApplication = require('./koa');

module.exports = {
Application,
KoaApplication,
SocketApplication
};
116 changes: 116 additions & 0 deletions src/apps/koa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
'use strict';

const KoaBodyParser = require('koa-bodyparser');
const session = require('koa-session');
const KoaStaticServer = require('koa-static-server');
const multer = require('@koa/multer');
const path = require('path');
const Koa = require('koa');
const { dispatcher } = require('../core');
const { printer } = require('@axiosleo/cli-tool');
const { _assign } = require('@axiosleo/cli-tool/src/helper/obj');

const Application = require('./app');

/**
* @param {import('./index').KoaContext} context
*/
const handleRes = (context) => {
let response = context.response;
if (response.format === 'json' && response.notResolve !== true) {
let code, message;
if (response.code) {
[code, message] = response.code.split(';');
}
response.data = {
request_id: context.request_id,
timestamp: (new Date()).getTime(),
code: code || `${response.status}`,
message: message || context.response.message,
data: response.data,
};
}
context.koa.type = response.format;
Object.keys(response.headers).forEach(k => {
context.koa.set(k, response.headers[k]);
});
context.koa.body = response.data || '';
context.koa.response.status = response.status;
};

class KoaApplication extends Application {
constructor(config = {}) {
config = _assign({
port: 8080,
listen_host: 'localhost',
debug: false,
routers: [],
app_id: '',
// session_key: '',
session: {
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 1296000000, // ms, 15 days
// autoCommit: true, /** (boolean) automatically commit headers (default true) */
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: true, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
// secure: process.env.DEBUG ? false : true, /** (boolean) secure cookie*/
secure: false,
// sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
},
static: {
rootDir: path.join(__dirname, './public'),
},
body_parser: {}
}, config);

printer.println().green('start on ').println(`http://localhost:${config.port}`).println();
super(config);
this.koa = new Koa(this.config.server);

// session middleware
if (this.config.session) {
this.koa.keys = [this.app_id];
this.koa.use(session({
key: this.config.session_key || 'koa.sess', /** (string) cookie key (default is koa.sess) */
...this.config.session
}, this.koa));
}

['a', 'b', 'c'].forEach((item, index) => {
index;
});

const upload = multer();
this.koa.use(upload.any());

// body parser
this.koa.use(KoaBodyParser(this.config.body_parser));

// dispatcher request
this.koa.use(dispatcher({
app: this,
app_id: this.app_id,
workflow: this.workflow,
routes: this.routes
}));

// koa static services
if (this.config.static) {
this.koa.use(KoaStaticServer(this.config.static));
}
this.on('response', handleRes);
}

async start() {
this.emit('starting');
// set '0.0.0.0' for public access
this.koa.listen(this.config.port, this.config.listen_host);
}
}

module.exports = KoaApplication;

0 comments on commit 77bf381

Please sign in to comment.