better code: split files

Massimo Melina committed Jan 2, 2022 at 23:34 UTC 368bf38766375a892b50943307dc9955e1927e8b
3 files changed +32 -12
src/index.ts
+2 -12
@@ -16,8 +16,7 @@ import { subscribe } from './config'
16 import session from 'koa-session'
17 import { zipStreamFromFolder } from './zip'
18 import { frontEndApis } from './frontEndApis'
19 -import { createWriteStream } from 'fs'
20 -import { Writable } from 'stream'
19 +import { log } from './log'
20
21 const BUILD_TIMESTAMP = ""
22
@@ -30,16 +29,7 @@ app.use(session({
29 rolling: true,
30 maxAge: 30*60_000,
31 }, app))
33 -
34 -let logMw: Koa.Middleware
35 -let logStream: Writable
36 -subscribe('log', path => {
37 - console.debug('log file: '+(path || 'disabled'))
38 - logStream?.end()
39 - logStream = path && createWriteStream(path, { flags:'a' })
40 - logMw = accesslog(logStream)
41 -}, 'access.log')
42 -app.use((ctx, next) => logMw?.(ctx,next)) // wrapping in a function will make it use current value
32 +app.use(log())
33
34 // serve apis
35 app.use(mount(API_URI, new Koa()
src/log.ts new
+29
@@ -0,0 +1,29 @@
1 +import Koa from 'koa'
2 +import { Writable } from 'stream'
3 +import { subscribe } from './config'
4 +import { createWriteStream } from 'fs'
5 +// @ts-ignore
6 +import accesslog from 'koa-accesslog'
7 +
8 +class Logger {
9 + mw?: Koa.Middleware
10 + stream?: Writable
11 + setPath(path: string) {
12 + this.stream?.end()
13 + if (!path)
14 + return this.mw = this.stream = undefined
15 + this.stream = createWriteStream(path, { flags: 'a' })
16 + this.mw = accesslog(this.stream)
17 + }
18 +}
19 +const accessLogger = new Logger()
20 +
21 +subscribe('log', path => {
22 + console.debug('log file: ' + (path || 'disabled'))
23 + accessLogger.setPath(path)
24 +}, 'access.log')
25 +
26 +export function log(): Koa.Middleware {
27 + return (ctx, next) => // wrapping in a function will make it use current value
28 + accessLogger.mw?.(ctx, next)
29 +}
todo.md
+1
@@ -19,6 +19,7 @@
19 - vfs: ability to remove/hide/rename files deep in a source
20 - administration interface
21 - log: ip2name
22 +- apis in separated log file with parameters?
23 - errors in separated log file
24 - login without passing clear text password?
25 we could use asymmetric encryption, possibly on a hashed password, that means