import { LayServer } from '../src'; import { resolve } from 'path'; import Html from '../src/Views/Html'; import Markdown from '../src/Views/Markdown'; import Placekeeper from '../src/Utils/Placekeeper'; import Storage from '../src/Utils/Storage'; const storage = new Storage({ baseDir: resolve(__dirname) }); const Templater = new Placekeeper({ cacheDir: '.cache', disableCache: true, storage, onError(err) { // console.error(err, err.stack); } }); const APP_PORT = Bun.env.APP_PORT ?? Bun.env.PORT ?? 3000; class InfoController { static namespace = 'info'; constructor(server) { server.get('/', this.index); server.get('/:country', this.countryInfo); server.get('/multiple/:a/:a/:a', this.multiple); } index(req, res) { return res.json({ headers: req.headers }) res.text('I think you are right here now go here'); } countryInfo(req, res) { res.json({ name: req.params.get('country'), description: `the country is ${req.params.get('country')}`, params: [...req.params.entries()], }); } multiple(req, res) { res.json({ params: [...req.params], }); } } const server = new LayServer({ port: APP_PORT, viewPaths: [ resolve(__dirname, 'views'), resolve(__dirname, 'contents') ], publicDir: resolve(__dirname, 'public'), publicFiles: [ resolve(__dirname, 'public', 'main.css'), ], discoverPublicFiles: true, layout: 'intro.html', loaders: new Map([ ['html', new Html(Templater)], ['md', new Markdown(Templater)], ]), controllers: [ function Main(server) { server.get('/', async (req, res) => { return res.json({message: 'hello world'}); }, { domain: 'example.layc.dev' }); server.all('/data', (req, res) => { let respBody = `your ${req.method} request was well recieved`; switch (req.method) { case 'POST': case 'PUT': return { message: respBody, data: { body: req.body, }, }; case 'PATCH': respBody = `we can try but i think there is no way to ${req.method} this out.`; break; case 'DELETE': respBody = 'What do you want to delete?'; break; case 'OPTIONS': respBody = `I guess, we are out of ${req.method}. 💩`; break; case 'HEAD': respBody = `this response has not really a body but a big ${req.method}`; break; } return new Response(respBody, { status: 200, }); }); server.get('/contact', (req, res) => { return new Response('This is how you remind me!', { status: 200, }); }); }, InfoController, ], }); server.get('/', async (req, res) => { return res.send('welcome home', { layout: false, title: 'Smart title or so', locale: 'en' }); }); server.get('/blog/:slug', async (req, res) => { try { return res.layout('index.html') .render(`blog/${req.params.get('slug').toString()}.md`); } catch(err) { return new Response('not found', {status: 404}); } }); server.use(async (req, res) => { return res.send('404 page is here', { title: 'Page not Found: 404' }).status(404); }) server.listen(APP_PORT, () => { console.log(`listen on ${APP_PORT}`); });