Permalink
Browse files

feat(logger): enable logger to database

  • Loading branch information...
jkuri committed Sep 4, 2017
1 parent 31d6c1f commit dced1feaf684348a0fb4f98c61fd2e7d0b086688
Showing with 173 additions and 74 deletions.
  1. +49 −1 package-lock.json
  2. +2 −0 package.json
  3. +64 −2 src/api/commit-status.ts
  4. +6 −6 src/api/db/config.ts
  5. +33 −0 src/api/db/log.ts
  6. +7 −0 src/api/db/migrations.ts
  7. +5 −0 src/api/db/model.ts
  8. +7 −3 src/api/logger.ts
  9. +0 −62 src/api/utils.ts

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
@@ -77,6 +77,7 @@
"@types/chalk": "^0.4.31",
"@types/cors": "^2.8.1",
"@types/express": "^4.0.37",
"@types/express-session": "^1.15.3",
"@types/jasmine": "^2.5.54",
"@types/jsonwebtoken": "^7.2.3",
"@types/knex": "0.0.59",
@@ -115,6 +116,7 @@
"date-fns": "^1.28.5",
"enhanced-resolve": "^3.4.1",
"express": "^4.15.4",
"express-session": "^1.15.5",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^0.11.2",
"fs-extra": "^4.0.1",
@@ -1,6 +1,7 @@
import { sendRequest, getBitBucketAccessToken, getConfig } from './utils';
import { getBitBucketAccessToken, getConfig } from './utils';
import * as logger from './logger';
import { yellow, red, blue, bold } from 'chalk';
import { yellow, red, blue, bold, cyan } from 'chalk';
import * as request from 'request';

export function sendSuccessStatus(build: any, buildId: number): Promise<void> {
const config: any = getConfig();
@@ -331,3 +332,64 @@ function setBitbucketStatusFailure(
})
.catch(err => Promise.reject(err));
}

function sendRequest(url: string, data: any, headers: any): Promise<any> {
return new Promise((resolve, reject) => {
let options = {
url: url,
method: 'POST',
headers: headers,
json: data
};

let msg = [
yellow('['),
cyan('http'),
yellow(']'),
' --- ',
yellow(`sending ${options.method} request to ${bold(url)}...`)
].join('');
logger.info(msg);

request(options, (err, response, body) => {
if (err) {
let msg = [
yellow('['),
cyan('http'),
yellow(']'),
' --- ',
red(`sending request to ${bold(url)} failed (${err})`)
].join('');
logger.error(msg);

reject(err);
} else {
if (response.statusCode < 300 && response.statusCode >= 200) {
let msg = [
yellow('['),
cyan('http'),
yellow(']'),
' --- ',
yellow(`sending request to ${bold(url)} successful (${response.statusCode})`)
].join('');
logger.info(msg);
resolve(body);
} else {
let msg = [
yellow('['),
cyan('http'),
yellow(']'),
' --- ',
red(`sending request to ${bold(url)} failed (${response.statusCode})`)
].join('');
logger.error(msg);

reject({
statusCode: response.statusCode,
response: body
});
}
}
});
});
}
@@ -1,22 +1,22 @@
import * as bookshelf from 'bookshelf';
import * as knex from 'knex';
import { configExists, writeDefaultConfig, getConfig, getFilePath } from '../utils';
import * as utils from '../utils';
import * as jsonColumns from 'bookshelf-json-columns';

if (!configExists()) {
writeDefaultConfig();
if (!utils.configExists()) {
utils.writeDefaultConfig();
}

let config: any = getConfig();
let config: any = utils.getConfig();
let dbConfig = Object.assign({}, config.db, {
migrations: {
tableName: 'knex_migrations',
directory: getFilePath('migrations')
directory: utils.getFilePath('migrations')
}
});

if (dbConfig.connection.filename) {
dbConfig.connection.filename = getFilePath(dbConfig.connection.filename);
dbConfig.connection.filename = utils.getFilePath(dbConfig.connection.filename);
}

export let Knex: knex = knex(dbConfig);
@@ -0,0 +1,33 @@
import { Log } from './model';

export interface LogType {
type: 'info' | 'warning' | 'error';
message: string;
}

export function insertLog(data: LogType): Promise<any> {
return new Promise((resolve, reject) => {
new Log(data).save(null, { method: 'insert' })
.then(log => !log ? reject(log) : resolve(log.toJSON()));
});
}

export function getLogs(
limit: number,
offset: number,
type?: 'info' | 'warning' | 'error'
): Promise<any[]> {
return new Promise((resolve, reject) => {
new Log().query(q => {
if (type) {
q.where('type', type);
}

q.orderBy('id', 'desc');
q.limit(limit);
q.offset(offset);
})
.fetchAll()
.then(logs => !logs ? reject(logs) : resolve(logs.toJSON()));
});
}
@@ -98,6 +98,13 @@ export function create(): Promise<null> {
t.boolean('permission').notNullable().defaultTo(true);
t.timestamps();
}))
.then(() => schema.createTableIfNotExists('logs', (t: knex.TableBuilder) => {
t.increments('id').unsigned().primary();
t.enum('type', ['info', 'warning', 'error']).notNullable();
t.text('message').notNullable();
t.boolean('read').notNullable().defaultTo(false);
t.timestamps();
}))
.then(() => resolve())
.catch(err => {
console.error(err);
@@ -58,3 +58,8 @@ export class Permission extends Bookshelf.Model<any> {
repository() { return this.belongsTo(Repository, 'repositories_id'); }
user() { return this.belongsTo(User, 'users_id'); }
}

export class Log extends Bookshelf.Model<any> {
get tableName() { return 'logs'; }
get hasTimestamps() { return true; }
}
@@ -1,18 +1,22 @@
import { red, green, blue, magenta, cyan, yellow, white } from 'chalk';
import { insertLog } from './db/log';

export function info(msg: string): void {
const time = getDateTime();
console.log(`${green('[' + time + ']')} ${white(msg)}`);
insertLog({ message: msg, type: 'info' })
.then(() => console.log(`${green('[' + time + ']')} ${white(msg)}`));
}

export function error(msg: string | any): void {
const time = getDateTime();
console.log(`${green('[' + time + ']')} ${red(msg)}`);
insertLog({ message: msg, type: 'error' })
.then(() => console.log(`${green('[' + time + ']')} ${red(msg)}`));
}

export function warning(msg: string): void {
const time = getDateTime();
console.log(`${green('[' + time + ']')} ${yellow(msg)}`);
insertLog({ message: msg, type: 'warning' })
.then(() => console.log(`${green('[' + time + ']')} ${yellow(msg)}`));
}

function getDateTime(): string {
@@ -7,7 +7,6 @@ import { Observable } from 'rxjs';
import * as uuid from 'uuid';
import * as request from 'request';
import * as temp from 'temp';
import * as logger from './logger';
import { blue, yellow, magenta, cyan, bold, red } from 'chalk';

const defaultConfig = {
@@ -211,64 +210,3 @@ export function getBitBucketAccessToken(clientCredentials: string): Promise<any>
});
});
}

export function sendRequest(url: string, data: any, headers: any): Promise<any> {
return new Promise((resolve, reject) => {
let options = {
url: url,
method: 'POST',
headers: headers,
json: data
};

let msg = [
yellow('['),
blue('http'),
yellow(']'),
' --- ',
yellow(`sending ${options.method} request to ${bold(url)}...`)
].join('');
logger.info(msg);

request(options, (err, response, body) => {
if (err) {
let msg = [
yellow('['),
blue('http'),
yellow(']'),
' --- ',
red(`sending request to ${bold(url)} failed (${err})`)
].join('');
logger.error(msg);

reject(err);
} else {
if (response.statusCode < 300 && response.statusCode >= 200) {
let msg = [
yellow('['),
blue('http'),
yellow(']'),
' --- ',
yellow(`sending request to ${bold(url)} successful (${response.statusCode})`)
].join('');
logger.info(msg);
resolve(body);
} else {
let msg = [
yellow('['),
blue('http'),
yellow(']'),
' --- ',
red(`sending request to ${bold(url)} failed (${response.statusCode})`)
].join('');
logger.error(msg);

reject({
statusCode: response.statusCode,
response: body
});
}
}
});
});
}

0 comments on commit dced1fe

Please sign in to comment.