You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
2.9 KiB

import fastify from 'fastify'
import dotenv from 'dotenv'
import path from 'path'
// getting .env
dotenv.config({ path: path.join(path.resolve(), '/../../.env') })
// create server
const server = fastify()
/**
* add liquidjs
*
*
*/
import * as Eta from 'eta'
import view from '@fastify/view'
import { asset, templateClass, isHome, injectStore, mediaUrl } from './helpers/eta.js'
import { marked } from 'marked'
server.register(view, {
engine: {
eta: Eta
},
root: path.join(path.resolve(), '/../frontend/views'),
extname: '.eta',
// adding function to templates
defaultContext: {
asset: asset,
templateClass: templateClass,
isHome: isHome,
injectStore: injectStore,
marked: marked,
mediaUrl: mediaUrl
},
options: {
tags: [ '{{', '}}' ],
includeViewExtension: true,
parse: {
exec: "#",
interpolate: "",
raw: "!"
},
useWith: true,
async: true
}
})
/**
* adding preHandler
*
*
*/
import SettingsStore from './stores/settings.js'
// getting options from directus add to all views
server.addHook('preHandler', async function (request, response) {
const settingsStore = new SettingsStore()
const settings = await settingsStore.find()
response.locals.settings = settings
})
// check url for paged
server.addHook('onRequest', async function (request, response) {
const url = request.url
let pathname = url.split('/').shift()
// default value for paged
let paged = 1
// check if pathname has values and is not 404
if (pathname.length > 0 && request.url !== '/404') {
const result = Number(pathname[pathname.length - 1])
// is result is an integer
if (Number.isInteger(result)) {
paged = result
// remove last from pathname, add default url to request,
// and check if pathname has more than one, join pathname for new url
pathname.pop()
request.raw.url = '/'
if (pathname.length > 0) {
request.raw.url = pathname.join('/')
}
}
}
// adding to response
response.locals = {
paged : paged
}
})
/**
* routing
*
*
*/
import commentHttp from './http/api/comment.js'
import notfoundHttp from './http/notfound.js'
import postHttp from './http/post.js'
// page and static has always the last routes, if no route before match, it try get a page
import sitemapHttp from './http/sitemap.js'
import pageHttp from './http/page.js'
import publicHttp from './http/public.js'
server
.register(commentHttp, {
'prefix': '/api/comment/v1/'
})
.register(notfoundHttp)
.register(postHttp, {
'prefix': '/blog'
})
.register(sitemapHttp)
.register(pageHttp)
.register(publicHttp)
export default server