nfp_sites/api/server.mjs

79 lines
2.2 KiB
JavaScript
Raw Normal View History

import { Flaska, QueryHandler } from 'flaska'
2022-04-05 16:47:24 +00:00
2022-06-16 22:44:43 +00:00
import { initPool } from './db.mjs'
2022-04-05 16:47:24 +00:00
import config from './config.mjs'
import PageRoutes from './page/routes.mjs'
import ServeHandler from './serve.mjs'
2022-04-19 15:51:47 +00:00
// import ArticleRoutes from './article/routes.mjs'
import ParserMiddleware from './pagination/parser.mjs'
2022-04-05 14:43:23 +00:00
export function run(http, port, core) {
let localUtil = new core.sc.Util(import.meta.url)
// Create our server
2022-04-05 14:43:23 +00:00
const flaska = new Flaska({
log: core.log,
2022-04-05 16:47:24 +00:00
nonce: ['script-src'],
nonceCacheLength: 50,
2022-04-05 14:43:23 +00:00
}, http)
2022-06-16 22:44:43 +00:00
// Create our database pool
2022-06-16 22:44:43 +00:00
let pool = initPool(core, config.get('mssql'))
// configure our server
2022-04-05 16:47:24 +00:00
if (config.get('NODE_ENV') === 'development') {
flaska.devMode()
}
const parser = new ParserMiddleware()
2022-04-05 14:43:23 +00:00
flaska.before(function(ctx) {
ctx.state.started = new Date().getTime()
ctx.db = pool
2022-04-05 14:43:23 +00:00
})
2022-04-05 16:47:24 +00:00
flaska.before(QueryHandler())
flaska.before(parser.contextParser())
2022-04-05 14:43:23 +00:00
//
2022-04-05 14:43:23 +00:00
flaska.after(function(ctx) {
let ended = new Date().getTime()
var requestTime = ended - ctx.state.started
let status = ''
let level = 'info'
if (ctx.status >= 400) {
status = ctx.status + ' '
level = 'warn'
}
if (ctx.status >= 500) {
level = 'error'
}
ctx.log[level]({
duration: requestTime,
status: ctx.status,
}, `<-- ${status}${ctx.method} ${ctx.url}`)
})
2022-04-05 16:47:24 +00:00
const page = new PageRoutes()
flaska.get('/api/pagetree', page.getPageTree.bind(page))
2022-06-28 08:15:51 +00:00
flaska.get('/api/frontpage', page.getPage.bind(page))
flaska.get('/api/pages/:path', page.getPage.bind(page))
2022-04-19 15:51:47 +00:00
// flaska.get('/api/pages/:pageId', page.getSinglePage.bind(page))
2022-04-05 16:47:24 +00:00
2022-04-19 15:51:47 +00:00
// const article = new ArticleRoutes()
// flaska.get('/api/articles/public', article.getPublicAllArticles.bind(article))
// flaska.get('/api/articles/public/:id', article.getPublicSingleArticle.bind(article))
// flaska.get('/api/pages/:pageId/articles/public', article.getPublicAllPageArticles.bind(article))
2022-04-05 14:43:23 +00:00
const serve = new ServeHandler({
root: localUtil.getPathFromRoot('../public'),
2022-06-16 22:44:43 +00:00
version: core.app.running,
frontend: config.get('frontend:url'),
2022-04-05 14:43:23 +00:00
})
flaska.get('/::file', serve.serve.bind(serve))
2022-04-05 14:43:23 +00:00
return flaska.listenAsync(port).then(function() {
core.log.info('Server is listening on port ' + port)
})
}