[feat] Remove unuse code

This commit is contained in:
JasonWu 2021-09-01 15:30:09 +08:00
parent 9174b540fd
commit c96cdf0ebd
13 changed files with 1 additions and 384 deletions

View File

@ -1,114 +0,0 @@
const pg = require('pg');
const fs = require('fs');
const path = require('path');
const config = require('src/config/index.js');
// schema file name format ######_name.sql
const schemaDir = path.resolve(__dirname, '..', 'schemas');
const db = new pg.Client({
host: config.database.host,
port: config.database.port,
user: config.database.user,
password: config.database.password,
database: config.database.dbname,
});
(async () => {
await db.connect();
await db.query(`select now();`);
let version = -1;
// check migrate record table exists
const checkTable = await db.query(
`
select exists(
select 1
from "information_schema"."tables"
where
"table_schema" = $1
and "table_name" = $2
) as exists
`,
['public', 'migrate_log']
);
if (checkTable.rowCount > 0 && checkTable.rows[0].exists === true) {
// version table exists
const maxVersion = await db.query(`select max("version")::integer as version from "public"."migrate_log"`);
if (maxVersion.rowCount > 0 && maxVersion.rows[0] && maxVersion.rows[0].version !== null) version = maxVersion.rows[0].version; // eslint-disable-line
} else {
// create version table
await db.query(`create table "public"."migrate_log" (
"version" integer not null primary key,
"created_time" timestamptz not null default now()
);`);
}
console.info(`Database Now Version: ${version}`);
// read all schema files
const schemaList = await fs.promises.readdir(schemaDir);
/**
* @type {{[x: number]: boolean}}
*/
const checkDuplicate = {};
/**
* @type {{version: number, filename: string}[]}
*/
const versionList = schemaList
.map(file => {
const strs = file.split('_');
const v = parseInt(strs[0], 10);
if (isNaN(version)) throw new Error(`schema filename format error (######_name.sql)`); // eslint-disable-line
if (v in checkDuplicate) throw new Error(`schema file version (${v}) is duplicate`);
checkDuplicate[v] = true;
return { version: v, filename: file };
})
.filter(t => t && t.version > version)
.sort((a, b) => a.version - b.version);
// 沒有需要更新的檔案
if (versionList.length === 0) return;
await db.query('begin');
try {
const vers = [];
// write all schema file
for (const it of versionList) {
vers.push(`(${it.version})`);
console.info(`Write Version: ${it.version}`);
const fileContent = await fs.promises.readFile(path.resolve(schemaDir, it.filename), 'utf-8');
await db.query(fileContent);
}
await db.query(`insert into "public"."migrate_log" ("version") values ${vers.join(',')}`);
await db.query('commit');
} catch (err) {
await db.query('rollback');
throw err;
}
})()
.then(() => {
console.info('Database Migrate Finish');
})
.catch(err => {
console.error('Database Migrate Failed, ', err);
process.exit(1);
})
.finally(() => {
db.end();
});

View File

@ -1,58 +0,0 @@
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { padLeft } = require('src/utils/index.js');
const schemaDir = path.resolve(__dirname, '..', 'schemas');
(async () => {
const args = process.argv.slice(2);
let filename = args[0] || '';
if (args.length === 0) {
// use readline
filename = await new Promise(resolve => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.prompt();
rl.question('schema filename: ', ans => {
resolve(ans.replace(' ', '_'));
rl.close();
});
rl.once('close', resolve);
});
}
if (filename === '') throw new Error('no schema filename');
const schemaFiles = await fs.promises.readdir(schemaDir);
let version = 0;
schemaFiles.forEach(name => {
if (!name.endsWith('.sql')) return;
const strInt = name.split(/_/g)[0];
const v = parseInt(strInt, 10);
if (isNaN(v)) return; // eslint-disable-line
if (v > version) version = v;
});
// 版本要比最後一筆加一
version += 1;
const schemaName = `${padLeft(`${version}`, 6, '0')}_${filename}.sql`;
const schemaText = `-- Created Time ${new Date().toISOString()}`;
await fs.promises.writeFile(path.resolve(schemaDir, schemaName), schemaText, 'utf-8');
console.info(`File: ${path.resolve(schemaDir, schemaName)} Created!`);
})().catch(err => {
console.error(err);
process.exit(1);
});

View File

@ -3,14 +3,9 @@ const { env } = process;
module.exports = { module.exports = {
server: { server: {
url: env.SERVER_URL || 'http://localhost:10230', url: env.SERVER_URL || 'http://localhost:10230',
cms_api_url: env.SERVER_CMS_API_URL || 'http://localhost:10230',
port: parseInt(env.SERVER_PORT, 10) || 10230, port: parseInt(env.SERVER_PORT, 10) || 10230,
jwt_secret: env.SERVER_JWT_SECRET || 'testsecret', jwt_secret: env.SERVER_JWT_SECRET || 'testsecret',
jwt_expire: parseInt(env.SERVER_JWT_EXPIRE, 10) || 60 * 60 * 24 * 30, // 30 day jwt_expire: parseInt(env.SERVER_JWT_EXPIRE, 10) || 60 * 60 * 24 * 30, // 30 day
tos_url: env.SERVER_TOS_URL || 'http://localhost:10230',
course_contract_url: env.SERVER_COURSE_CONTRACT_URL || 'http://localhost:10230',
cms_limit_enabled: env.SERVER_CMS_LIMIT_ENABLED !== '0', // 啟用CMS routing 限制
cms_limit_token: env.SERVER_CMS_LIMIT_TOKEN || '',
}, },
redis: { redis: {
host: env.REDIS_HOST || 'localhost', host: env.REDIS_HOST || 'localhost',
@ -26,13 +21,4 @@ module.exports = {
client_id: env.SSO_CLIENT_ID || '', client_id: env.SSO_CLIENT_ID || '',
client_secret: env.SSO_CLIENT_SECRET || '', client_secret: env.SSO_CLIENT_SECRET || '',
}, },
database: {
host: env.DB_HOST || 'localhost',
port: parseInt(env.DB_PORT, 10) || 5432,
user: env.DB_USER || 'postgres',
password: env.DB_PASSWORD || '',
dbname: env.DB_NAME || 'professor_x',
pool_max: parseInt(env.DB_POOL_MAX, 10) || 5,
pool_min: parseInt(env.DB_POOL_MIN, 10) || 2,
},
}; };

View File

@ -4,7 +4,7 @@ const constants = {
OPENID_EXPIRE: 300, // 5min OPENID_EXPIRE: 300, // 5min
INTERNAL_REGULATION_CACHE_TTL: 1800, // 30min INTERNAL_REGULATION_CACHE_TTL: 1800, // 30min
REPORT_CACHE_TTL: 600, // 10 min REPORT_CACHE_TTL: 600, // 10 min
ALLOW_GROUP_ROLE: ['Ironman3'] ALLOW_GROUP_ROLE: ['Ironman3'] // 允許的 Group 身份
}; };
module.exports = constants; module.exports = constants;

View File

@ -1,25 +0,0 @@
const db = require('src/utils/database.js');
class Base {
constructor() {
this.cols = [];
this.schema = 'public';
this.table = '';
this.db = db;
}
async transaction(trxFunc) {
if (typeof trxFunc !== 'function') throw new Error('transaction function type error');
return this.db.transaction(trxFunc);
}
async checkSchema() {
await this.db
.withSchema(this.schema)
.from(this.table)
.select(...this.cols)
.limit(1);
}
}
module.exports = Base;

View File

@ -1,14 +0,0 @@
/* eslint-disable func-names */
const Base = require('./base.js');
class Common extends Base {
constructor() {
super();
}
async test() {
// nothing
}
}
module.exports = Common;

View File

@ -1,25 +0,0 @@
// const debug = require('debug')('models:account');
const Base = require('src/model/base.js');
/**
* @typedef AccountModel
* @property {string} id
* @property {string} phone
* @property {string} password with bcrypt
* @property {string} display_name
* @property {string} secret
* @property {string} created_time
* @property {string} updated_time
*/
class Acconut extends Base {
constructor() {
super();
}
async test() {
}
}
module.exports = Acconut;

View File

@ -5,10 +5,7 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node index.js", "start": "node index.js",
"migrate": "node bin/db-migrate.js",
"test": "mocha --timeout 5000 --exit test/ && jest --passWithNoTests --runInBand --coverage .", "test": "mocha --timeout 5000 --exit test/ && jest --passWithNoTests --runInBand --coverage .",
"test-with-db": "npm run migrate && npm run test",
"new-schema": "node bin/migrate-tool.js",
"postinstall": "node -e \"var s='../',d='node_modules/src',fs=require('fs');fs.exists(d,function(e){e||fs.symlinkSync(s,d,'dir')});\"" "postinstall": "node -e \"var s='../',d='node_modules/src',fs=require('fs');fs.exists(d,function(e){e||fs.symlinkSync(s,d,'dir')});\""
}, },
"keywords": [], "keywords": [],

View File

@ -10,20 +10,3 @@ module.exports = {};
* @property {string} errorMessage api error message (除了prod以外的環境會有) * @property {string} errorMessage api error message (除了prod以外的環境會有)
*/ */
/**
* @typedef Pager
* @description 頁數資訊
* @property {number} page 目前頁數
* @property {number} count 總筆數
* @property {number} total 總頁數
*/
/**
* @typedef Account
* @description API回傳使用者資訊
* @property {string} id 使用者ID
* @property {string} phone 手機
* @property {string} display_name 顯示名稱
* @property {string} created_time 帳號建立時間
* @property {string} updated_time 帳號更新時間
*/

View File

@ -1,50 +0,0 @@
--
-- PostgreSQL database dump
--
-- Dumped from database version 11.7
-- Dumped by pg_dump version 11.7
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: log; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA log;
--
-- Name: ltree; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS ltree WITH SCHEMA public;
--
-- Name: EXTENSION ltree; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION ltree IS 'data type for hierarchical tree-like structures';
--
-- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;
--
-- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions';

View File

@ -1,19 +0,0 @@
const knex = require('knex');
const config = require('src/config/index.js');
const pool = knex({
client: 'pg',
connection: {
user: config.database.user,
password: config.database.password,
host: config.database.host,
port: config.database.port,
database: config.database.dbname,
},
pool: {
max: config.database.pool_max,
min: config.database.pool_min,
},
});
module.exports = pool;

View File

@ -122,45 +122,3 @@ mod.selectObject = (obj, param) => {
return newObj; return newObj;
}; };
/**
* pad string to target length
* @param {any} v source input
* @param {number} len target length
* @param {number} direct pad direct (-1 left, 1 right)
* @param {string} padChar default '0'
* @return {string}
*/
mod.pad = (v, len = 0, direct = -1, padChar = '0') => {
if (v === null || v === undefined) return '';
if (typeof v !== 'string' && !v.toString) return '';
if (direct !== 1 && direct !== -1) return '';
if (typeof v !== 'string') v = v.toString();
if (typeof padChar !== 'string') padChar = '0';
len = mod.toNumber(len, 0, 0);
if (v.length < len) {
if (direct < 0) v = `${padChar}${v}`;
else v = `${v}${padChar}`;
return mod.pad(v, len, direct, padChar);
}
return v;
};
/**
* pad left
* @param {any} v
* @param {number} len
* @param {string} padChar
* @return {string}
*/
mod.padLeft = (v, len = 0, padChar = '0') => mod.pad(v, len, -1, padChar);
/**
* pad right
* @param {any} v
* @param {number} len
* @param {string} padChar
* @return {string}
*/
mod.padRight = (v, len = 0, padChar = '0') => mod.pad(v, len, 1, padChar);

View File

@ -117,8 +117,6 @@ mod.getToken = async (code, state) => {
const decoded = jwt.decode(idToken); const decoded = jwt.decode(idToken);
if (!decoded || typeof decoded !== 'object') throw new Error('jwt decode fail'); if (!decoded || typeof decoded !== 'object') throw new Error('jwt decode fail');
console.log('decoded ::: ', decoded)
console.log('body ::: ', body)
// @ts-ignore // @ts-ignore
const { preferred_username: preferredUsername } = decoded; const { preferred_username: preferredUsername } = decoded;
if (!preferredUsername) throw new Error('id token field missing'); if (!preferredUsername) throw new Error('id token field missing');