cometa/app.ts

78 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-01-19 18:52:30 +01:00
import * as path from 'path'
import * as util from './util'
import * as parser from './parser'
2018-02-06 20:00:09 +01:00
import * as compiler from './compiler'
import { Compiled, LOG_TYPE, options } from './options'
2018-01-19 18:52:30 +01:00
2018-02-06 20:00:09 +01:00
const cache: Map<string, Compiled> = new Map()
2018-01-19 18:52:30 +01:00
function logger(type: LOG_TYPE, msg: object | string): void {
if (typeof msg === 'object')
msg = JSON.stringify(msg)
let typeString: string = ''
switch (type) {
case LOG_TYPE.Info:
typeString = 'Info'
break
case LOG_TYPE.Warning:
typeString = 'Warning'
break
case LOG_TYPE.Error:
typeString = 'Error'
break
}
console.log(`${typeString}:`, msg)
}
2018-02-06 20:00:09 +01:00
async function compile(html: string): Promise<Compiled> {
2018-01-19 18:52:30 +01:00
return {
2018-02-06 20:00:09 +01:00
template: compiler.process(html),
2018-01-19 18:52:30 +01:00
hash: await util.checksum(html, true),
time: Date.now()
}
}
2018-02-06 20:00:09 +01:00
async function render(template_name: string, data?: any): Promise<string> {
// const compiled_path = path.join(options.compiled_dir, `${template_name}.${options.compiled_ext}`)
const template_path = path.join(options.template_dir, `${template_name}.${options.template_ext}`)
2018-01-19 18:52:30 +01:00
2018-02-06 20:00:09 +01:00
// Compile Template if is not in cache
if (options.caching && !cache.get(template_name)) {
2018-01-19 18:52:30 +01:00
const html = await util.readFile(template_path)
2018-02-06 20:00:09 +01:00
if (html !== undefined)
cache.set(template_name, await compile(html))
else {
2018-01-19 18:52:30 +01:00
logger(LOG_TYPE.Error, 'No file found')
2018-02-06 20:00:09 +01:00
return ''
2018-01-19 18:52:30 +01:00
}
}
2018-02-06 20:00:09 +01:00
const compiled = cache.get(template_name)
if (compiled)
return parser.computeParts(compiled.template, data)
2018-01-19 18:52:30 +01:00
else
2018-02-06 20:00:09 +01:00
return ''
2018-01-19 18:52:30 +01:00
}
async function go() {
2018-02-06 20:00:09 +01:00
const ret = await render('new', {
test: true,
testa: true,
title: 'test',
2018-01-19 18:52:30 +01:00
body: {
p: [
'omg',
{
2018-01-21 23:03:04 +01:00
check: 'let goo'
2018-01-19 18:52:30 +01:00
}
]
},
2018-02-06 20:00:09 +01:00
})
ret.log()
2018-01-19 18:52:30 +01:00
}
go()