|
| 1 | +import type { |
| 2 | + Context, |
| 3 | + RouteParams, |
| 4 | + State, |
| 5 | +} from "https://deno.land/x/oak@v10.5.1/mod.ts"; |
| 6 | + |
| 7 | +import type { ViewConfig,Adapter,Engine } from "../../viewEngine.type.ts"; |
| 8 | +import { getTemplate } from "./oak.utils.ts"; |
| 9 | + |
| 10 | +declare module "https://deno.land/x/oak@v10.5.1/mod.ts" { |
| 11 | + // App level Context |
| 12 | + interface Context { |
| 13 | + render: (fileName: string, data?: object) => void; |
| 14 | + } |
| 15 | + |
| 16 | + // Router level Context |
| 17 | + interface RouterContext< |
| 18 | + R extends string, |
| 19 | + P extends RouteParams<R> = RouteParams<R>, |
| 20 | + // deno-lint-ignore no-explicit-any |
| 21 | + S extends State = Record<string, any> |
| 22 | + > { |
| 23 | + render: (fileName: string, data?: object) => void; |
| 24 | + } |
| 25 | + |
| 26 | + // add viewConfig to Application interface |
| 27 | + interface Application { |
| 28 | + viewConcig: ViewConfig; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +//! Add `render` function to Context |
| 33 | +export const oakAdapter: Adapter = ( |
| 34 | + renderEngine: Engine, |
| 35 | + config: ViewConfig = <ViewConfig>{} |
| 36 | +) => { |
| 37 | + return async function (ctx: Context, next: Function) { |
| 38 | + // load default view setting |
| 39 | + if (!ctx.app.viewConcig) { |
| 40 | + ctx.app.viewConcig = { |
| 41 | + viewEngine: config.viewEngine, |
| 42 | + viewRoot: config.viewRoot ?? "./", |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + ctx.render = async function (fileName: string, data?: object) { |
| 47 | + try { |
| 48 | + const viewConfig = ctx.app.viewConcig; |
| 49 | + |
| 50 | + // find template file path, either on internet or in local file system |
| 51 | + let template = await getTemplate(viewConfig.viewRoot!, fileName); |
| 52 | + |
| 53 | + ctx.response.headers.set("Content-Type", "text/html; charset=utf-8"); |
| 54 | + ctx.response.body = await renderEngine( |
| 55 | + template, |
| 56 | + data ?? {}, |
| 57 | + ctx.app.viewConcig, |
| 58 | + fileName |
| 59 | + ); |
| 60 | + } catch (e) { |
| 61 | + ctx.response.status = 404; |
| 62 | + console.error("View-Engine: ", e.message); |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + await next(); |
| 67 | + }; |
| 68 | +}; |
0 commit comments