0
0

Refactoring

This commit is contained in:
syuilo 2017-05-24 20:50:17 +09:00
parent 5a3cd80973
commit caeba1197c
16 changed files with 84 additions and 206 deletions

View File

@ -52,7 +52,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -51,7 +51,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -51,7 +51,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -86,7 +86,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 365; i++) { for (let i = 0; i < 365; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -84,7 +84,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -56,7 +56,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
const graph = []; const graph = [];
for (let i = 0; i < 30; i++) { for (let i = 0; i < 30; i++) {
let day = new Date(new Date().setDate(new Date().getDate() - i)); const day = new Date(new Date().setDate(new Date().getDate() - i));
const data = datas.filter(d => const data = datas.filter(d =>
d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate() d.date.year == day.getFullYear() && d.date.month == day.getMonth() + 1 && d.date.day == day.getDate()

View File

@ -34,7 +34,7 @@ module.exports = (params, user, app, isSecure) => new Promise(async (res, rej) =
const [value, valueError] = $(params.value).optional.string().$; const [value, valueError] = $(params.value).optional.string().$;
if (valueError) return rej('invalid value param'); if (valueError) return rej('invalid value param');
let set = {}; const set = {};
if (data) { if (data) {
Object.entries(data).forEach(([k, v]) => { Object.entries(data).forEach(([k, v]) => {
set[`data.${k}`] = v; set[`data.${k}`] = v;

View File

@ -36,9 +36,7 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => {
// Fetch files // Fetch files
// forEach だと途中でエラーなどがあっても return できないので // forEach だと途中でエラーなどがあっても return できないので
// 敢えて for を使っています。 // 敢えて for を使っています。
for (let i = 0; i < mediaIds.length; i++) { for (const mediaId of mediaIds) {
const mediaId = mediaIds[i];
// Fetch file // Fetch file
// SELECT _id // SELECT _id
const entity = await DriveFile.findOne({ const entity = await DriveFile.findOne({
@ -188,7 +186,7 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => {
} }
}); });
let mentions = []; const mentions = [];
function addMention(mentionee, type) { function addMention(mentionee, type) {
// Reject if already added // Reject if already added

View File

@ -13,14 +13,6 @@ class MisskeyEvent {
config.redis.port, config.redis.host); config.redis.port, config.redis.host);
} }
private publish(channel: string, type: string, value?: any): void {
const message = value == null ?
{ type: type } :
{ type: type, body: value };
this.redisClient.publish(`misskey:${channel}`, JSON.stringify(message));
}
public publishUserStream(userId: ID, type: string, value?: any): void { public publishUserStream(userId: ID, type: string, value?: any): void {
this.publish(`user-stream:${userId}`, type, typeof value === 'undefined' ? null : value); this.publish(`user-stream:${userId}`, type, typeof value === 'undefined' ? null : value);
} }
@ -32,6 +24,14 @@ class MisskeyEvent {
public publishMessagingStream(userId: ID, otherpartyId: ID, type: string, value?: any): void { public publishMessagingStream(userId: ID, otherpartyId: ID, type: string, value?: any): void {
this.publish(`messaging-stream:${userId}-${otherpartyId}`, type, typeof value === 'undefined' ? null : value); this.publish(`messaging-stream:${userId}-${otherpartyId}`, type, typeof value === 'undefined' ? null : value);
} }
private publish(channel: string, type: string, value?: any): void {
const message = value == null ?
{ type: type } :
{ type: type, body: value };
this.redisClient.publish(`misskey:${channel}`, JSON.stringify(message));
}
} }
const ev = new MisskeyEvent(); const ev = new MisskeyEvent();

View File

@ -22,7 +22,7 @@ export const path = process.env.NODE_ENV == 'test'
/** /**
* *
*/ */
interface Source { type Source = {
maintainer: string; maintainer: string;
url: string; url: string;
secondary_url: string; secondary_url: string;
@ -68,12 +68,12 @@ interface Source {
hook_secret: string; hook_secret: string;
username: string; username: string;
}; };
} };
/** /**
* Misskeyが自動的に() * Misskeyが自動的に()
*/ */
interface Mixin { type Mixin = {
host: string; host: string;
scheme: string; scheme: string;
secondary_host: string; secondary_host: string;
@ -83,7 +83,7 @@ interface Mixin {
about_url: string; about_url: string;
dev_url: string; dev_url: string;
drive_url: string; drive_url: string;
} };
export type Config = Source & Mixin; export type Config = Source & Mixin;

View File

@ -87,7 +87,7 @@ async function init(): Promise<Config> {
MachineInfo.show(); MachineInfo.show();
new DependencyInfo().showAll(); new DependencyInfo().showAll();
let configLogger = new Logger('Config'); const configLogger = new Logger('Config');
if (!fs.existsSync(configPath)) { if (!fs.existsSync(configPath)) {
throw 'Configuration not found - Please run "npm run config" command.'; throw 'Configuration not found - Please run "npm run config" command.';
} }
@ -109,7 +109,7 @@ async function init(): Promise<Config> {
*/ */
// Try to connect to MongoDB // Try to connect to MongoDB
let mongoDBLogger = new Logger('MongoDB'); const mongoDBLogger = new Logger('MongoDB');
const db = require('./db/mongodb').default; const db = require('./db/mongodb').default;
mongoDBLogger.info('Successfully connected'); mongoDBLogger.info('Successfully connected');
db.close(); db.close();

View File

@ -2,19 +2,19 @@ import Logger from './logger';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
export default class { export default class {
logger: Logger; private logger: Logger;
constructor() { constructor() {
this.logger = new Logger('Deps'); this.logger = new Logger('Deps');
} }
showAll(): void { public showAll(): void {
this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/)); this.show('MongoDB', 'mongo --version', x => x.match(/^MongoDB shell version:? (.*)\r?\n/));
this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/)); this.show('Redis', 'redis-server --version', x => x.match(/v=([0-9\.]*)/));
this.show('GraphicsMagick', 'gm -version', x => x.match(/^GraphicsMagick ([0-9\.]*) .*/)); this.show('GraphicsMagick', 'gm -version', x => x.match(/^GraphicsMagick ([0-9\.]*) .*/));
} }
show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void { public show(serviceName: string, command: string, transform: (x: string) => RegExpMatchArray): void {
try { try {
// ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので // ステータス0以外のときにexecSyncはstderrをコンソール上に出力してしまうので
// プロセスからのstderrをすべて無視するように stdio オプションをセット // プロセスからのstderrをすべて無視するように stdio オプションをセット

View File

@ -1,10 +1,11 @@
import Logger from './logger'; import Logger from './logger';
export default class { export default class {
static show(): void { public static show(): void {
const env = process.env.NODE_ENV; const env = process.env.NODE_ENV;
let logger = new Logger('Env'); const logger = new Logger('Env');
logger.info(typeof env == 'undefined' ? 'NODE_ENV is not set' : `NODE_ENV: ${env}`); logger.info(typeof env == 'undefined' ? 'NODE_ENV is not set' : `NODE_ENV: ${env}`);
if (env !== 'production') { if (env !== 'production') {
logger.warn('The environment is not in production mode'); logger.warn('The environment is not in production mode');
logger.warn('Do not use for production purpose'); logger.warn('Do not use for production purpose');

View File

@ -11,43 +11,43 @@ function toLevelColor(level: LogLevel): chalk.ChalkStyle {
} }
export default class Logger { export default class Logger {
domain: string; private domain: string;
static log(level: LogLevel, message: string): void {
let color = toLevelColor(level);
let time = (new Date()).toLocaleTimeString('ja-JP');
console.log(`[${time} ${color.bold(level.toUpperCase())}]: ${message}`);
}
static error(message: string): void {
Logger.log('Error', message);
}
static warn(message: string): void {
Logger.log('Warn', message);
}
static info(message: string): void {
Logger.log('Info', message);
}
constructor(domain: string) { constructor(domain: string) {
this.domain = domain; this.domain = domain;
} }
log(level: LogLevel, message: string): void { public static log(level: LogLevel, message: string): void {
const color = toLevelColor(level);
const time = (new Date()).toLocaleTimeString('ja-JP');
console.log(`[${time} ${color.bold(level.toUpperCase())}]: ${message}`);
}
public static error(message: string): void {
Logger.log('Error', message);
}
public static warn(message: string): void {
Logger.log('Warn', message);
}
public static info(message: string): void {
Logger.log('Info', message);
}
public log(level: LogLevel, message: string): void {
Logger.log(level, `[${this.domain}] ${message}`); Logger.log(level, `[${this.domain}] ${message}`);
} }
error(message: string): void { public error(message: string): void {
this.log('Error', message); this.log('Error', message);
} }
warn(message: string): void { public warn(message: string): void {
this.log('Warn', message); this.log('Warn', message);
} }
info(message: string): void { public info(message: string): void {
this.log('Info', message); this.log('Info', message);
} }
} }

View File

@ -2,10 +2,10 @@ import * as os from 'os';
import Logger from './logger'; import Logger from './logger';
export default class { export default class {
static show(): void { public static show(): void {
const totalmem = (os.totalmem() / 1024 / 1024 / 1024).toFixed(1); const totalmem = (os.totalmem() / 1024 / 1024 / 1024).toFixed(1);
const freemem = (os.freemem() / 1024 / 1024 / 1024).toFixed(1); const freemem = (os.freemem() / 1024 / 1024 / 1024).toFixed(1);
let logger = new Logger('Machine'); const logger = new Logger('Machine');
logger.info(`Hostname: ${os.hostname()}`); logger.info(`Hostname: ${os.hostname()}`);
logger.info(`Platform: ${process.platform}`); logger.info(`Platform: ${process.platform}`);
logger.info(`Architecture: ${process.arch}`); logger.info(`Architecture: ${process.arch}`);

View File

@ -1,153 +1,32 @@
{ {
"rules": { "defaultSeverity": "error",
// TypeScript Specific "extends": [
"ban-types": [ "tslint:recommended"
true, ],
[ "jsRules": {},
"Object" "rules": {
] "indent": ["tab"],
], "quotemark": ["single"],
"member-access": false, "no-var-requires": false,
"member-ordering": [ "no-string-throw": false,
true, "trailing-comma": [false],
"static-before-instance", "object-literal-sort-keys": false,
"variables-before-functions" "curly": false,
], "no-console": [false],
"no-any": false, "ordered-imports": [false],
"no-import-side-effect": true, "arrow-parens": false,
"no-inferrable-types": false, "object-literal-shorthand": false,
"no-internal-module": false, "triple-equals": [false],
"no-namespace": false, "no-shadowed-variable": false,
"no-non-null-assertion": true, "no-string-literal": false,
"no-reference": true, "variable-name": [false],
"no-var-requires": false, "comment-format": [false],
"only-arrow-functions": false, "interface-over-type-literal": false,
"typedef": [ "max-line-length": [false],
true, "member-ordering": [false],
"property-declaration" "ban-types": [
], "Object"
"typedef-whitespace": [ ]
true, },
{ "rulesDirectory": []
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
// Functionality
"ban": false,
"curly": false,
"forin": true,
"label-position": true,
"no-arg": true,
"no-bitwise": true,
"no-conditional-assignment": true,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-super": true,
"no-duplicate-variable": true,
"no-empty": true,
"no-eval": false,
"no-for-in-array": false,
"no-invalid-this": [
true,
"check-function-in-method"
],
"no-misused-new": true,
"no-null-keyword": false,
"no-shadowed-variable": false,
"no-string-literal": false,
"no-switch-case-fall-through": true,
"no-unsafe-finally": true,
"no-unused-expression": true,
"no-use-before-declare": false,
"no-var-keyword": true,
"radix": true,
"restrict-plus-operands": false,
"switch-default": false,
"triple-equals": [
false,
"allow-null-check",
"allow-undefined-check"
],
"use-isnan": true,
// Maintainability
"eofline": true,
"indent": [
true,
"tabs"
],
"linebreak-style": false,
"max-file-line-count": false,
"max-line-length": false,
"no-default-export": false,
"no-mergeable-namespace": true,
"no-require-imports": false,
"no-reference-import": true,
"no-trailing-whitespace": true,
"no-unnecessary-callback-wrapper": true,
"no-unnecessary-initializer": true,
"object-literal-sort-keys": false,
"trailing-comma": true,
// Style
"align": [
true,
"parameters",
"statements"
],
"arrow-parens": false,
"arrow-return-shorthand": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"interface-name": false,
"jsdoc-format": true,
"match-default-export-name": false,
"newline-before-return": false,
"new-parens": true,
"no-angle-bracket-type-assertion": true,
"no-consecutive-blank-lines": true,
"object-literal-key-quotes": false,
"one-line": [
true,
"check-catch",
"check-finally",
"check-else",
"check-open-brace",
"check-whitespace"
],
"one-variable-per-declaration": true,
"ordered-imports": false,
"prefer-function-over-method": true,
"prefer-method-signature": true,
"prefer-template": true,
"quotemark": [
true,
"single",
"avoid-escape"
],
"semicolon": true,
"variable-name": false,
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type",
"check-preblock"
]
}
} }